PackageManagerService.java revision 3a44f3f1b446315ef894e01d2ab9b5388c2bd8c4
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.Manifest.permission.INSTALL_PACKAGES;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.os.Process.PACKAGE_INFO_GID;
28import static android.os.Process.SYSTEM_UID;
29import static android.system.OsConstants.S_IRGRP;
30import static android.system.OsConstants.S_IROTH;
31import static android.system.OsConstants.S_IRWXU;
32import static android.system.OsConstants.S_IXGRP;
33import static android.system.OsConstants.S_IXOTH;
34import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
35import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
36import static com.android.internal.util.ArrayUtils.appendInt;
37import static com.android.internal.util.ArrayUtils.removeInt;
38
39import com.android.internal.R;
40import com.android.internal.app.IMediaContainerService;
41import com.android.internal.app.ResolverActivity;
42import com.android.internal.content.NativeLibraryHelper;
43import com.android.internal.content.PackageHelper;
44import com.android.internal.util.FastPrintWriter;
45import com.android.internal.util.FastXmlSerializer;
46import com.android.internal.util.XmlUtils;
47import com.android.server.EventLogTags;
48import com.android.server.IntentResolver;
49import com.android.server.LocalServices;
50import com.android.server.ServiceThread;
51import com.android.server.Watchdog;
52import com.android.server.pm.Settings.DatabaseVersion;
53import com.android.server.storage.DeviceStorageMonitorInternal;
54import com.android.server.storage.DeviceStorageMonitorInternal;
55
56import org.xmlpull.v1.XmlPullParser;
57import org.xmlpull.v1.XmlPullParserException;
58import org.xmlpull.v1.XmlSerializer;
59
60import android.app.ActivityManager;
61import android.app.ActivityManagerNative;
62import android.app.IActivityManager;
63import android.app.PackageInstallObserver;
64import android.app.admin.IDevicePolicyManager;
65import android.app.backup.IBackupManager;
66import android.content.BroadcastReceiver;
67import android.content.ComponentName;
68import android.content.Context;
69import android.content.IIntentReceiver;
70import android.content.Intent;
71import android.content.IntentFilter;
72import android.content.IntentSender;
73import android.content.IntentSender.SendIntentException;
74import android.content.ServiceConnection;
75import android.content.pm.ActivityInfo;
76import android.content.pm.ApplicationInfo;
77import android.content.pm.ContainerEncryptionParams;
78import android.content.pm.FeatureInfo;
79import android.content.pm.IPackageDataObserver;
80import android.content.pm.IPackageDeleteObserver;
81import android.content.pm.IPackageInstallObserver;
82import android.content.pm.IPackageInstallObserver2;
83import android.content.pm.IPackageInstaller;
84import android.content.pm.IPackageManager;
85import android.content.pm.IPackageMoveObserver;
86import android.content.pm.IPackageStatsObserver;
87import android.content.pm.InstrumentationInfo;
88import android.content.pm.ManifestDigest;
89import android.content.pm.PackageCleanItem;
90import android.content.pm.PackageInfo;
91import android.content.pm.PackageInfoLite;
92import android.content.pm.PackageInstallerParams;
93import android.content.pm.PackageManager;
94import android.content.pm.PackageParser.ActivityIntentInfo;
95import android.content.pm.PackageParser;
96import android.content.pm.PackageStats;
97import android.content.pm.PackageUserState;
98import android.content.pm.ParceledListSlice;
99import android.content.pm.PermissionGroupInfo;
100import android.content.pm.PermissionInfo;
101import android.content.pm.ProviderInfo;
102import android.content.pm.ResolveInfo;
103import android.content.pm.ServiceInfo;
104import android.content.pm.Signature;
105import android.content.pm.VerificationParams;
106import android.content.pm.VerifierDeviceIdentity;
107import android.content.pm.VerifierInfo;
108import android.content.res.Resources;
109import android.hardware.display.DisplayManager;
110import android.net.Uri;
111import android.os.Binder;
112import android.os.Build;
113import android.os.Bundle;
114import android.os.Environment;
115import android.os.Environment.UserEnvironment;
116import android.os.FileObserver;
117import android.os.FileUtils;
118import android.os.Handler;
119import android.os.IBinder;
120import android.os.Looper;
121import android.os.Message;
122import android.os.Parcel;
123import android.os.ParcelFileDescriptor;
124import android.os.Process;
125import android.os.RemoteException;
126import android.os.SELinux;
127import android.os.ServiceManager;
128import android.os.SystemClock;
129import android.os.SystemProperties;
130import android.os.UserHandle;
131import android.os.UserManager;
132import android.security.KeyStore;
133import android.security.SystemKeyStore;
134import android.system.ErrnoException;
135import android.system.Os;
136import android.system.StructStat;
137import android.text.TextUtils;
138import android.util.AtomicFile;
139import android.util.DisplayMetrics;
140import android.util.EventLog;
141import android.util.Log;
142import android.util.LogPrinter;
143import android.util.PrintStreamPrinter;
144import android.util.Slog;
145import android.util.SparseArray;
146import android.util.Xml;
147import android.view.Display;
148
149import java.io.BufferedInputStream;
150import java.io.BufferedOutputStream;
151import java.io.File;
152import java.io.FileDescriptor;
153import java.io.FileInputStream;
154import java.io.FileNotFoundException;
155import java.io.FileOutputStream;
156import java.io.FileReader;
157import java.io.FilenameFilter;
158import java.io.IOException;
159import java.io.InputStream;
160import java.io.PrintWriter;
161import java.nio.charset.StandardCharsets;
162import java.security.NoSuchAlgorithmException;
163import java.security.PublicKey;
164import java.security.cert.Certificate;
165import java.security.cert.CertificateEncodingException;
166import java.security.cert.CertificateException;
167import java.text.SimpleDateFormat;
168import java.util.ArrayList;
169import java.util.Arrays;
170import java.util.Collection;
171import java.util.Collections;
172import java.util.Comparator;
173import java.util.Date;
174import java.util.HashMap;
175import java.util.HashSet;
176import java.util.Iterator;
177import java.util.List;
178import java.util.Map;
179import java.util.Set;
180import java.util.concurrent.atomic.AtomicBoolean;
181import java.util.concurrent.atomic.AtomicLong;
182
183import dalvik.system.DexFile;
184import dalvik.system.StaleDexCacheError;
185import dalvik.system.VMRuntime;
186
187import libcore.io.IoUtils;
188
189/**
190 * Keep track of all those .apks everywhere.
191 *
192 * This is very central to the platform's security; please run the unit
193 * tests whenever making modifications here:
194 *
195mmm frameworks/base/tests/AndroidTests
196adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
197adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
198 *
199 * {@hide}
200 */
201public class PackageManagerService extends IPackageManager.Stub {
202    static final String TAG = "PackageManager";
203    static final boolean DEBUG_SETTINGS = false;
204    static final boolean DEBUG_PREFERRED = false;
205    static final boolean DEBUG_UPGRADE = false;
206    private static final boolean DEBUG_INSTALL = false;
207    private static final boolean DEBUG_REMOVE = false;
208    private static final boolean DEBUG_BROADCASTS = false;
209    private static final boolean DEBUG_SHOW_INFO = false;
210    private static final boolean DEBUG_PACKAGE_INFO = false;
211    private static final boolean DEBUG_INTENT_MATCHING = false;
212    private static final boolean DEBUG_PACKAGE_SCANNING = false;
213    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
214    private static final boolean DEBUG_VERIFY = false;
215    private static final boolean DEBUG_DEXOPT = false;
216
217    private static final int RADIO_UID = Process.PHONE_UID;
218    private static final int LOG_UID = Process.LOG_UID;
219    private static final int NFC_UID = Process.NFC_UID;
220    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
221    private static final int SHELL_UID = Process.SHELL_UID;
222
223    // Cap the size of permission trees that 3rd party apps can define
224    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
225
226    private static final int REMOVE_EVENTS =
227        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
228    private static final int ADD_EVENTS =
229        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
230
231    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
232    // Suffix used during package installation when copying/moving
233    // package apks to install directory.
234    private static final String INSTALL_PACKAGE_SUFFIX = "-";
235
236    static final int SCAN_MONITOR = 1<<0;
237    static final int SCAN_NO_DEX = 1<<1;
238    static final int SCAN_FORCE_DEX = 1<<2;
239    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
240    static final int SCAN_NEW_INSTALL = 1<<4;
241    static final int SCAN_NO_PATHS = 1<<5;
242    static final int SCAN_UPDATE_TIME = 1<<6;
243    static final int SCAN_DEFER_DEX = 1<<7;
244    static final int SCAN_BOOTING = 1<<8;
245    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
246    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
247
248    static final int REMOVE_CHATTY = 1<<16;
249
250    /**
251     * Timeout (in milliseconds) after which the watchdog should declare that
252     * our handler thread is wedged.  The usual default for such things is one
253     * minute but we sometimes do very lengthy I/O operations on this thread,
254     * such as installing multi-gigabyte applications, so ours needs to be longer.
255     */
256    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
257
258    /**
259     * Whether verification is enabled by default.
260     */
261    private static final boolean DEFAULT_VERIFY_ENABLE = true;
262
263    /**
264     * The default maximum time to wait for the verification agent to return in
265     * milliseconds.
266     */
267    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
268
269    /**
270     * The default response for package verification timeout.
271     *
272     * This can be either PackageManager.VERIFICATION_ALLOW or
273     * PackageManager.VERIFICATION_REJECT.
274     */
275    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
276
277    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
278
279    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
280            DEFAULT_CONTAINER_PACKAGE,
281            "com.android.defcontainer.DefaultContainerService");
282
283    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
284
285    private static final String LIB_DIR_NAME = "lib";
286    private static final String LIB64_DIR_NAME = "lib64";
287
288    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
289
290    static final String mTempContainerPrefix = "smdl2tmp";
291
292    private static String sPreferredInstructionSet;
293
294    final ServiceThread mHandlerThread;
295
296    private static final String IDMAP_PREFIX = "/data/resource-cache/";
297    private static final String IDMAP_SUFFIX = "@idmap";
298
299    final PackageHandler mHandler;
300
301    final int mSdkVersion = Build.VERSION.SDK_INT;
302
303    final Context mContext;
304    final boolean mFactoryTest;
305    final boolean mOnlyCore;
306    final DisplayMetrics mMetrics;
307    final int mDefParseFlags;
308    final String[] mSeparateProcesses;
309
310    // This is where all application persistent data goes.
311    final File mAppDataDir;
312
313    // This is where all application persistent data goes for secondary users.
314    final File mUserAppDataDir;
315
316    /** The location for ASEC container files on internal storage. */
317    final String mAsecInternalPath;
318
319    // This is the object monitoring the framework dir.
320    final FileObserver mFrameworkInstallObserver;
321
322    // This is the object monitoring the system app dir.
323    final FileObserver mSystemInstallObserver;
324
325    // This is the object monitoring the privileged system app dir.
326    final FileObserver mPrivilegedInstallObserver;
327
328    // This is the object monitoring the vendor app dir.
329    final FileObserver mVendorInstallObserver;
330
331    // This is the object monitoring the vendor overlay package dir.
332    final FileObserver mVendorOverlayInstallObserver;
333
334    // This is the object monitoring the OEM app dir.
335    final FileObserver mOemInstallObserver;
336
337    // This is the object monitoring mAppInstallDir.
338    final FileObserver mAppInstallObserver;
339
340    // This is the object monitoring mDrmAppPrivateInstallDir.
341    final FileObserver mDrmAppInstallObserver;
342
343    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
344    // LOCK HELD.  Can be called with mInstallLock held.
345    final Installer mInstaller;
346
347    final File mAppInstallDir;
348
349    /**
350     * Directory to which applications installed internally have native
351     * libraries copied.
352     */
353    private File mAppLibInstallDir;
354
355    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
356    // apps.
357    final File mDrmAppPrivateInstallDir;
358
359    final File mAppStagingDir;
360
361    // ----------------------------------------------------------------
362
363    // Lock for state used when installing and doing other long running
364    // operations.  Methods that must be called with this lock held have
365    // the suffix "LI".
366    final Object mInstallLock = new Object();
367
368    // These are the directories in the 3rd party applications installed dir
369    // that we have currently loaded packages from.  Keys are the application's
370    // installed zip file (absolute codePath), and values are Package.
371    final HashMap<String, PackageParser.Package> mAppDirs =
372            new HashMap<String, PackageParser.Package>();
373
374    // Information for the parser to write more useful error messages.
375    int mLastScanError;
376
377    // ----------------------------------------------------------------
378
379    // Keys are String (package name), values are Package.  This also serves
380    // as the lock for the global state.  Methods that must be called with
381    // this lock held have the prefix "LP".
382    final HashMap<String, PackageParser.Package> mPackages =
383            new HashMap<String, PackageParser.Package>();
384
385    // Tracks available target package names -> overlay package paths.
386    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
387        new HashMap<String, HashMap<String, PackageParser.Package>>();
388
389    final Settings mSettings;
390    boolean mRestoredSettings;
391
392    // Group-ids that are given to all packages as read from etc/permissions/*.xml.
393    int[] mGlobalGids;
394
395    // These are the built-in uid -> permission mappings that were read from the
396    // etc/permissions.xml file.
397    final SparseArray<HashSet<String>> mSystemPermissions =
398            new SparseArray<HashSet<String>>();
399
400    static final class SharedLibraryEntry {
401        final String path;
402        final String apk;
403
404        SharedLibraryEntry(String _path, String _apk) {
405            path = _path;
406            apk = _apk;
407        }
408    }
409
410    // These are the built-in shared libraries that were read from the
411    // etc/permissions.xml file.
412    final HashMap<String, SharedLibraryEntry> mSharedLibraries
413            = new HashMap<String, SharedLibraryEntry>();
414
415    // Temporary for building the final shared libraries for an .apk.
416    String[] mTmpSharedLibraries = null;
417
418    // These are the features this devices supports that were read from the
419    // etc/permissions.xml file.
420    final HashMap<String, FeatureInfo> mAvailableFeatures =
421            new HashMap<String, FeatureInfo>();
422
423    // If mac_permissions.xml was found for seinfo labeling.
424    boolean mFoundPolicyFile;
425
426    // If a recursive restorecon of /data/data/<pkg> is needed.
427    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
428
429    // All available activities, for your resolving pleasure.
430    final ActivityIntentResolver mActivities =
431            new ActivityIntentResolver();
432
433    // All available receivers, for your resolving pleasure.
434    final ActivityIntentResolver mReceivers =
435            new ActivityIntentResolver();
436
437    // All available services, for your resolving pleasure.
438    final ServiceIntentResolver mServices = new ServiceIntentResolver();
439
440    // All available providers, for your resolving pleasure.
441    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
442
443    // Mapping from provider base names (first directory in content URI codePath)
444    // to the provider information.
445    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
446            new HashMap<String, PackageParser.Provider>();
447
448    // Mapping from instrumentation class names to info about them.
449    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
450            new HashMap<ComponentName, PackageParser.Instrumentation>();
451
452    // Mapping from permission names to info about them.
453    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
454            new HashMap<String, PackageParser.PermissionGroup>();
455
456    // Packages whose data we have transfered into another package, thus
457    // should no longer exist.
458    final HashSet<String> mTransferedPackages = new HashSet<String>();
459
460    // Broadcast actions that are only available to the system.
461    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
462
463    /** List of packages waiting for verification. */
464    final SparseArray<PackageVerificationState> mPendingVerification
465            = new SparseArray<PackageVerificationState>();
466
467    final PackageInstallerService mInstallerService;
468
469    HashSet<PackageParser.Package> mDeferredDexOpt = null;
470
471    /** Token for keys in mPendingVerification. */
472    private int mPendingVerificationToken = 0;
473
474    boolean mSystemReady;
475    boolean mSafeMode;
476    boolean mHasSystemUidErrors;
477
478    ApplicationInfo mAndroidApplication;
479    final ActivityInfo mResolveActivity = new ActivityInfo();
480    final ResolveInfo mResolveInfo = new ResolveInfo();
481    ComponentName mResolveComponentName;
482    PackageParser.Package mPlatformPackage;
483    ComponentName mCustomResolverComponentName;
484
485    boolean mResolverReplaced = false;
486
487    // Set of pending broadcasts for aggregating enable/disable of components.
488    static class PendingPackageBroadcasts {
489        // for each user id, a map of <package name -> components within that package>
490        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
491
492        public PendingPackageBroadcasts() {
493            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
494        }
495
496        public ArrayList<String> get(int userId, String packageName) {
497            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
498            return packages.get(packageName);
499        }
500
501        public void put(int userId, String packageName, ArrayList<String> components) {
502            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
503            packages.put(packageName, components);
504        }
505
506        public void remove(int userId, String packageName) {
507            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
508            if (packages != null) {
509                packages.remove(packageName);
510            }
511        }
512
513        public void remove(int userId) {
514            mUidMap.remove(userId);
515        }
516
517        public int userIdCount() {
518            return mUidMap.size();
519        }
520
521        public int userIdAt(int n) {
522            return mUidMap.keyAt(n);
523        }
524
525        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
526            return mUidMap.get(userId);
527        }
528
529        public int size() {
530            // total number of pending broadcast entries across all userIds
531            int num = 0;
532            for (int i = 0; i< mUidMap.size(); i++) {
533                num += mUidMap.valueAt(i).size();
534            }
535            return num;
536        }
537
538        public void clear() {
539            mUidMap.clear();
540        }
541
542        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
543            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
544            if (map == null) {
545                map = new HashMap<String, ArrayList<String>>();
546                mUidMap.put(userId, map);
547            }
548            return map;
549        }
550    }
551    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
552
553    // Service Connection to remote media container service to copy
554    // package uri's from external media onto secure containers
555    // or internal storage.
556    private IMediaContainerService mContainerService = null;
557
558    static final int SEND_PENDING_BROADCAST = 1;
559    static final int MCS_BOUND = 3;
560    static final int END_COPY = 4;
561    static final int INIT_COPY = 5;
562    static final int MCS_UNBIND = 6;
563    static final int START_CLEANING_PACKAGE = 7;
564    static final int FIND_INSTALL_LOC = 8;
565    static final int POST_INSTALL = 9;
566    static final int MCS_RECONNECT = 10;
567    static final int MCS_GIVE_UP = 11;
568    static final int UPDATED_MEDIA_STATUS = 12;
569    static final int WRITE_SETTINGS = 13;
570    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
571    static final int PACKAGE_VERIFIED = 15;
572    static final int CHECK_PENDING_VERIFICATION = 16;
573
574    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
575
576    // Delay time in millisecs
577    static final int BROADCAST_DELAY = 10 * 1000;
578
579    static UserManagerService sUserManager;
580
581    // Stores a list of users whose package restrictions file needs to be updated
582    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
583
584    final private DefaultContainerConnection mDefContainerConn =
585            new DefaultContainerConnection();
586    class DefaultContainerConnection implements ServiceConnection {
587        public void onServiceConnected(ComponentName name, IBinder service) {
588            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
589            IMediaContainerService imcs =
590                IMediaContainerService.Stub.asInterface(service);
591            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
592        }
593
594        public void onServiceDisconnected(ComponentName name) {
595            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
596        }
597    };
598
599    // Recordkeeping of restore-after-install operations that are currently in flight
600    // between the Package Manager and the Backup Manager
601    class PostInstallData {
602        public InstallArgs args;
603        public PackageInstalledInfo res;
604
605        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
606            args = _a;
607            res = _r;
608        }
609    };
610    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
611    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
612
613    private final String mRequiredVerifierPackage;
614
615    private final PackageUsage mPackageUsage = new PackageUsage();
616
617    private class PackageUsage {
618        private static final int WRITE_INTERVAL
619            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
620
621        private final Object mFileLock = new Object();
622        private final AtomicLong mLastWritten = new AtomicLong(0);
623        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
624
625        private boolean mIsFirstBoot = false;
626
627        boolean isFirstBoot() {
628            return mIsFirstBoot;
629        }
630
631        void write(boolean force) {
632            if (force) {
633                writeInternal();
634                return;
635            }
636            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
637                && !DEBUG_DEXOPT) {
638                return;
639            }
640            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
641                new Thread("PackageUsage_DiskWriter") {
642                    @Override
643                    public void run() {
644                        try {
645                            writeInternal();
646                        } finally {
647                            mBackgroundWriteRunning.set(false);
648                        }
649                    }
650                }.start();
651            }
652        }
653
654        private void writeInternal() {
655            synchronized (mPackages) {
656                synchronized (mFileLock) {
657                    AtomicFile file = getFile();
658                    FileOutputStream f = null;
659                    try {
660                        f = file.startWrite();
661                        BufferedOutputStream out = new BufferedOutputStream(f);
662                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
663                        StringBuilder sb = new StringBuilder();
664                        for (PackageParser.Package pkg : mPackages.values()) {
665                            if (pkg.mLastPackageUsageTimeInMills == 0) {
666                                continue;
667                            }
668                            sb.setLength(0);
669                            sb.append(pkg.packageName);
670                            sb.append(' ');
671                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
672                            sb.append('\n');
673                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
674                        }
675                        out.flush();
676                        file.finishWrite(f);
677                    } catch (IOException e) {
678                        if (f != null) {
679                            file.failWrite(f);
680                        }
681                        Log.e(TAG, "Failed to write package usage times", e);
682                    }
683                }
684            }
685            mLastWritten.set(SystemClock.elapsedRealtime());
686        }
687
688        void readLP() {
689            synchronized (mFileLock) {
690                AtomicFile file = getFile();
691                BufferedInputStream in = null;
692                try {
693                    in = new BufferedInputStream(file.openRead());
694                    StringBuffer sb = new StringBuffer();
695                    while (true) {
696                        String packageName = readToken(in, sb, ' ');
697                        if (packageName == null) {
698                            break;
699                        }
700                        String timeInMillisString = readToken(in, sb, '\n');
701                        if (timeInMillisString == null) {
702                            throw new IOException("Failed to find last usage time for package "
703                                                  + packageName);
704                        }
705                        PackageParser.Package pkg = mPackages.get(packageName);
706                        if (pkg == null) {
707                            continue;
708                        }
709                        long timeInMillis;
710                        try {
711                            timeInMillis = Long.parseLong(timeInMillisString.toString());
712                        } catch (NumberFormatException e) {
713                            throw new IOException("Failed to parse " + timeInMillisString
714                                                  + " as a long.", e);
715                        }
716                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
717                    }
718                } catch (FileNotFoundException expected) {
719                    mIsFirstBoot = true;
720                } catch (IOException e) {
721                    Log.w(TAG, "Failed to read package usage times", e);
722                } finally {
723                    IoUtils.closeQuietly(in);
724                }
725            }
726            mLastWritten.set(SystemClock.elapsedRealtime());
727        }
728
729        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
730                throws IOException {
731            sb.setLength(0);
732            while (true) {
733                int ch = in.read();
734                if (ch == -1) {
735                    if (sb.length() == 0) {
736                        return null;
737                    }
738                    throw new IOException("Unexpected EOF");
739                }
740                if (ch == endOfToken) {
741                    return sb.toString();
742                }
743                sb.append((char)ch);
744            }
745        }
746
747        private AtomicFile getFile() {
748            File dataDir = Environment.getDataDirectory();
749            File systemDir = new File(dataDir, "system");
750            File fname = new File(systemDir, "package-usage.list");
751            return new AtomicFile(fname);
752        }
753    }
754
755    class PackageHandler extends Handler {
756        private boolean mBound = false;
757        final ArrayList<HandlerParams> mPendingInstalls =
758            new ArrayList<HandlerParams>();
759
760        private boolean connectToService() {
761            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
762                    " DefaultContainerService");
763            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
764            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
765            if (mContext.bindServiceAsUser(service, mDefContainerConn,
766                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
767                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
768                mBound = true;
769                return true;
770            }
771            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
772            return false;
773        }
774
775        private void disconnectService() {
776            mContainerService = null;
777            mBound = false;
778            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
779            mContext.unbindService(mDefContainerConn);
780            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
781        }
782
783        PackageHandler(Looper looper) {
784            super(looper);
785        }
786
787        public void handleMessage(Message msg) {
788            try {
789                doHandleMessage(msg);
790            } finally {
791                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
792            }
793        }
794
795        void doHandleMessage(Message msg) {
796            switch (msg.what) {
797                case INIT_COPY: {
798                    HandlerParams params = (HandlerParams) msg.obj;
799                    int idx = mPendingInstalls.size();
800                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
801                    // If a bind was already initiated we dont really
802                    // need to do anything. The pending install
803                    // will be processed later on.
804                    if (!mBound) {
805                        // If this is the only one pending we might
806                        // have to bind to the service again.
807                        if (!connectToService()) {
808                            Slog.e(TAG, "Failed to bind to media container service");
809                            params.serviceError();
810                            return;
811                        } else {
812                            // Once we bind to the service, the first
813                            // pending request will be processed.
814                            mPendingInstalls.add(idx, params);
815                        }
816                    } else {
817                        mPendingInstalls.add(idx, params);
818                        // Already bound to the service. Just make
819                        // sure we trigger off processing the first request.
820                        if (idx == 0) {
821                            mHandler.sendEmptyMessage(MCS_BOUND);
822                        }
823                    }
824                    break;
825                }
826                case MCS_BOUND: {
827                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
828                    if (msg.obj != null) {
829                        mContainerService = (IMediaContainerService) msg.obj;
830                    }
831                    if (mContainerService == null) {
832                        // Something seriously wrong. Bail out
833                        Slog.e(TAG, "Cannot bind to media container service");
834                        for (HandlerParams params : mPendingInstalls) {
835                            // Indicate service bind error
836                            params.serviceError();
837                        }
838                        mPendingInstalls.clear();
839                    } else if (mPendingInstalls.size() > 0) {
840                        HandlerParams params = mPendingInstalls.get(0);
841                        if (params != null) {
842                            if (params.startCopy()) {
843                                // We are done...  look for more work or to
844                                // go idle.
845                                if (DEBUG_SD_INSTALL) Log.i(TAG,
846                                        "Checking for more work or unbind...");
847                                // Delete pending install
848                                if (mPendingInstalls.size() > 0) {
849                                    mPendingInstalls.remove(0);
850                                }
851                                if (mPendingInstalls.size() == 0) {
852                                    if (mBound) {
853                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
854                                                "Posting delayed MCS_UNBIND");
855                                        removeMessages(MCS_UNBIND);
856                                        Message ubmsg = obtainMessage(MCS_UNBIND);
857                                        // Unbind after a little delay, to avoid
858                                        // continual thrashing.
859                                        sendMessageDelayed(ubmsg, 10000);
860                                    }
861                                } else {
862                                    // There are more pending requests in queue.
863                                    // Just post MCS_BOUND message to trigger processing
864                                    // of next pending install.
865                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
866                                            "Posting MCS_BOUND for next work");
867                                    mHandler.sendEmptyMessage(MCS_BOUND);
868                                }
869                            }
870                        }
871                    } else {
872                        // Should never happen ideally.
873                        Slog.w(TAG, "Empty queue");
874                    }
875                    break;
876                }
877                case MCS_RECONNECT: {
878                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
879                    if (mPendingInstalls.size() > 0) {
880                        if (mBound) {
881                            disconnectService();
882                        }
883                        if (!connectToService()) {
884                            Slog.e(TAG, "Failed to bind to media container service");
885                            for (HandlerParams params : mPendingInstalls) {
886                                // Indicate service bind error
887                                params.serviceError();
888                            }
889                            mPendingInstalls.clear();
890                        }
891                    }
892                    break;
893                }
894                case MCS_UNBIND: {
895                    // If there is no actual work left, then time to unbind.
896                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
897
898                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
899                        if (mBound) {
900                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
901
902                            disconnectService();
903                        }
904                    } else if (mPendingInstalls.size() > 0) {
905                        // There are more pending requests in queue.
906                        // Just post MCS_BOUND message to trigger processing
907                        // of next pending install.
908                        mHandler.sendEmptyMessage(MCS_BOUND);
909                    }
910
911                    break;
912                }
913                case MCS_GIVE_UP: {
914                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
915                    mPendingInstalls.remove(0);
916                    break;
917                }
918                case SEND_PENDING_BROADCAST: {
919                    String packages[];
920                    ArrayList<String> components[];
921                    int size = 0;
922                    int uids[];
923                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
924                    synchronized (mPackages) {
925                        if (mPendingBroadcasts == null) {
926                            return;
927                        }
928                        size = mPendingBroadcasts.size();
929                        if (size <= 0) {
930                            // Nothing to be done. Just return
931                            return;
932                        }
933                        packages = new String[size];
934                        components = new ArrayList[size];
935                        uids = new int[size];
936                        int i = 0;  // filling out the above arrays
937
938                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
939                            int packageUserId = mPendingBroadcasts.userIdAt(n);
940                            Iterator<Map.Entry<String, ArrayList<String>>> it
941                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
942                                            .entrySet().iterator();
943                            while (it.hasNext() && i < size) {
944                                Map.Entry<String, ArrayList<String>> ent = it.next();
945                                packages[i] = ent.getKey();
946                                components[i] = ent.getValue();
947                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
948                                uids[i] = (ps != null)
949                                        ? UserHandle.getUid(packageUserId, ps.appId)
950                                        : -1;
951                                i++;
952                            }
953                        }
954                        size = i;
955                        mPendingBroadcasts.clear();
956                    }
957                    // Send broadcasts
958                    for (int i = 0; i < size; i++) {
959                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
960                    }
961                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
962                    break;
963                }
964                case START_CLEANING_PACKAGE: {
965                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
966                    final String packageName = (String)msg.obj;
967                    final int userId = msg.arg1;
968                    final boolean andCode = msg.arg2 != 0;
969                    synchronized (mPackages) {
970                        if (userId == UserHandle.USER_ALL) {
971                            int[] users = sUserManager.getUserIds();
972                            for (int user : users) {
973                                mSettings.addPackageToCleanLPw(
974                                        new PackageCleanItem(user, packageName, andCode));
975                            }
976                        } else {
977                            mSettings.addPackageToCleanLPw(
978                                    new PackageCleanItem(userId, packageName, andCode));
979                        }
980                    }
981                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
982                    startCleaningPackages();
983                } break;
984                case POST_INSTALL: {
985                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
986                    PostInstallData data = mRunningInstalls.get(msg.arg1);
987                    mRunningInstalls.delete(msg.arg1);
988                    boolean deleteOld = false;
989
990                    if (data != null) {
991                        InstallArgs args = data.args;
992                        PackageInstalledInfo res = data.res;
993
994                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
995                            res.removedInfo.sendBroadcast(false, true, false);
996                            Bundle extras = new Bundle(1);
997                            extras.putInt(Intent.EXTRA_UID, res.uid);
998                            // Determine the set of users who are adding this
999                            // package for the first time vs. those who are seeing
1000                            // an update.
1001                            int[] firstUsers;
1002                            int[] updateUsers = new int[0];
1003                            if (res.origUsers == null || res.origUsers.length == 0) {
1004                                firstUsers = res.newUsers;
1005                            } else {
1006                                firstUsers = new int[0];
1007                                for (int i=0; i<res.newUsers.length; i++) {
1008                                    int user = res.newUsers[i];
1009                                    boolean isNew = true;
1010                                    for (int j=0; j<res.origUsers.length; j++) {
1011                                        if (res.origUsers[j] == user) {
1012                                            isNew = false;
1013                                            break;
1014                                        }
1015                                    }
1016                                    if (isNew) {
1017                                        int[] newFirst = new int[firstUsers.length+1];
1018                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1019                                                firstUsers.length);
1020                                        newFirst[firstUsers.length] = user;
1021                                        firstUsers = newFirst;
1022                                    } else {
1023                                        int[] newUpdate = new int[updateUsers.length+1];
1024                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1025                                                updateUsers.length);
1026                                        newUpdate[updateUsers.length] = user;
1027                                        updateUsers = newUpdate;
1028                                    }
1029                                }
1030                            }
1031                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1032                                    res.pkg.applicationInfo.packageName,
1033                                    extras, null, null, firstUsers);
1034                            final boolean update = res.removedInfo.removedPackage != null;
1035                            if (update) {
1036                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1037                            }
1038                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1039                                    res.pkg.applicationInfo.packageName,
1040                                    extras, null, null, updateUsers);
1041                            if (update) {
1042                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1043                                        res.pkg.applicationInfo.packageName,
1044                                        extras, null, null, updateUsers);
1045                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1046                                        null, null,
1047                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1048
1049                                // treat asec-hosted packages like removable media on upgrade
1050                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1051                                    if (DEBUG_INSTALL) {
1052                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1053                                                + " is ASEC-hosted -> AVAILABLE");
1054                                    }
1055                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1056                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1057                                    pkgList.add(res.pkg.applicationInfo.packageName);
1058                                    sendResourcesChangedBroadcast(true, true,
1059                                            pkgList,uidArray, null);
1060                                }
1061                            }
1062                            if (res.removedInfo.args != null) {
1063                                // Remove the replaced package's older resources safely now
1064                                deleteOld = true;
1065                            }
1066
1067                            // Log current value of "unknown sources" setting
1068                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1069                                getUnknownSourcesSettings());
1070                        }
1071                        // Force a gc to clear up things
1072                        Runtime.getRuntime().gc();
1073                        // We delete after a gc for applications  on sdcard.
1074                        if (deleteOld) {
1075                            synchronized (mInstallLock) {
1076                                res.removedInfo.args.doPostDeleteLI(true);
1077                            }
1078                        }
1079                        if (args.observer != null) {
1080                            try {
1081                                args.observer.packageInstalled(res.name, res.returnCode);
1082                            } catch (RemoteException e) {
1083                                Slog.i(TAG, "Observer no longer exists.");
1084                            }
1085                        }
1086                        if (args.observer2 != null) {
1087                            try {
1088                                Bundle extras = extrasForInstallResult(res);
1089                                args.observer2.packageInstalled(res.name, extras, res.returnCode);
1090                            } catch (RemoteException e) {
1091                                Slog.i(TAG, "Observer no longer exists.");
1092                            }
1093                        }
1094                    } else {
1095                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1096                    }
1097                } break;
1098                case UPDATED_MEDIA_STATUS: {
1099                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1100                    boolean reportStatus = msg.arg1 == 1;
1101                    boolean doGc = msg.arg2 == 1;
1102                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1103                    if (doGc) {
1104                        // Force a gc to clear up stale containers.
1105                        Runtime.getRuntime().gc();
1106                    }
1107                    if (msg.obj != null) {
1108                        @SuppressWarnings("unchecked")
1109                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1110                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1111                        // Unload containers
1112                        unloadAllContainers(args);
1113                    }
1114                    if (reportStatus) {
1115                        try {
1116                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1117                            PackageHelper.getMountService().finishMediaUpdate();
1118                        } catch (RemoteException e) {
1119                            Log.e(TAG, "MountService not running?");
1120                        }
1121                    }
1122                } break;
1123                case WRITE_SETTINGS: {
1124                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1125                    synchronized (mPackages) {
1126                        removeMessages(WRITE_SETTINGS);
1127                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1128                        mSettings.writeLPr();
1129                        mDirtyUsers.clear();
1130                    }
1131                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1132                } break;
1133                case WRITE_PACKAGE_RESTRICTIONS: {
1134                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1135                    synchronized (mPackages) {
1136                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1137                        for (int userId : mDirtyUsers) {
1138                            mSettings.writePackageRestrictionsLPr(userId);
1139                        }
1140                        mDirtyUsers.clear();
1141                    }
1142                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1143                } break;
1144                case CHECK_PENDING_VERIFICATION: {
1145                    final int verificationId = msg.arg1;
1146                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1147
1148                    if ((state != null) && !state.timeoutExtended()) {
1149                        final InstallArgs args = state.getInstallArgs();
1150                        Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
1151                        mPendingVerification.remove(verificationId);
1152
1153                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1154
1155                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1156                            Slog.i(TAG, "Continuing with installation of "
1157                                    + args.packageURI.toString());
1158                            state.setVerifierResponse(Binder.getCallingUid(),
1159                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1160                            broadcastPackageVerified(verificationId, args.packageURI,
1161                                    PackageManager.VERIFICATION_ALLOW,
1162                                    state.getInstallArgs().getUser());
1163                            try {
1164                                ret = args.copyApk(mContainerService, true);
1165                            } catch (RemoteException e) {
1166                                Slog.e(TAG, "Could not contact the ContainerService");
1167                            }
1168                        } else {
1169                            broadcastPackageVerified(verificationId, args.packageURI,
1170                                    PackageManager.VERIFICATION_REJECT,
1171                                    state.getInstallArgs().getUser());
1172                        }
1173
1174                        processPendingInstall(args, ret);
1175                        mHandler.sendEmptyMessage(MCS_UNBIND);
1176                    }
1177                    break;
1178                }
1179                case PACKAGE_VERIFIED: {
1180                    final int verificationId = msg.arg1;
1181
1182                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1183                    if (state == null) {
1184                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1185                        break;
1186                    }
1187
1188                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1189
1190                    state.setVerifierResponse(response.callerUid, response.code);
1191
1192                    if (state.isVerificationComplete()) {
1193                        mPendingVerification.remove(verificationId);
1194
1195                        final InstallArgs args = state.getInstallArgs();
1196
1197                        int ret;
1198                        if (state.isInstallAllowed()) {
1199                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1200                            broadcastPackageVerified(verificationId, args.packageURI,
1201                                    response.code, state.getInstallArgs().getUser());
1202                            try {
1203                                ret = args.copyApk(mContainerService, true);
1204                            } catch (RemoteException e) {
1205                                Slog.e(TAG, "Could not contact the ContainerService");
1206                            }
1207                        } else {
1208                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1209                        }
1210
1211                        processPendingInstall(args, ret);
1212
1213                        mHandler.sendEmptyMessage(MCS_UNBIND);
1214                    }
1215
1216                    break;
1217                }
1218            }
1219        }
1220    }
1221
1222    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1223        Bundle extras = null;
1224        switch (res.returnCode) {
1225            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1226                extras = new Bundle();
1227                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1228                        res.origPermission);
1229                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1230                        res.origPackage);
1231                break;
1232            }
1233        }
1234        return extras;
1235    }
1236
1237    void scheduleWriteSettingsLocked() {
1238        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1239            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1240        }
1241    }
1242
1243    void scheduleWritePackageRestrictionsLocked(int userId) {
1244        if (!sUserManager.exists(userId)) return;
1245        mDirtyUsers.add(userId);
1246        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1247            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1248        }
1249    }
1250
1251    public static final IPackageManager main(Context context, Installer installer,
1252            boolean factoryTest, boolean onlyCore) {
1253        PackageManagerService m = new PackageManagerService(context, installer,
1254                factoryTest, onlyCore);
1255        ServiceManager.addService("package", m);
1256        return m;
1257    }
1258
1259    static String[] splitString(String str, char sep) {
1260        int count = 1;
1261        int i = 0;
1262        while ((i=str.indexOf(sep, i)) >= 0) {
1263            count++;
1264            i++;
1265        }
1266
1267        String[] res = new String[count];
1268        i=0;
1269        count = 0;
1270        int lastI=0;
1271        while ((i=str.indexOf(sep, i)) >= 0) {
1272            res[count] = str.substring(lastI, i);
1273            count++;
1274            i++;
1275            lastI = i;
1276        }
1277        res[count] = str.substring(lastI, str.length());
1278        return res;
1279    }
1280
1281    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1282        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1283                Context.DISPLAY_SERVICE);
1284        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1285    }
1286
1287    public PackageManagerService(Context context, Installer installer,
1288            boolean factoryTest, boolean onlyCore) {
1289        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1290                SystemClock.uptimeMillis());
1291
1292        if (mSdkVersion <= 0) {
1293            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1294        }
1295
1296        mContext = context;
1297        mFactoryTest = factoryTest;
1298        mOnlyCore = onlyCore;
1299        mMetrics = new DisplayMetrics();
1300        mSettings = new Settings(context);
1301        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1302                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1303        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1304                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1305        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1306                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1307        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1308                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1309        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1310                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1311        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1312                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1313
1314        String separateProcesses = SystemProperties.get("debug.separate_processes");
1315        if (separateProcesses != null && separateProcesses.length() > 0) {
1316            if ("*".equals(separateProcesses)) {
1317                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1318                mSeparateProcesses = null;
1319                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1320            } else {
1321                mDefParseFlags = 0;
1322                mSeparateProcesses = separateProcesses.split(",");
1323                Slog.w(TAG, "Running with debug.separate_processes: "
1324                        + separateProcesses);
1325            }
1326        } else {
1327            mDefParseFlags = 0;
1328            mSeparateProcesses = null;
1329        }
1330
1331        mInstaller = installer;
1332
1333        getDefaultDisplayMetrics(context, mMetrics);
1334
1335        synchronized (mInstallLock) {
1336        // writer
1337        synchronized (mPackages) {
1338            mHandlerThread = new ServiceThread(TAG,
1339                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1340            mHandlerThread.start();
1341            mHandler = new PackageHandler(mHandlerThread.getLooper());
1342            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1343
1344            File dataDir = Environment.getDataDirectory();
1345            mAppDataDir = new File(dataDir, "data");
1346            mAppInstallDir = new File(dataDir, "app");
1347            mAppLibInstallDir = new File(dataDir, "app-lib");
1348            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1349            mUserAppDataDir = new File(dataDir, "user");
1350            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1351            mAppStagingDir = new File(dataDir, "app-staging");
1352
1353            sUserManager = new UserManagerService(context, this,
1354                    mInstallLock, mPackages);
1355
1356            // Read permissions and features from system
1357            readPermissions(Environment.buildPath(
1358                    Environment.getRootDirectory(), "etc", "permissions"), false);
1359            // Only read features from OEM
1360            readPermissions(Environment.buildPath(
1361                    Environment.getOemDirectory(), "etc", "permissions"), true);
1362
1363            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1364
1365            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1366                    mSdkVersion, mOnlyCore);
1367
1368            String customResolverActivity = Resources.getSystem().getString(
1369                    R.string.config_customResolverActivity);
1370            if (TextUtils.isEmpty(customResolverActivity)) {
1371                customResolverActivity = null;
1372            } else {
1373                mCustomResolverComponentName = ComponentName.unflattenFromString(
1374                        customResolverActivity);
1375            }
1376
1377            long startTime = SystemClock.uptimeMillis();
1378
1379            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1380                    startTime);
1381
1382            // Set flag to monitor and not change apk file paths when
1383            // scanning install directories.
1384            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1385
1386            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1387
1388            /**
1389             * Add everything in the in the boot class path to the
1390             * list of process files because dexopt will have been run
1391             * if necessary during zygote startup.
1392             */
1393            String bootClassPath = System.getProperty("java.boot.class.path");
1394            if (bootClassPath != null) {
1395                String[] paths = splitString(bootClassPath, ':');
1396                for (int i=0; i<paths.length; i++) {
1397                    alreadyDexOpted.add(paths[i]);
1398                }
1399            } else {
1400                Slog.w(TAG, "No BOOTCLASSPATH found!");
1401            }
1402
1403            boolean didDexOptLibraryOrTool = false;
1404
1405            final List<String> instructionSets = getAllInstructionSets();
1406
1407            /**
1408             * Ensure all external libraries have had dexopt run on them.
1409             */
1410            if (mSharedLibraries.size() > 0) {
1411                // NOTE: For now, we're compiling these system "shared libraries"
1412                // (and framework jars) into all available architectures. It's possible
1413                // to compile them only when we come across an app that uses them (there's
1414                // already logic for that in scanPackageLI) but that adds some complexity.
1415                for (String instructionSet : instructionSets) {
1416                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1417                        final String lib = libEntry.path;
1418                        if (lib == null) {
1419                            continue;
1420                        }
1421
1422                        try {
1423                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1424                                alreadyDexOpted.add(lib);
1425
1426                                // The list of "shared libraries" we have at this point is
1427                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1428                                didDexOptLibraryOrTool = true;
1429                            }
1430                        } catch (FileNotFoundException e) {
1431                            Slog.w(TAG, "Library not found: " + lib);
1432                        } catch (IOException e) {
1433                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1434                                    + e.getMessage());
1435                        }
1436                    }
1437                }
1438            }
1439
1440            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1441
1442            // Gross hack for now: we know this file doesn't contain any
1443            // code, so don't dexopt it to avoid the resulting log spew.
1444            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1445
1446            // Gross hack for now: we know this file is only part of
1447            // the boot class path for art, so don't dexopt it to
1448            // avoid the resulting log spew.
1449            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1450
1451            /**
1452             * And there are a number of commands implemented in Java, which
1453             * we currently need to do the dexopt on so that they can be
1454             * run from a non-root shell.
1455             */
1456            String[] frameworkFiles = frameworkDir.list();
1457            if (frameworkFiles != null) {
1458                // TODO: We could compile these only for the most preferred ABI. We should
1459                // first double check that the dex files for these commands are not referenced
1460                // by other system apps.
1461                for (String instructionSet : instructionSets) {
1462                    for (int i=0; i<frameworkFiles.length; i++) {
1463                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1464                        String path = libPath.getPath();
1465                        // Skip the file if we already did it.
1466                        if (alreadyDexOpted.contains(path)) {
1467                            continue;
1468                        }
1469                        // Skip the file if it is not a type we want to dexopt.
1470                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1471                            continue;
1472                        }
1473                        try {
1474                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1475                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1476                                didDexOptLibraryOrTool = true;
1477                            }
1478                        } catch (FileNotFoundException e) {
1479                            Slog.w(TAG, "Jar not found: " + path);
1480                        } catch (IOException e) {
1481                            Slog.w(TAG, "Exception reading jar: " + path, e);
1482                        }
1483                    }
1484                }
1485            }
1486
1487            if (didDexOptLibraryOrTool) {
1488                pruneDexFiles(new File(dataDir, "dalvik-cache"));
1489            }
1490
1491            // Collect vendor overlay packages.
1492            // (Do this before scanning any apps.)
1493            // For security and version matching reason, only consider
1494            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1495            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1496            mVendorOverlayInstallObserver = new AppDirObserver(
1497                vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1498            mVendorOverlayInstallObserver.startWatching();
1499            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1500                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1501
1502            // Find base frameworks (resource packages without code).
1503            mFrameworkInstallObserver = new AppDirObserver(
1504                frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1505            mFrameworkInstallObserver.startWatching();
1506            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1507                    | PackageParser.PARSE_IS_SYSTEM_DIR
1508                    | PackageParser.PARSE_IS_PRIVILEGED,
1509                    scanMode | SCAN_NO_DEX, 0);
1510
1511            // Collected privileged system packages.
1512            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1513            mPrivilegedInstallObserver = new AppDirObserver(
1514                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1515            mPrivilegedInstallObserver.startWatching();
1516                scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1517                        | PackageParser.PARSE_IS_SYSTEM_DIR
1518                        | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1519
1520            // Collect ordinary system packages.
1521            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1522            mSystemInstallObserver = new AppDirObserver(
1523                systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1524            mSystemInstallObserver.startWatching();
1525            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1526                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1527
1528            // Collect all vendor packages.
1529            File vendorAppDir = new File("/vendor/app");
1530            try {
1531                vendorAppDir = vendorAppDir.getCanonicalFile();
1532            } catch (IOException e) {
1533                // failed to look up canonical path, continue with original one
1534            }
1535            mVendorInstallObserver = new AppDirObserver(
1536                vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1537            mVendorInstallObserver.startWatching();
1538            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1539                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1540
1541            // Collect all OEM packages.
1542            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1543            mOemInstallObserver = new AppDirObserver(
1544                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1545            mOemInstallObserver.startWatching();
1546            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1547                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1548
1549            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1550            mInstaller.moveFiles();
1551
1552            // Prune any system packages that no longer exist.
1553            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1554            if (!mOnlyCore) {
1555                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1556                while (psit.hasNext()) {
1557                    PackageSetting ps = psit.next();
1558
1559                    /*
1560                     * If this is not a system app, it can't be a
1561                     * disable system app.
1562                     */
1563                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1564                        continue;
1565                    }
1566
1567                    /*
1568                     * If the package is scanned, it's not erased.
1569                     */
1570                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1571                    if (scannedPkg != null) {
1572                        /*
1573                         * If the system app is both scanned and in the
1574                         * disabled packages list, then it must have been
1575                         * added via OTA. Remove it from the currently
1576                         * scanned package so the previously user-installed
1577                         * application can be scanned.
1578                         */
1579                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1580                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1581                                    + "; removing system app");
1582                            removePackageLI(ps, true);
1583                        }
1584
1585                        continue;
1586                    }
1587
1588                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1589                        psit.remove();
1590                        String msg = "System package " + ps.name
1591                                + " no longer exists; wiping its data";
1592                        reportSettingsProblem(Log.WARN, msg);
1593                        removeDataDirsLI(ps.name);
1594                    } else {
1595                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1596                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1597                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1598                        }
1599                    }
1600                }
1601            }
1602
1603            //look for any incomplete package installations
1604            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1605            //clean up list
1606            for(int i = 0; i < deletePkgsList.size(); i++) {
1607                //clean up here
1608                cleanupInstallFailedPackage(deletePkgsList.get(i));
1609            }
1610            //delete tmp files
1611            deleteTempPackageFiles();
1612
1613            // Remove any shared userIDs that have no associated packages
1614            mSettings.pruneSharedUsersLPw();
1615
1616            if (!mOnlyCore) {
1617                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1618                        SystemClock.uptimeMillis());
1619                mAppInstallObserver = new AppDirObserver(
1620                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1621                mAppInstallObserver.startWatching();
1622                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1623
1624                mDrmAppInstallObserver = new AppDirObserver(
1625                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1626                mDrmAppInstallObserver.startWatching();
1627                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1628                        scanMode, 0);
1629
1630                /**
1631                 * Remove disable package settings for any updated system
1632                 * apps that were removed via an OTA. If they're not a
1633                 * previously-updated app, remove them completely.
1634                 * Otherwise, just revoke their system-level permissions.
1635                 */
1636                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1637                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1638                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1639
1640                    String msg;
1641                    if (deletedPkg == null) {
1642                        msg = "Updated system package " + deletedAppName
1643                                + " no longer exists; wiping its data";
1644                        removeDataDirsLI(deletedAppName);
1645                    } else {
1646                        msg = "Updated system app + " + deletedAppName
1647                                + " no longer present; removing system privileges for "
1648                                + deletedAppName;
1649
1650                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1651
1652                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1653                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1654                    }
1655                    reportSettingsProblem(Log.WARN, msg);
1656                }
1657            } else {
1658                mAppInstallObserver = null;
1659                mDrmAppInstallObserver = null;
1660            }
1661
1662            // Now that we know all of the shared libraries, update all clients to have
1663            // the correct library paths.
1664            updateAllSharedLibrariesLPw();
1665
1666            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1667                adjustCpuAbisForSharedUserLPw(setting.packages, true /* do dexopt */,
1668                        false /* force dexopt */, false /* defer dexopt */);
1669            }
1670
1671            // Now that we know all the packages we are keeping,
1672            // read and update their last usage times.
1673            mPackageUsage.readLP();
1674
1675            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1676                    SystemClock.uptimeMillis());
1677            Slog.i(TAG, "Time to scan packages: "
1678                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1679                    + " seconds");
1680
1681            // If the platform SDK has changed since the last time we booted,
1682            // we need to re-grant app permission to catch any new ones that
1683            // appear.  This is really a hack, and means that apps can in some
1684            // cases get permissions that the user didn't initially explicitly
1685            // allow...  it would be nice to have some better way to handle
1686            // this situation.
1687            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1688                    != mSdkVersion;
1689            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1690                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1691                    + "; regranting permissions for internal storage");
1692            mSettings.mInternalSdkPlatform = mSdkVersion;
1693
1694            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1695                    | (regrantPermissions
1696                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1697                            : 0));
1698
1699            // If this is the first boot, and it is a normal boot, then
1700            // we need to initialize the default preferred apps.
1701            if (!mRestoredSettings && !onlyCore) {
1702                mSettings.readDefaultPreferredAppsLPw(this, 0);
1703            }
1704
1705            // All the changes are done during package scanning.
1706            mSettings.updateInternalDatabaseVersion();
1707
1708            // can downgrade to reader
1709            mSettings.writeLPr();
1710
1711            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1712                    SystemClock.uptimeMillis());
1713
1714
1715            mRequiredVerifierPackage = getRequiredVerifierLPr();
1716        } // synchronized (mPackages)
1717        } // synchronized (mInstallLock)
1718
1719        mInstallerService = new PackageInstallerService(context, this, mAppStagingDir);
1720
1721        // Now after opening every single application zip, make sure they
1722        // are all flushed.  Not really needed, but keeps things nice and
1723        // tidy.
1724        Runtime.getRuntime().gc();
1725    }
1726
1727    private static void pruneDexFiles(File cacheDir) {
1728        // If we had to do a dexopt of one of the previous
1729        // things, then something on the system has changed.
1730        // Consider this significant, and wipe away all other
1731        // existing dexopt files to ensure we don't leave any
1732        // dangling around.
1733        //
1734        // Additionally, delete all dex files from the root directory
1735        // since there shouldn't be any there anyway.
1736        //
1737        // Note: This isn't as good an indicator as it used to be. It
1738        // used to include the boot classpath but at some point
1739        // DexFile.isDexOptNeeded started returning false for the boot
1740        // class path files in all cases. It is very possible in a
1741        // small maintenance release update that the library and tool
1742        // jars may be unchanged but APK could be removed resulting in
1743        // unused dalvik-cache files.
1744        File[] files = cacheDir.listFiles();
1745        if (files != null) {
1746            for (File file : files) {
1747                if (!file.isDirectory()) {
1748                    Slog.i(TAG, "Pruning dalvik file: " + file.getAbsolutePath());
1749                    file.delete();
1750                } else {
1751                    File[] subDirList = file.listFiles();
1752                    if (subDirList != null) {
1753                        for (File subDirFile : subDirList) {
1754                            final String fn = subDirFile.getName();
1755                            if (fn.startsWith("data@app@") || fn.startsWith("data@app-private@")) {
1756                                Slog.i(TAG, "Pruning dalvik file: " + fn);
1757                                subDirFile.delete();
1758                            }
1759                        }
1760                    }
1761                }
1762            }
1763        }
1764    }
1765
1766    @Override
1767    public boolean isFirstBoot() {
1768        return !mRestoredSettings || mPackageUsage.isFirstBoot();
1769    }
1770
1771    @Override
1772    public boolean isOnlyCoreApps() {
1773        return mOnlyCore;
1774    }
1775
1776    private String getRequiredVerifierLPr() {
1777        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1778        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1779                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1780
1781        String requiredVerifier = null;
1782
1783        final int N = receivers.size();
1784        for (int i = 0; i < N; i++) {
1785            final ResolveInfo info = receivers.get(i);
1786
1787            if (info.activityInfo == null) {
1788                continue;
1789            }
1790
1791            final String packageName = info.activityInfo.packageName;
1792
1793            final PackageSetting ps = mSettings.mPackages.get(packageName);
1794            if (ps == null) {
1795                continue;
1796            }
1797
1798            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1799            if (!gp.grantedPermissions
1800                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1801                continue;
1802            }
1803
1804            if (requiredVerifier != null) {
1805                throw new RuntimeException("There can be only one required verifier");
1806            }
1807
1808            requiredVerifier = packageName;
1809        }
1810
1811        return requiredVerifier;
1812    }
1813
1814    @Override
1815    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1816            throws RemoteException {
1817        try {
1818            return super.onTransact(code, data, reply, flags);
1819        } catch (RuntimeException e) {
1820            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1821                Slog.wtf(TAG, "Package Manager Crash", e);
1822            }
1823            throw e;
1824        }
1825    }
1826
1827    void cleanupInstallFailedPackage(PackageSetting ps) {
1828        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1829        removeDataDirsLI(ps.name);
1830        if (ps.codePath != null) {
1831            if (!ps.codePath.delete()) {
1832                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1833            }
1834        }
1835        if (ps.resourcePath != null) {
1836            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1837                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1838            }
1839        }
1840        mSettings.removePackageLPw(ps.name);
1841    }
1842
1843    void readPermissions(File libraryDir, boolean onlyFeatures) {
1844        // Read permissions from .../etc/permission directory.
1845        if (!libraryDir.exists() || !libraryDir.isDirectory()) {
1846            Slog.w(TAG, "No directory " + libraryDir + ", skipping");
1847            return;
1848        }
1849        if (!libraryDir.canRead()) {
1850            Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
1851            return;
1852        }
1853
1854        // Iterate over the files in the directory and scan .xml files
1855        for (File f : libraryDir.listFiles()) {
1856            // We'll read platform.xml last
1857            if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1858                continue;
1859            }
1860
1861            if (!f.getPath().endsWith(".xml")) {
1862                Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
1863                continue;
1864            }
1865            if (!f.canRead()) {
1866                Slog.w(TAG, "Permissions library file " + f + " cannot be read");
1867                continue;
1868            }
1869
1870            readPermissionsFromXml(f, onlyFeatures);
1871        }
1872
1873        // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1874        final File permFile = new File(Environment.getRootDirectory(),
1875                "etc/permissions/platform.xml");
1876        readPermissionsFromXml(permFile, onlyFeatures);
1877    }
1878
1879    private void readPermissionsFromXml(File permFile, boolean onlyFeatures) {
1880        FileReader permReader = null;
1881        try {
1882            permReader = new FileReader(permFile);
1883        } catch (FileNotFoundException e) {
1884            Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
1885            return;
1886        }
1887
1888        try {
1889            XmlPullParser parser = Xml.newPullParser();
1890            parser.setInput(permReader);
1891
1892            XmlUtils.beginDocument(parser, "permissions");
1893
1894            while (true) {
1895                XmlUtils.nextElement(parser);
1896                if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1897                    break;
1898                }
1899
1900                String name = parser.getName();
1901                if ("group".equals(name) && !onlyFeatures) {
1902                    String gidStr = parser.getAttributeValue(null, "gid");
1903                    if (gidStr != null) {
1904                        int gid = Process.getGidForName(gidStr);
1905                        mGlobalGids = appendInt(mGlobalGids, gid);
1906                    } else {
1907                        Slog.w(TAG, "<group> without gid at "
1908                                + parser.getPositionDescription());
1909                    }
1910
1911                    XmlUtils.skipCurrentTag(parser);
1912                    continue;
1913                } else if ("permission".equals(name) && !onlyFeatures) {
1914                    String perm = parser.getAttributeValue(null, "name");
1915                    if (perm == null) {
1916                        Slog.w(TAG, "<permission> without name at "
1917                                + parser.getPositionDescription());
1918                        XmlUtils.skipCurrentTag(parser);
1919                        continue;
1920                    }
1921                    perm = perm.intern();
1922                    readPermission(parser, perm);
1923
1924                } else if ("assign-permission".equals(name) && !onlyFeatures) {
1925                    String perm = parser.getAttributeValue(null, "name");
1926                    if (perm == null) {
1927                        Slog.w(TAG, "<assign-permission> without name at "
1928                                + parser.getPositionDescription());
1929                        XmlUtils.skipCurrentTag(parser);
1930                        continue;
1931                    }
1932                    String uidStr = parser.getAttributeValue(null, "uid");
1933                    if (uidStr == null) {
1934                        Slog.w(TAG, "<assign-permission> without uid at "
1935                                + parser.getPositionDescription());
1936                        XmlUtils.skipCurrentTag(parser);
1937                        continue;
1938                    }
1939                    int uid = Process.getUidForName(uidStr);
1940                    if (uid < 0) {
1941                        Slog.w(TAG, "<assign-permission> with unknown uid \""
1942                                + uidStr + "\" at "
1943                                + parser.getPositionDescription());
1944                        XmlUtils.skipCurrentTag(parser);
1945                        continue;
1946                    }
1947                    perm = perm.intern();
1948                    HashSet<String> perms = mSystemPermissions.get(uid);
1949                    if (perms == null) {
1950                        perms = new HashSet<String>();
1951                        mSystemPermissions.put(uid, perms);
1952                    }
1953                    perms.add(perm);
1954                    XmlUtils.skipCurrentTag(parser);
1955
1956                } else if ("library".equals(name) && !onlyFeatures) {
1957                    String lname = parser.getAttributeValue(null, "name");
1958                    String lfile = parser.getAttributeValue(null, "file");
1959                    if (lname == null) {
1960                        Slog.w(TAG, "<library> without name at "
1961                                + parser.getPositionDescription());
1962                    } else if (lfile == null) {
1963                        Slog.w(TAG, "<library> without file at "
1964                                + parser.getPositionDescription());
1965                    } else {
1966                        //Log.i(TAG, "Got library " + lname + " in " + lfile);
1967                        mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null));
1968                    }
1969                    XmlUtils.skipCurrentTag(parser);
1970                    continue;
1971
1972                } else if ("feature".equals(name)) {
1973                    String fname = parser.getAttributeValue(null, "name");
1974                    if (fname == null) {
1975                        Slog.w(TAG, "<feature> without name at "
1976                                + parser.getPositionDescription());
1977                    } else {
1978                        //Log.i(TAG, "Got feature " + fname);
1979                        FeatureInfo fi = new FeatureInfo();
1980                        fi.name = fname;
1981                        mAvailableFeatures.put(fname, fi);
1982                    }
1983                    XmlUtils.skipCurrentTag(parser);
1984                    continue;
1985
1986                } else {
1987                    XmlUtils.skipCurrentTag(parser);
1988                    continue;
1989                }
1990
1991            }
1992            permReader.close();
1993        } catch (XmlPullParserException e) {
1994            Slog.w(TAG, "Got execption parsing permissions.", e);
1995        } catch (IOException e) {
1996            Slog.w(TAG, "Got execption parsing permissions.", e);
1997        }
1998    }
1999
2000    void readPermission(XmlPullParser parser, String name)
2001            throws IOException, XmlPullParserException {
2002
2003        name = name.intern();
2004
2005        BasePermission bp = mSettings.mPermissions.get(name);
2006        if (bp == null) {
2007            bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
2008            mSettings.mPermissions.put(name, bp);
2009        }
2010        int outerDepth = parser.getDepth();
2011        int type;
2012        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2013               && (type != XmlPullParser.END_TAG
2014                       || parser.getDepth() > outerDepth)) {
2015            if (type == XmlPullParser.END_TAG
2016                    || type == XmlPullParser.TEXT) {
2017                continue;
2018            }
2019
2020            String tagName = parser.getName();
2021            if ("group".equals(tagName)) {
2022                String gidStr = parser.getAttributeValue(null, "gid");
2023                if (gidStr != null) {
2024                    int gid = Process.getGidForName(gidStr);
2025                    bp.gids = appendInt(bp.gids, gid);
2026                } else {
2027                    Slog.w(TAG, "<group> without gid at "
2028                            + parser.getPositionDescription());
2029                }
2030            }
2031            XmlUtils.skipCurrentTag(parser);
2032        }
2033    }
2034
2035    static int[] appendInts(int[] cur, int[] add) {
2036        if (add == null) return cur;
2037        if (cur == null) return add;
2038        final int N = add.length;
2039        for (int i=0; i<N; i++) {
2040            cur = appendInt(cur, add[i]);
2041        }
2042        return cur;
2043    }
2044
2045    static int[] removeInts(int[] cur, int[] rem) {
2046        if (rem == null) return cur;
2047        if (cur == null) return cur;
2048        final int N = rem.length;
2049        for (int i=0; i<N; i++) {
2050            cur = removeInt(cur, rem[i]);
2051        }
2052        return cur;
2053    }
2054
2055    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2056        if (!sUserManager.exists(userId)) return null;
2057        final PackageSetting ps = (PackageSetting) p.mExtras;
2058        if (ps == null) {
2059            return null;
2060        }
2061        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2062        final PackageUserState state = ps.readUserState(userId);
2063        return PackageParser.generatePackageInfo(p, gp.gids, flags,
2064                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
2065                state, userId);
2066    }
2067
2068    @Override
2069    public boolean isPackageAvailable(String packageName, int userId) {
2070        if (!sUserManager.exists(userId)) return false;
2071        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
2072        synchronized (mPackages) {
2073            PackageParser.Package p = mPackages.get(packageName);
2074            if (p != null) {
2075                final PackageSetting ps = (PackageSetting) p.mExtras;
2076                if (ps != null) {
2077                    final PackageUserState state = ps.readUserState(userId);
2078                    if (state != null) {
2079                        return PackageParser.isAvailable(state);
2080                    }
2081                }
2082            }
2083        }
2084        return false;
2085    }
2086
2087    @Override
2088    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2089        if (!sUserManager.exists(userId)) return null;
2090        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
2091        // reader
2092        synchronized (mPackages) {
2093            PackageParser.Package p = mPackages.get(packageName);
2094            if (DEBUG_PACKAGE_INFO)
2095                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2096            if (p != null) {
2097                return generatePackageInfo(p, flags, userId);
2098            }
2099            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2100                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2101            }
2102        }
2103        return null;
2104    }
2105
2106    @Override
2107    public String[] currentToCanonicalPackageNames(String[] names) {
2108        String[] out = new String[names.length];
2109        // reader
2110        synchronized (mPackages) {
2111            for (int i=names.length-1; i>=0; i--) {
2112                PackageSetting ps = mSettings.mPackages.get(names[i]);
2113                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2114            }
2115        }
2116        return out;
2117    }
2118
2119    @Override
2120    public String[] canonicalToCurrentPackageNames(String[] names) {
2121        String[] out = new String[names.length];
2122        // reader
2123        synchronized (mPackages) {
2124            for (int i=names.length-1; i>=0; i--) {
2125                String cur = mSettings.mRenamedPackages.get(names[i]);
2126                out[i] = cur != null ? cur : names[i];
2127            }
2128        }
2129        return out;
2130    }
2131
2132    @Override
2133    public int getPackageUid(String packageName, int userId) {
2134        if (!sUserManager.exists(userId)) return -1;
2135        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
2136        // reader
2137        synchronized (mPackages) {
2138            PackageParser.Package p = mPackages.get(packageName);
2139            if(p != null) {
2140                return UserHandle.getUid(userId, p.applicationInfo.uid);
2141            }
2142            PackageSetting ps = mSettings.mPackages.get(packageName);
2143            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2144                return -1;
2145            }
2146            p = ps.pkg;
2147            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2148        }
2149    }
2150
2151    @Override
2152    public int[] getPackageGids(String packageName) {
2153        // reader
2154        synchronized (mPackages) {
2155            PackageParser.Package p = mPackages.get(packageName);
2156            if (DEBUG_PACKAGE_INFO)
2157                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2158            if (p != null) {
2159                final PackageSetting ps = (PackageSetting)p.mExtras;
2160                return ps.getGids();
2161            }
2162        }
2163        // stupid thing to indicate an error.
2164        return new int[0];
2165    }
2166
2167    static final PermissionInfo generatePermissionInfo(
2168            BasePermission bp, int flags) {
2169        if (bp.perm != null) {
2170            return PackageParser.generatePermissionInfo(bp.perm, flags);
2171        }
2172        PermissionInfo pi = new PermissionInfo();
2173        pi.name = bp.name;
2174        pi.packageName = bp.sourcePackage;
2175        pi.nonLocalizedLabel = bp.name;
2176        pi.protectionLevel = bp.protectionLevel;
2177        return pi;
2178    }
2179
2180    @Override
2181    public PermissionInfo getPermissionInfo(String name, int flags) {
2182        // reader
2183        synchronized (mPackages) {
2184            final BasePermission p = mSettings.mPermissions.get(name);
2185            if (p != null) {
2186                return generatePermissionInfo(p, flags);
2187            }
2188            return null;
2189        }
2190    }
2191
2192    @Override
2193    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2194        // reader
2195        synchronized (mPackages) {
2196            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2197            for (BasePermission p : mSettings.mPermissions.values()) {
2198                if (group == null) {
2199                    if (p.perm == null || p.perm.info.group == null) {
2200                        out.add(generatePermissionInfo(p, flags));
2201                    }
2202                } else {
2203                    if (p.perm != null && group.equals(p.perm.info.group)) {
2204                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2205                    }
2206                }
2207            }
2208
2209            if (out.size() > 0) {
2210                return out;
2211            }
2212            return mPermissionGroups.containsKey(group) ? out : null;
2213        }
2214    }
2215
2216    @Override
2217    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2218        // reader
2219        synchronized (mPackages) {
2220            return PackageParser.generatePermissionGroupInfo(
2221                    mPermissionGroups.get(name), flags);
2222        }
2223    }
2224
2225    @Override
2226    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2227        // reader
2228        synchronized (mPackages) {
2229            final int N = mPermissionGroups.size();
2230            ArrayList<PermissionGroupInfo> out
2231                    = new ArrayList<PermissionGroupInfo>(N);
2232            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2233                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2234            }
2235            return out;
2236        }
2237    }
2238
2239    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2240            int userId) {
2241        if (!sUserManager.exists(userId)) return null;
2242        PackageSetting ps = mSettings.mPackages.get(packageName);
2243        if (ps != null) {
2244            if (ps.pkg == null) {
2245                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2246                        flags, userId);
2247                if (pInfo != null) {
2248                    return pInfo.applicationInfo;
2249                }
2250                return null;
2251            }
2252            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2253                    ps.readUserState(userId), userId);
2254        }
2255        return null;
2256    }
2257
2258    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2259            int userId) {
2260        if (!sUserManager.exists(userId)) return null;
2261        PackageSetting ps = mSettings.mPackages.get(packageName);
2262        if (ps != null) {
2263            PackageParser.Package pkg = ps.pkg;
2264            if (pkg == null) {
2265                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2266                    return null;
2267                }
2268                // TODO: teach about reading split name
2269                pkg = new PackageParser.Package(packageName, null);
2270                pkg.applicationInfo.packageName = packageName;
2271                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2272                pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
2273                pkg.applicationInfo.sourceDir = ps.codePathString;
2274                pkg.applicationInfo.dataDir =
2275                        getDataPathForPackage(packageName, 0).getPath();
2276                pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
2277                pkg.applicationInfo.requiredCpuAbi = ps.requiredCpuAbiString;
2278            }
2279            return generatePackageInfo(pkg, flags, userId);
2280        }
2281        return null;
2282    }
2283
2284    @Override
2285    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2286        if (!sUserManager.exists(userId)) return null;
2287        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2288        // writer
2289        synchronized (mPackages) {
2290            PackageParser.Package p = mPackages.get(packageName);
2291            if (DEBUG_PACKAGE_INFO) Log.v(
2292                    TAG, "getApplicationInfo " + packageName
2293                    + ": " + p);
2294            if (p != null) {
2295                PackageSetting ps = mSettings.mPackages.get(packageName);
2296                if (ps == null) return null;
2297                // Note: isEnabledLP() does not apply here - always return info
2298                return PackageParser.generateApplicationInfo(
2299                        p, flags, ps.readUserState(userId), userId);
2300            }
2301            if ("android".equals(packageName)||"system".equals(packageName)) {
2302                return mAndroidApplication;
2303            }
2304            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2305                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2306            }
2307        }
2308        return null;
2309    }
2310
2311
2312    @Override
2313    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2314        mContext.enforceCallingOrSelfPermission(
2315                android.Manifest.permission.CLEAR_APP_CACHE, null);
2316        // Queue up an async operation since clearing cache may take a little while.
2317        mHandler.post(new Runnable() {
2318            public void run() {
2319                mHandler.removeCallbacks(this);
2320                int retCode = -1;
2321                synchronized (mInstallLock) {
2322                    retCode = mInstaller.freeCache(freeStorageSize);
2323                    if (retCode < 0) {
2324                        Slog.w(TAG, "Couldn't clear application caches");
2325                    }
2326                }
2327                if (observer != null) {
2328                    try {
2329                        observer.onRemoveCompleted(null, (retCode >= 0));
2330                    } catch (RemoteException e) {
2331                        Slog.w(TAG, "RemoveException when invoking call back");
2332                    }
2333                }
2334            }
2335        });
2336    }
2337
2338    @Override
2339    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2340        mContext.enforceCallingOrSelfPermission(
2341                android.Manifest.permission.CLEAR_APP_CACHE, null);
2342        // Queue up an async operation since clearing cache may take a little while.
2343        mHandler.post(new Runnable() {
2344            public void run() {
2345                mHandler.removeCallbacks(this);
2346                int retCode = -1;
2347                synchronized (mInstallLock) {
2348                    retCode = mInstaller.freeCache(freeStorageSize);
2349                    if (retCode < 0) {
2350                        Slog.w(TAG, "Couldn't clear application caches");
2351                    }
2352                }
2353                if(pi != null) {
2354                    try {
2355                        // Callback via pending intent
2356                        int code = (retCode >= 0) ? 1 : 0;
2357                        pi.sendIntent(null, code, null,
2358                                null, null);
2359                    } catch (SendIntentException e1) {
2360                        Slog.i(TAG, "Failed to send pending intent");
2361                    }
2362                }
2363            }
2364        });
2365    }
2366
2367    void freeStorage(long freeStorageSize) throws IOException {
2368        synchronized (mInstallLock) {
2369            if (mInstaller.freeCache(freeStorageSize) < 0) {
2370                throw new IOException("Failed to free enough space");
2371            }
2372        }
2373    }
2374
2375    @Override
2376    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2377        if (!sUserManager.exists(userId)) return null;
2378        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2379        synchronized (mPackages) {
2380            PackageParser.Activity a = mActivities.mActivities.get(component);
2381
2382            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2383            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2384                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2385                if (ps == null) return null;
2386                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2387                        userId);
2388            }
2389            if (mResolveComponentName.equals(component)) {
2390                return mResolveActivity;
2391            }
2392        }
2393        return null;
2394    }
2395
2396    @Override
2397    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2398            String resolvedType) {
2399        synchronized (mPackages) {
2400            PackageParser.Activity a = mActivities.mActivities.get(component);
2401            if (a == null) {
2402                return false;
2403            }
2404            for (int i=0; i<a.intents.size(); i++) {
2405                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2406                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2407                    return true;
2408                }
2409            }
2410            return false;
2411        }
2412    }
2413
2414    @Override
2415    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2416        if (!sUserManager.exists(userId)) return null;
2417        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2418        synchronized (mPackages) {
2419            PackageParser.Activity a = mReceivers.mActivities.get(component);
2420            if (DEBUG_PACKAGE_INFO) Log.v(
2421                TAG, "getReceiverInfo " + component + ": " + a);
2422            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2423                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2424                if (ps == null) return null;
2425                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2426                        userId);
2427            }
2428        }
2429        return null;
2430    }
2431
2432    @Override
2433    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2434        if (!sUserManager.exists(userId)) return null;
2435        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2436        synchronized (mPackages) {
2437            PackageParser.Service s = mServices.mServices.get(component);
2438            if (DEBUG_PACKAGE_INFO) Log.v(
2439                TAG, "getServiceInfo " + component + ": " + s);
2440            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2441                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2442                if (ps == null) return null;
2443                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2444                        userId);
2445            }
2446        }
2447        return null;
2448    }
2449
2450    @Override
2451    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2452        if (!sUserManager.exists(userId)) return null;
2453        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2454        synchronized (mPackages) {
2455            PackageParser.Provider p = mProviders.mProviders.get(component);
2456            if (DEBUG_PACKAGE_INFO) Log.v(
2457                TAG, "getProviderInfo " + component + ": " + p);
2458            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2459                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2460                if (ps == null) return null;
2461                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2462                        userId);
2463            }
2464        }
2465        return null;
2466    }
2467
2468    @Override
2469    public String[] getSystemSharedLibraryNames() {
2470        Set<String> libSet;
2471        synchronized (mPackages) {
2472            libSet = mSharedLibraries.keySet();
2473            int size = libSet.size();
2474            if (size > 0) {
2475                String[] libs = new String[size];
2476                libSet.toArray(libs);
2477                return libs;
2478            }
2479        }
2480        return null;
2481    }
2482
2483    @Override
2484    public FeatureInfo[] getSystemAvailableFeatures() {
2485        Collection<FeatureInfo> featSet;
2486        synchronized (mPackages) {
2487            featSet = mAvailableFeatures.values();
2488            int size = featSet.size();
2489            if (size > 0) {
2490                FeatureInfo[] features = new FeatureInfo[size+1];
2491                featSet.toArray(features);
2492                FeatureInfo fi = new FeatureInfo();
2493                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2494                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2495                features[size] = fi;
2496                return features;
2497            }
2498        }
2499        return null;
2500    }
2501
2502    @Override
2503    public boolean hasSystemFeature(String name) {
2504        synchronized (mPackages) {
2505            return mAvailableFeatures.containsKey(name);
2506        }
2507    }
2508
2509    private void checkValidCaller(int uid, int userId) {
2510        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2511            return;
2512
2513        throw new SecurityException("Caller uid=" + uid
2514                + " is not privileged to communicate with user=" + userId);
2515    }
2516
2517    @Override
2518    public int checkPermission(String permName, String pkgName) {
2519        synchronized (mPackages) {
2520            PackageParser.Package p = mPackages.get(pkgName);
2521            if (p != null && p.mExtras != null) {
2522                PackageSetting ps = (PackageSetting)p.mExtras;
2523                if (ps.sharedUser != null) {
2524                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2525                        return PackageManager.PERMISSION_GRANTED;
2526                    }
2527                } else if (ps.grantedPermissions.contains(permName)) {
2528                    return PackageManager.PERMISSION_GRANTED;
2529                }
2530            }
2531        }
2532        return PackageManager.PERMISSION_DENIED;
2533    }
2534
2535    @Override
2536    public int checkUidPermission(String permName, int uid) {
2537        synchronized (mPackages) {
2538            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2539            if (obj != null) {
2540                GrantedPermissions gp = (GrantedPermissions)obj;
2541                if (gp.grantedPermissions.contains(permName)) {
2542                    return PackageManager.PERMISSION_GRANTED;
2543                }
2544            } else {
2545                HashSet<String> perms = mSystemPermissions.get(uid);
2546                if (perms != null && perms.contains(permName)) {
2547                    return PackageManager.PERMISSION_GRANTED;
2548                }
2549            }
2550        }
2551        return PackageManager.PERMISSION_DENIED;
2552    }
2553
2554    /**
2555     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2556     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2557     * @param message the message to log on security exception
2558     */
2559    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2560            String message) {
2561        if (userId < 0) {
2562            throw new IllegalArgumentException("Invalid userId " + userId);
2563        }
2564        if (userId == UserHandle.getUserId(callingUid)) return;
2565        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2566            if (requireFullPermission) {
2567                mContext.enforceCallingOrSelfPermission(
2568                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2569            } else {
2570                try {
2571                    mContext.enforceCallingOrSelfPermission(
2572                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2573                } catch (SecurityException se) {
2574                    mContext.enforceCallingOrSelfPermission(
2575                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2576                }
2577            }
2578        }
2579    }
2580
2581    private BasePermission findPermissionTreeLP(String permName) {
2582        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2583            if (permName.startsWith(bp.name) &&
2584                    permName.length() > bp.name.length() &&
2585                    permName.charAt(bp.name.length()) == '.') {
2586                return bp;
2587            }
2588        }
2589        return null;
2590    }
2591
2592    private BasePermission checkPermissionTreeLP(String permName) {
2593        if (permName != null) {
2594            BasePermission bp = findPermissionTreeLP(permName);
2595            if (bp != null) {
2596                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2597                    return bp;
2598                }
2599                throw new SecurityException("Calling uid "
2600                        + Binder.getCallingUid()
2601                        + " is not allowed to add to permission tree "
2602                        + bp.name + " owned by uid " + bp.uid);
2603            }
2604        }
2605        throw new SecurityException("No permission tree found for " + permName);
2606    }
2607
2608    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2609        if (s1 == null) {
2610            return s2 == null;
2611        }
2612        if (s2 == null) {
2613            return false;
2614        }
2615        if (s1.getClass() != s2.getClass()) {
2616            return false;
2617        }
2618        return s1.equals(s2);
2619    }
2620
2621    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2622        if (pi1.icon != pi2.icon) return false;
2623        if (pi1.logo != pi2.logo) return false;
2624        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2625        if (!compareStrings(pi1.name, pi2.name)) return false;
2626        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2627        // We'll take care of setting this one.
2628        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2629        // These are not currently stored in settings.
2630        //if (!compareStrings(pi1.group, pi2.group)) return false;
2631        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2632        //if (pi1.labelRes != pi2.labelRes) return false;
2633        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2634        return true;
2635    }
2636
2637    int permissionInfoFootprint(PermissionInfo info) {
2638        int size = info.name.length();
2639        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2640        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2641        return size;
2642    }
2643
2644    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2645        int size = 0;
2646        for (BasePermission perm : mSettings.mPermissions.values()) {
2647            if (perm.uid == tree.uid) {
2648                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2649            }
2650        }
2651        return size;
2652    }
2653
2654    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2655        // We calculate the max size of permissions defined by this uid and throw
2656        // if that plus the size of 'info' would exceed our stated maximum.
2657        if (tree.uid != Process.SYSTEM_UID) {
2658            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2659            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2660                throw new SecurityException("Permission tree size cap exceeded");
2661            }
2662        }
2663    }
2664
2665    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2666        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2667            throw new SecurityException("Label must be specified in permission");
2668        }
2669        BasePermission tree = checkPermissionTreeLP(info.name);
2670        BasePermission bp = mSettings.mPermissions.get(info.name);
2671        boolean added = bp == null;
2672        boolean changed = true;
2673        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2674        if (added) {
2675            enforcePermissionCapLocked(info, tree);
2676            bp = new BasePermission(info.name, tree.sourcePackage,
2677                    BasePermission.TYPE_DYNAMIC);
2678        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2679            throw new SecurityException(
2680                    "Not allowed to modify non-dynamic permission "
2681                    + info.name);
2682        } else {
2683            if (bp.protectionLevel == fixedLevel
2684                    && bp.perm.owner.equals(tree.perm.owner)
2685                    && bp.uid == tree.uid
2686                    && comparePermissionInfos(bp.perm.info, info)) {
2687                changed = false;
2688            }
2689        }
2690        bp.protectionLevel = fixedLevel;
2691        info = new PermissionInfo(info);
2692        info.protectionLevel = fixedLevel;
2693        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2694        bp.perm.info.packageName = tree.perm.info.packageName;
2695        bp.uid = tree.uid;
2696        if (added) {
2697            mSettings.mPermissions.put(info.name, bp);
2698        }
2699        if (changed) {
2700            if (!async) {
2701                mSettings.writeLPr();
2702            } else {
2703                scheduleWriteSettingsLocked();
2704            }
2705        }
2706        return added;
2707    }
2708
2709    @Override
2710    public boolean addPermission(PermissionInfo info) {
2711        synchronized (mPackages) {
2712            return addPermissionLocked(info, false);
2713        }
2714    }
2715
2716    @Override
2717    public boolean addPermissionAsync(PermissionInfo info) {
2718        synchronized (mPackages) {
2719            return addPermissionLocked(info, true);
2720        }
2721    }
2722
2723    @Override
2724    public void removePermission(String name) {
2725        synchronized (mPackages) {
2726            checkPermissionTreeLP(name);
2727            BasePermission bp = mSettings.mPermissions.get(name);
2728            if (bp != null) {
2729                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2730                    throw new SecurityException(
2731                            "Not allowed to modify non-dynamic permission "
2732                            + name);
2733                }
2734                mSettings.mPermissions.remove(name);
2735                mSettings.writeLPr();
2736            }
2737        }
2738    }
2739
2740    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2741        int index = pkg.requestedPermissions.indexOf(bp.name);
2742        if (index == -1) {
2743            throw new SecurityException("Package " + pkg.packageName
2744                    + " has not requested permission " + bp.name);
2745        }
2746        boolean isNormal =
2747                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2748                        == PermissionInfo.PROTECTION_NORMAL);
2749        boolean isDangerous =
2750                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2751                        == PermissionInfo.PROTECTION_DANGEROUS);
2752        boolean isDevelopment =
2753                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2754
2755        if (!isNormal && !isDangerous && !isDevelopment) {
2756            throw new SecurityException("Permission " + bp.name
2757                    + " is not a changeable permission type");
2758        }
2759
2760        if (isNormal || isDangerous) {
2761            if (pkg.requestedPermissionsRequired.get(index)) {
2762                throw new SecurityException("Can't change " + bp.name
2763                        + ". It is required by the application");
2764            }
2765        }
2766    }
2767
2768    @Override
2769    public void grantPermission(String packageName, String permissionName) {
2770        mContext.enforceCallingOrSelfPermission(
2771                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2772        synchronized (mPackages) {
2773            final PackageParser.Package pkg = mPackages.get(packageName);
2774            if (pkg == null) {
2775                throw new IllegalArgumentException("Unknown package: " + packageName);
2776            }
2777            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2778            if (bp == null) {
2779                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2780            }
2781
2782            checkGrantRevokePermissions(pkg, bp);
2783
2784            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2785            if (ps == null) {
2786                return;
2787            }
2788            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2789            if (gp.grantedPermissions.add(permissionName)) {
2790                if (ps.haveGids) {
2791                    gp.gids = appendInts(gp.gids, bp.gids);
2792                }
2793                mSettings.writeLPr();
2794            }
2795        }
2796    }
2797
2798    @Override
2799    public void revokePermission(String packageName, String permissionName) {
2800        int changedAppId = -1;
2801
2802        synchronized (mPackages) {
2803            final PackageParser.Package pkg = mPackages.get(packageName);
2804            if (pkg == null) {
2805                throw new IllegalArgumentException("Unknown package: " + packageName);
2806            }
2807            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2808                mContext.enforceCallingOrSelfPermission(
2809                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2810            }
2811            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2812            if (bp == null) {
2813                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2814            }
2815
2816            checkGrantRevokePermissions(pkg, bp);
2817
2818            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2819            if (ps == null) {
2820                return;
2821            }
2822            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2823            if (gp.grantedPermissions.remove(permissionName)) {
2824                gp.grantedPermissions.remove(permissionName);
2825                if (ps.haveGids) {
2826                    gp.gids = removeInts(gp.gids, bp.gids);
2827                }
2828                mSettings.writeLPr();
2829                changedAppId = ps.appId;
2830            }
2831        }
2832
2833        if (changedAppId >= 0) {
2834            // We changed the perm on someone, kill its processes.
2835            IActivityManager am = ActivityManagerNative.getDefault();
2836            if (am != null) {
2837                final int callingUserId = UserHandle.getCallingUserId();
2838                final long ident = Binder.clearCallingIdentity();
2839                try {
2840                    //XXX we should only revoke for the calling user's app permissions,
2841                    // but for now we impact all users.
2842                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2843                    //        "revoke " + permissionName);
2844                    int[] users = sUserManager.getUserIds();
2845                    for (int user : users) {
2846                        am.killUid(UserHandle.getUid(user, changedAppId),
2847                                "revoke " + permissionName);
2848                    }
2849                } catch (RemoteException e) {
2850                } finally {
2851                    Binder.restoreCallingIdentity(ident);
2852                }
2853            }
2854        }
2855    }
2856
2857    @Override
2858    public boolean isProtectedBroadcast(String actionName) {
2859        synchronized (mPackages) {
2860            return mProtectedBroadcasts.contains(actionName);
2861        }
2862    }
2863
2864    @Override
2865    public int checkSignatures(String pkg1, String pkg2) {
2866        synchronized (mPackages) {
2867            final PackageParser.Package p1 = mPackages.get(pkg1);
2868            final PackageParser.Package p2 = mPackages.get(pkg2);
2869            if (p1 == null || p1.mExtras == null
2870                    || p2 == null || p2.mExtras == null) {
2871                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2872            }
2873            return compareSignatures(p1.mSignatures, p2.mSignatures);
2874        }
2875    }
2876
2877    @Override
2878    public int checkUidSignatures(int uid1, int uid2) {
2879        // Map to base uids.
2880        uid1 = UserHandle.getAppId(uid1);
2881        uid2 = UserHandle.getAppId(uid2);
2882        // reader
2883        synchronized (mPackages) {
2884            Signature[] s1;
2885            Signature[] s2;
2886            Object obj = mSettings.getUserIdLPr(uid1);
2887            if (obj != null) {
2888                if (obj instanceof SharedUserSetting) {
2889                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2890                } else if (obj instanceof PackageSetting) {
2891                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2892                } else {
2893                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2894                }
2895            } else {
2896                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2897            }
2898            obj = mSettings.getUserIdLPr(uid2);
2899            if (obj != null) {
2900                if (obj instanceof SharedUserSetting) {
2901                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2902                } else if (obj instanceof PackageSetting) {
2903                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2904                } else {
2905                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2906                }
2907            } else {
2908                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2909            }
2910            return compareSignatures(s1, s2);
2911        }
2912    }
2913
2914    /**
2915     * Compares two sets of signatures. Returns:
2916     * <br />
2917     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2918     * <br />
2919     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2920     * <br />
2921     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2922     * <br />
2923     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2924     * <br />
2925     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2926     */
2927    static int compareSignatures(Signature[] s1, Signature[] s2) {
2928        if (s1 == null) {
2929            return s2 == null
2930                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2931                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2932        }
2933
2934        if (s2 == null) {
2935            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2936        }
2937
2938        if (s1.length != s2.length) {
2939            return PackageManager.SIGNATURE_NO_MATCH;
2940        }
2941
2942        // Since both signature sets are of size 1, we can compare without HashSets.
2943        if (s1.length == 1) {
2944            return s1[0].equals(s2[0]) ?
2945                    PackageManager.SIGNATURE_MATCH :
2946                    PackageManager.SIGNATURE_NO_MATCH;
2947        }
2948
2949        HashSet<Signature> set1 = new HashSet<Signature>();
2950        for (Signature sig : s1) {
2951            set1.add(sig);
2952        }
2953        HashSet<Signature> set2 = new HashSet<Signature>();
2954        for (Signature sig : s2) {
2955            set2.add(sig);
2956        }
2957        // Make sure s2 contains all signatures in s1.
2958        if (set1.equals(set2)) {
2959            return PackageManager.SIGNATURE_MATCH;
2960        }
2961        return PackageManager.SIGNATURE_NO_MATCH;
2962    }
2963
2964    /**
2965     * If the database version for this type of package (internal storage or
2966     * external storage) is less than the version where package signatures
2967     * were updated, return true.
2968     */
2969    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2970        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2971                DatabaseVersion.SIGNATURE_END_ENTITY))
2972                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2973                        DatabaseVersion.SIGNATURE_END_ENTITY));
2974    }
2975
2976    /**
2977     * Used for backward compatibility to make sure any packages with
2978     * certificate chains get upgraded to the new style. {@code existingSigs}
2979     * will be in the old format (since they were stored on disk from before the
2980     * system upgrade) and {@code scannedSigs} will be in the newer format.
2981     */
2982    private int compareSignaturesCompat(PackageSignatures existingSigs,
2983            PackageParser.Package scannedPkg) {
2984        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2985            return PackageManager.SIGNATURE_NO_MATCH;
2986        }
2987
2988        HashSet<Signature> existingSet = new HashSet<Signature>();
2989        for (Signature sig : existingSigs.mSignatures) {
2990            existingSet.add(sig);
2991        }
2992        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2993        for (Signature sig : scannedPkg.mSignatures) {
2994            try {
2995                Signature[] chainSignatures = sig.getChainSignatures();
2996                for (Signature chainSig : chainSignatures) {
2997                    scannedCompatSet.add(chainSig);
2998                }
2999            } catch (CertificateEncodingException e) {
3000                scannedCompatSet.add(sig);
3001            }
3002        }
3003        /*
3004         * Make sure the expanded scanned set contains all signatures in the
3005         * existing one.
3006         */
3007        if (scannedCompatSet.equals(existingSet)) {
3008            // Migrate the old signatures to the new scheme.
3009            existingSigs.assignSignatures(scannedPkg.mSignatures);
3010            // The new KeySets will be re-added later in the scanning process.
3011            mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName);
3012            return PackageManager.SIGNATURE_MATCH;
3013        }
3014        return PackageManager.SIGNATURE_NO_MATCH;
3015    }
3016
3017    @Override
3018    public String[] getPackagesForUid(int uid) {
3019        uid = UserHandle.getAppId(uid);
3020        // reader
3021        synchronized (mPackages) {
3022            Object obj = mSettings.getUserIdLPr(uid);
3023            if (obj instanceof SharedUserSetting) {
3024                final SharedUserSetting sus = (SharedUserSetting) obj;
3025                final int N = sus.packages.size();
3026                final String[] res = new String[N];
3027                final Iterator<PackageSetting> it = sus.packages.iterator();
3028                int i = 0;
3029                while (it.hasNext()) {
3030                    res[i++] = it.next().name;
3031                }
3032                return res;
3033            } else if (obj instanceof PackageSetting) {
3034                final PackageSetting ps = (PackageSetting) obj;
3035                return new String[] { ps.name };
3036            }
3037        }
3038        return null;
3039    }
3040
3041    @Override
3042    public String getNameForUid(int uid) {
3043        // reader
3044        synchronized (mPackages) {
3045            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3046            if (obj instanceof SharedUserSetting) {
3047                final SharedUserSetting sus = (SharedUserSetting) obj;
3048                return sus.name + ":" + sus.userId;
3049            } else if (obj instanceof PackageSetting) {
3050                final PackageSetting ps = (PackageSetting) obj;
3051                return ps.name;
3052            }
3053        }
3054        return null;
3055    }
3056
3057    @Override
3058    public int getUidForSharedUser(String sharedUserName) {
3059        if(sharedUserName == null) {
3060            return -1;
3061        }
3062        // reader
3063        synchronized (mPackages) {
3064            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
3065            if (suid == null) {
3066                return -1;
3067            }
3068            return suid.userId;
3069        }
3070    }
3071
3072    @Override
3073    public int getFlagsForUid(int uid) {
3074        synchronized (mPackages) {
3075            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3076            if (obj instanceof SharedUserSetting) {
3077                final SharedUserSetting sus = (SharedUserSetting) obj;
3078                return sus.pkgFlags;
3079            } else if (obj instanceof PackageSetting) {
3080                final PackageSetting ps = (PackageSetting) obj;
3081                return ps.pkgFlags;
3082            }
3083        }
3084        return 0;
3085    }
3086
3087    @Override
3088    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3089            int flags, int userId) {
3090        if (!sUserManager.exists(userId)) return null;
3091        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
3092        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3093        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3094    }
3095
3096    @Override
3097    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3098            IntentFilter filter, int match, ComponentName activity) {
3099        final int userId = UserHandle.getCallingUserId();
3100        if (DEBUG_PREFERRED) {
3101            Log.v(TAG, "setLastChosenActivity intent=" + intent
3102                + " resolvedType=" + resolvedType
3103                + " flags=" + flags
3104                + " filter=" + filter
3105                + " match=" + match
3106                + " activity=" + activity);
3107            filter.dump(new PrintStreamPrinter(System.out), "    ");
3108        }
3109        intent.setComponent(null);
3110        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3111        // Find any earlier preferred or last chosen entries and nuke them
3112        findPreferredActivity(intent, resolvedType,
3113                flags, query, 0, false, true, false, userId);
3114        // Add the new activity as the last chosen for this filter
3115        addPreferredActivityInternal(filter, match, null, activity, false, userId);
3116    }
3117
3118    @Override
3119    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3120        final int userId = UserHandle.getCallingUserId();
3121        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3122        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3123        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3124                false, false, false, userId);
3125    }
3126
3127    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3128            int flags, List<ResolveInfo> query, int userId) {
3129        if (query != null) {
3130            final int N = query.size();
3131            if (N == 1) {
3132                return query.get(0);
3133            } else if (N > 1) {
3134                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3135                // If there is more than one activity with the same priority,
3136                // then let the user decide between them.
3137                ResolveInfo r0 = query.get(0);
3138                ResolveInfo r1 = query.get(1);
3139                if (DEBUG_INTENT_MATCHING || debug) {
3140                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3141                            + r1.activityInfo.name + "=" + r1.priority);
3142                }
3143                // If the first activity has a higher priority, or a different
3144                // default, then it is always desireable to pick it.
3145                if (r0.priority != r1.priority
3146                        || r0.preferredOrder != r1.preferredOrder
3147                        || r0.isDefault != r1.isDefault) {
3148                    return query.get(0);
3149                }
3150                // If we have saved a preference for a preferred activity for
3151                // this Intent, use that.
3152                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3153                        flags, query, r0.priority, true, false, debug, userId);
3154                if (ri != null) {
3155                    return ri;
3156                }
3157                if (userId != 0) {
3158                    ri = new ResolveInfo(mResolveInfo);
3159                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3160                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3161                            ri.activityInfo.applicationInfo);
3162                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3163                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3164                    return ri;
3165                }
3166                return mResolveInfo;
3167            }
3168        }
3169        return null;
3170    }
3171
3172    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3173            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3174        final int N = query.size();
3175        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3176                .get(userId);
3177        // Get the list of persistent preferred activities that handle the intent
3178        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3179        List<PersistentPreferredActivity> pprefs = ppir != null
3180                ? ppir.queryIntent(intent, resolvedType,
3181                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3182                : null;
3183        if (pprefs != null && pprefs.size() > 0) {
3184            final int M = pprefs.size();
3185            for (int i=0; i<M; i++) {
3186                final PersistentPreferredActivity ppa = pprefs.get(i);
3187                if (DEBUG_PREFERRED || debug) {
3188                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3189                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3190                            + "\n  component=" + ppa.mComponent);
3191                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3192                }
3193                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3194                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3195                if (DEBUG_PREFERRED || debug) {
3196                    Slog.v(TAG, "Found persistent preferred activity:");
3197                    if (ai != null) {
3198                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3199                    } else {
3200                        Slog.v(TAG, "  null");
3201                    }
3202                }
3203                if (ai == null) {
3204                    // This previously registered persistent preferred activity
3205                    // component is no longer known. Ignore it and do NOT remove it.
3206                    continue;
3207                }
3208                for (int j=0; j<N; j++) {
3209                    final ResolveInfo ri = query.get(j);
3210                    if (!ri.activityInfo.applicationInfo.packageName
3211                            .equals(ai.applicationInfo.packageName)) {
3212                        continue;
3213                    }
3214                    if (!ri.activityInfo.name.equals(ai.name)) {
3215                        continue;
3216                    }
3217                    //  Found a persistent preference that can handle the intent.
3218                    if (DEBUG_PREFERRED || debug) {
3219                        Slog.v(TAG, "Returning persistent preferred activity: " +
3220                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3221                    }
3222                    return ri;
3223                }
3224            }
3225        }
3226        return null;
3227    }
3228
3229    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3230            List<ResolveInfo> query, int priority, boolean always,
3231            boolean removeMatches, boolean debug, int userId) {
3232        if (!sUserManager.exists(userId)) return null;
3233        // writer
3234        synchronized (mPackages) {
3235            if (intent.getSelector() != null) {
3236                intent = intent.getSelector();
3237            }
3238            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3239
3240            // Try to find a matching persistent preferred activity.
3241            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3242                    debug, userId);
3243
3244            // If a persistent preferred activity matched, use it.
3245            if (pri != null) {
3246                return pri;
3247            }
3248
3249            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3250            // Get the list of preferred activities that handle the intent
3251            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3252            List<PreferredActivity> prefs = pir != null
3253                    ? pir.queryIntent(intent, resolvedType,
3254                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3255                    : null;
3256            if (prefs != null && prefs.size() > 0) {
3257                // First figure out how good the original match set is.
3258                // We will only allow preferred activities that came
3259                // from the same match quality.
3260                int match = 0;
3261
3262                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3263
3264                final int N = query.size();
3265                for (int j=0; j<N; j++) {
3266                    final ResolveInfo ri = query.get(j);
3267                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3268                            + ": 0x" + Integer.toHexString(match));
3269                    if (ri.match > match) {
3270                        match = ri.match;
3271                    }
3272                }
3273
3274                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3275                        + Integer.toHexString(match));
3276
3277                match &= IntentFilter.MATCH_CATEGORY_MASK;
3278                final int M = prefs.size();
3279                for (int i=0; i<M; i++) {
3280                    final PreferredActivity pa = prefs.get(i);
3281                    if (DEBUG_PREFERRED || debug) {
3282                        Slog.v(TAG, "Checking PreferredActivity ds="
3283                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3284                                + "\n  component=" + pa.mPref.mComponent);
3285                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3286                    }
3287                    if (pa.mPref.mMatch != match) {
3288                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3289                                + Integer.toHexString(pa.mPref.mMatch));
3290                        continue;
3291                    }
3292                    // If it's not an "always" type preferred activity and that's what we're
3293                    // looking for, skip it.
3294                    if (always && !pa.mPref.mAlways) {
3295                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3296                        continue;
3297                    }
3298                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3299                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3300                    if (DEBUG_PREFERRED || debug) {
3301                        Slog.v(TAG, "Found preferred activity:");
3302                        if (ai != null) {
3303                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3304                        } else {
3305                            Slog.v(TAG, "  null");
3306                        }
3307                    }
3308                    if (ai == null) {
3309                        // This previously registered preferred activity
3310                        // component is no longer known.  Most likely an update
3311                        // to the app was installed and in the new version this
3312                        // component no longer exists.  Clean it up by removing
3313                        // it from the preferred activities list, and skip it.
3314                        Slog.w(TAG, "Removing dangling preferred activity: "
3315                                + pa.mPref.mComponent);
3316                        pir.removeFilter(pa);
3317                        continue;
3318                    }
3319                    for (int j=0; j<N; j++) {
3320                        final ResolveInfo ri = query.get(j);
3321                        if (!ri.activityInfo.applicationInfo.packageName
3322                                .equals(ai.applicationInfo.packageName)) {
3323                            continue;
3324                        }
3325                        if (!ri.activityInfo.name.equals(ai.name)) {
3326                            continue;
3327                        }
3328
3329                        if (removeMatches) {
3330                            pir.removeFilter(pa);
3331                            if (DEBUG_PREFERRED) {
3332                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3333                            }
3334                            break;
3335                        }
3336
3337                        // Okay we found a previously set preferred or last chosen app.
3338                        // If the result set is different from when this
3339                        // was created, we need to clear it and re-ask the
3340                        // user their preference, if we're looking for an "always" type entry.
3341                        if (always && !pa.mPref.sameSet(query, priority)) {
3342                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3343                                    + intent + " type " + resolvedType);
3344                            if (DEBUG_PREFERRED) {
3345                                Slog.v(TAG, "Removing preferred activity since set changed "
3346                                        + pa.mPref.mComponent);
3347                            }
3348                            pir.removeFilter(pa);
3349                            // Re-add the filter as a "last chosen" entry (!always)
3350                            PreferredActivity lastChosen = new PreferredActivity(
3351                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3352                            pir.addFilter(lastChosen);
3353                            mSettings.writePackageRestrictionsLPr(userId);
3354                            return null;
3355                        }
3356
3357                        // Yay! Either the set matched or we're looking for the last chosen
3358                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3359                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3360                        mSettings.writePackageRestrictionsLPr(userId);
3361                        return ri;
3362                    }
3363                }
3364            }
3365            mSettings.writePackageRestrictionsLPr(userId);
3366        }
3367        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3368        return null;
3369    }
3370
3371    /*
3372     * Returns if intent can be forwarded from the userId from to dest
3373     */
3374    @Override
3375    public boolean canForwardTo(Intent intent, String resolvedType, int userIdFrom, int userIdDest) {
3376        mContext.enforceCallingOrSelfPermission(
3377                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3378        List<ForwardingIntentFilter> matches =
3379                getMatchingForwardingIntentFilters(intent, resolvedType, userIdFrom);
3380        if (matches != null) {
3381            int size = matches.size();
3382            for (int i = 0; i < size; i++) {
3383                if (matches.get(i).getUserIdDest() == userIdDest) return true;
3384            }
3385        }
3386        return false;
3387    }
3388
3389    private List<ForwardingIntentFilter> getMatchingForwardingIntentFilters(Intent intent,
3390            String resolvedType, int userId) {
3391        ForwardingIntentResolver fir = mSettings.mForwardingIntentResolvers.get(userId);
3392        if (fir != null) {
3393            return fir.queryIntent(intent, resolvedType, false, userId);
3394        }
3395        return null;
3396    }
3397
3398    @Override
3399    public List<ResolveInfo> queryIntentActivities(Intent intent,
3400            String resolvedType, int flags, int userId) {
3401        if (!sUserManager.exists(userId)) return Collections.emptyList();
3402        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3403        ComponentName comp = intent.getComponent();
3404        if (comp == null) {
3405            if (intent.getSelector() != null) {
3406                intent = intent.getSelector();
3407                comp = intent.getComponent();
3408            }
3409        }
3410
3411        if (comp != null) {
3412            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3413            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3414            if (ai != null) {
3415                final ResolveInfo ri = new ResolveInfo();
3416                ri.activityInfo = ai;
3417                list.add(ri);
3418            }
3419            return list;
3420        }
3421
3422        // reader
3423        synchronized (mPackages) {
3424            final String pkgName = intent.getPackage();
3425            if (pkgName == null) {
3426                List<ResolveInfo> result =
3427                        mActivities.queryIntent(intent, resolvedType, flags, userId);
3428                // Checking if we can forward the intent to another user
3429                List<ForwardingIntentFilter> fifs =
3430                        getMatchingForwardingIntentFilters(intent, resolvedType, userId);
3431                if (fifs != null) {
3432                    ForwardingIntentFilter forwardingIntentFilterWithResult = null;
3433                    HashSet<Integer> alreadyTriedUserIds = new HashSet<Integer>();
3434                    for (ForwardingIntentFilter fif : fifs) {
3435                        int userIdDest = fif.getUserIdDest();
3436                        // Two {@link ForwardingIntentFilter}s can have the same userIdDest and
3437                        // match the same an intent. For performance reasons, it is better not to
3438                        // run queryIntent twice for the same userId
3439                        if (!alreadyTriedUserIds.contains(userIdDest)) {
3440                            List<ResolveInfo> resultUser = mActivities.queryIntent(intent,
3441                                    resolvedType, flags, userIdDest);
3442                            if (resultUser != null) {
3443                                forwardingIntentFilterWithResult = fif;
3444                                // As soon as there is a match in another user, we add the
3445                                // intentForwarderActivity to the list of ResolveInfo.
3446                                break;
3447                            }
3448                            alreadyTriedUserIds.add(userIdDest);
3449                        }
3450                    }
3451                    if (forwardingIntentFilterWithResult != null) {
3452                        ResolveInfo forwardingResolveInfo = createForwardingResolveInfo(
3453                                forwardingIntentFilterWithResult, userId);
3454                        result.add(forwardingResolveInfo);
3455                    }
3456                }
3457                return result;
3458            }
3459            final PackageParser.Package pkg = mPackages.get(pkgName);
3460            if (pkg != null) {
3461                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3462                        pkg.activities, userId);
3463            }
3464            return new ArrayList<ResolveInfo>();
3465        }
3466    }
3467
3468    private ResolveInfo createForwardingResolveInfo(ForwardingIntentFilter fif, int userIdFrom) {
3469        String className;
3470        int userIdDest = fif.getUserIdDest();
3471        if (userIdDest == UserHandle.USER_OWNER) {
3472            className = FORWARD_INTENT_TO_USER_OWNER;
3473        } else {
3474            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3475        }
3476        ComponentName forwardingActivityComponentName = new ComponentName(
3477                mAndroidApplication.packageName, className);
3478        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3479                userIdFrom);
3480        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3481        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3482        forwardingResolveInfo.priority = 0;
3483        forwardingResolveInfo.preferredOrder = 0;
3484        forwardingResolveInfo.match = 0;
3485        forwardingResolveInfo.isDefault = true;
3486        forwardingResolveInfo.filter = fif;
3487        return forwardingResolveInfo;
3488    }
3489
3490    @Override
3491    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3492            Intent[] specifics, String[] specificTypes, Intent intent,
3493            String resolvedType, int flags, int userId) {
3494        if (!sUserManager.exists(userId)) return Collections.emptyList();
3495        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3496                "query intent activity options");
3497        final String resultsAction = intent.getAction();
3498
3499        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3500                | PackageManager.GET_RESOLVED_FILTER, userId);
3501
3502        if (DEBUG_INTENT_MATCHING) {
3503            Log.v(TAG, "Query " + intent + ": " + results);
3504        }
3505
3506        int specificsPos = 0;
3507        int N;
3508
3509        // todo: note that the algorithm used here is O(N^2).  This
3510        // isn't a problem in our current environment, but if we start running
3511        // into situations where we have more than 5 or 10 matches then this
3512        // should probably be changed to something smarter...
3513
3514        // First we go through and resolve each of the specific items
3515        // that were supplied, taking care of removing any corresponding
3516        // duplicate items in the generic resolve list.
3517        if (specifics != null) {
3518            for (int i=0; i<specifics.length; i++) {
3519                final Intent sintent = specifics[i];
3520                if (sintent == null) {
3521                    continue;
3522                }
3523
3524                if (DEBUG_INTENT_MATCHING) {
3525                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3526                }
3527
3528                String action = sintent.getAction();
3529                if (resultsAction != null && resultsAction.equals(action)) {
3530                    // If this action was explicitly requested, then don't
3531                    // remove things that have it.
3532                    action = null;
3533                }
3534
3535                ResolveInfo ri = null;
3536                ActivityInfo ai = null;
3537
3538                ComponentName comp = sintent.getComponent();
3539                if (comp == null) {
3540                    ri = resolveIntent(
3541                        sintent,
3542                        specificTypes != null ? specificTypes[i] : null,
3543                            flags, userId);
3544                    if (ri == null) {
3545                        continue;
3546                    }
3547                    if (ri == mResolveInfo) {
3548                        // ACK!  Must do something better with this.
3549                    }
3550                    ai = ri.activityInfo;
3551                    comp = new ComponentName(ai.applicationInfo.packageName,
3552                            ai.name);
3553                } else {
3554                    ai = getActivityInfo(comp, flags, userId);
3555                    if (ai == null) {
3556                        continue;
3557                    }
3558                }
3559
3560                // Look for any generic query activities that are duplicates
3561                // of this specific one, and remove them from the results.
3562                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3563                N = results.size();
3564                int j;
3565                for (j=specificsPos; j<N; j++) {
3566                    ResolveInfo sri = results.get(j);
3567                    if ((sri.activityInfo.name.equals(comp.getClassName())
3568                            && sri.activityInfo.applicationInfo.packageName.equals(
3569                                    comp.getPackageName()))
3570                        || (action != null && sri.filter.matchAction(action))) {
3571                        results.remove(j);
3572                        if (DEBUG_INTENT_MATCHING) Log.v(
3573                            TAG, "Removing duplicate item from " + j
3574                            + " due to specific " + specificsPos);
3575                        if (ri == null) {
3576                            ri = sri;
3577                        }
3578                        j--;
3579                        N--;
3580                    }
3581                }
3582
3583                // Add this specific item to its proper place.
3584                if (ri == null) {
3585                    ri = new ResolveInfo();
3586                    ri.activityInfo = ai;
3587                }
3588                results.add(specificsPos, ri);
3589                ri.specificIndex = i;
3590                specificsPos++;
3591            }
3592        }
3593
3594        // Now we go through the remaining generic results and remove any
3595        // duplicate actions that are found here.
3596        N = results.size();
3597        for (int i=specificsPos; i<N-1; i++) {
3598            final ResolveInfo rii = results.get(i);
3599            if (rii.filter == null) {
3600                continue;
3601            }
3602
3603            // Iterate over all of the actions of this result's intent
3604            // filter...  typically this should be just one.
3605            final Iterator<String> it = rii.filter.actionsIterator();
3606            if (it == null) {
3607                continue;
3608            }
3609            while (it.hasNext()) {
3610                final String action = it.next();
3611                if (resultsAction != null && resultsAction.equals(action)) {
3612                    // If this action was explicitly requested, then don't
3613                    // remove things that have it.
3614                    continue;
3615                }
3616                for (int j=i+1; j<N; j++) {
3617                    final ResolveInfo rij = results.get(j);
3618                    if (rij.filter != null && rij.filter.hasAction(action)) {
3619                        results.remove(j);
3620                        if (DEBUG_INTENT_MATCHING) Log.v(
3621                            TAG, "Removing duplicate item from " + j
3622                            + " due to action " + action + " at " + i);
3623                        j--;
3624                        N--;
3625                    }
3626                }
3627            }
3628
3629            // If the caller didn't request filter information, drop it now
3630            // so we don't have to marshall/unmarshall it.
3631            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3632                rii.filter = null;
3633            }
3634        }
3635
3636        // Filter out the caller activity if so requested.
3637        if (caller != null) {
3638            N = results.size();
3639            for (int i=0; i<N; i++) {
3640                ActivityInfo ainfo = results.get(i).activityInfo;
3641                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3642                        && caller.getClassName().equals(ainfo.name)) {
3643                    results.remove(i);
3644                    break;
3645                }
3646            }
3647        }
3648
3649        // If the caller didn't request filter information,
3650        // drop them now so we don't have to
3651        // marshall/unmarshall it.
3652        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3653            N = results.size();
3654            for (int i=0; i<N; i++) {
3655                results.get(i).filter = null;
3656            }
3657        }
3658
3659        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3660        return results;
3661    }
3662
3663    @Override
3664    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3665            int userId) {
3666        if (!sUserManager.exists(userId)) return Collections.emptyList();
3667        ComponentName comp = intent.getComponent();
3668        if (comp == null) {
3669            if (intent.getSelector() != null) {
3670                intent = intent.getSelector();
3671                comp = intent.getComponent();
3672            }
3673        }
3674        if (comp != null) {
3675            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3676            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3677            if (ai != null) {
3678                ResolveInfo ri = new ResolveInfo();
3679                ri.activityInfo = ai;
3680                list.add(ri);
3681            }
3682            return list;
3683        }
3684
3685        // reader
3686        synchronized (mPackages) {
3687            String pkgName = intent.getPackage();
3688            if (pkgName == null) {
3689                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3690            }
3691            final PackageParser.Package pkg = mPackages.get(pkgName);
3692            if (pkg != null) {
3693                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3694                        userId);
3695            }
3696            return null;
3697        }
3698    }
3699
3700    @Override
3701    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3702        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3703        if (!sUserManager.exists(userId)) return null;
3704        if (query != null) {
3705            if (query.size() >= 1) {
3706                // If there is more than one service with the same priority,
3707                // just arbitrarily pick the first one.
3708                return query.get(0);
3709            }
3710        }
3711        return null;
3712    }
3713
3714    @Override
3715    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3716            int userId) {
3717        if (!sUserManager.exists(userId)) return Collections.emptyList();
3718        ComponentName comp = intent.getComponent();
3719        if (comp == null) {
3720            if (intent.getSelector() != null) {
3721                intent = intent.getSelector();
3722                comp = intent.getComponent();
3723            }
3724        }
3725        if (comp != null) {
3726            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3727            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3728            if (si != null) {
3729                final ResolveInfo ri = new ResolveInfo();
3730                ri.serviceInfo = si;
3731                list.add(ri);
3732            }
3733            return list;
3734        }
3735
3736        // reader
3737        synchronized (mPackages) {
3738            String pkgName = intent.getPackage();
3739            if (pkgName == null) {
3740                return mServices.queryIntent(intent, resolvedType, flags, userId);
3741            }
3742            final PackageParser.Package pkg = mPackages.get(pkgName);
3743            if (pkg != null) {
3744                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3745                        userId);
3746            }
3747            return null;
3748        }
3749    }
3750
3751    @Override
3752    public List<ResolveInfo> queryIntentContentProviders(
3753            Intent intent, String resolvedType, int flags, int userId) {
3754        if (!sUserManager.exists(userId)) return Collections.emptyList();
3755        ComponentName comp = intent.getComponent();
3756        if (comp == null) {
3757            if (intent.getSelector() != null) {
3758                intent = intent.getSelector();
3759                comp = intent.getComponent();
3760            }
3761        }
3762        if (comp != null) {
3763            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3764            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3765            if (pi != null) {
3766                final ResolveInfo ri = new ResolveInfo();
3767                ri.providerInfo = pi;
3768                list.add(ri);
3769            }
3770            return list;
3771        }
3772
3773        // reader
3774        synchronized (mPackages) {
3775            String pkgName = intent.getPackage();
3776            if (pkgName == null) {
3777                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3778            }
3779            final PackageParser.Package pkg = mPackages.get(pkgName);
3780            if (pkg != null) {
3781                return mProviders.queryIntentForPackage(
3782                        intent, resolvedType, flags, pkg.providers, userId);
3783            }
3784            return null;
3785        }
3786    }
3787
3788    @Override
3789    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3790        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3791
3792        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3793
3794        // writer
3795        synchronized (mPackages) {
3796            ArrayList<PackageInfo> list;
3797            if (listUninstalled) {
3798                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3799                for (PackageSetting ps : mSettings.mPackages.values()) {
3800                    PackageInfo pi;
3801                    if (ps.pkg != null) {
3802                        pi = generatePackageInfo(ps.pkg, flags, userId);
3803                    } else {
3804                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3805                    }
3806                    if (pi != null) {
3807                        list.add(pi);
3808                    }
3809                }
3810            } else {
3811                list = new ArrayList<PackageInfo>(mPackages.size());
3812                for (PackageParser.Package p : mPackages.values()) {
3813                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3814                    if (pi != null) {
3815                        list.add(pi);
3816                    }
3817                }
3818            }
3819
3820            return new ParceledListSlice<PackageInfo>(list);
3821        }
3822    }
3823
3824    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3825            String[] permissions, boolean[] tmp, int flags, int userId) {
3826        int numMatch = 0;
3827        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3828        for (int i=0; i<permissions.length; i++) {
3829            if (gp.grantedPermissions.contains(permissions[i])) {
3830                tmp[i] = true;
3831                numMatch++;
3832            } else {
3833                tmp[i] = false;
3834            }
3835        }
3836        if (numMatch == 0) {
3837            return;
3838        }
3839        PackageInfo pi;
3840        if (ps.pkg != null) {
3841            pi = generatePackageInfo(ps.pkg, flags, userId);
3842        } else {
3843            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3844        }
3845        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3846            if (numMatch == permissions.length) {
3847                pi.requestedPermissions = permissions;
3848            } else {
3849                pi.requestedPermissions = new String[numMatch];
3850                numMatch = 0;
3851                for (int i=0; i<permissions.length; i++) {
3852                    if (tmp[i]) {
3853                        pi.requestedPermissions[numMatch] = permissions[i];
3854                        numMatch++;
3855                    }
3856                }
3857            }
3858        }
3859        list.add(pi);
3860    }
3861
3862    @Override
3863    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3864            String[] permissions, int flags, int userId) {
3865        if (!sUserManager.exists(userId)) return null;
3866        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3867
3868        // writer
3869        synchronized (mPackages) {
3870            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3871            boolean[] tmpBools = new boolean[permissions.length];
3872            if (listUninstalled) {
3873                for (PackageSetting ps : mSettings.mPackages.values()) {
3874                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3875                }
3876            } else {
3877                for (PackageParser.Package pkg : mPackages.values()) {
3878                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3879                    if (ps != null) {
3880                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3881                                userId);
3882                    }
3883                }
3884            }
3885
3886            return new ParceledListSlice<PackageInfo>(list);
3887        }
3888    }
3889
3890    @Override
3891    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3892        if (!sUserManager.exists(userId)) return null;
3893        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3894
3895        // writer
3896        synchronized (mPackages) {
3897            ArrayList<ApplicationInfo> list;
3898            if (listUninstalled) {
3899                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3900                for (PackageSetting ps : mSettings.mPackages.values()) {
3901                    ApplicationInfo ai;
3902                    if (ps.pkg != null) {
3903                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3904                                ps.readUserState(userId), userId);
3905                    } else {
3906                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3907                    }
3908                    if (ai != null) {
3909                        list.add(ai);
3910                    }
3911                }
3912            } else {
3913                list = new ArrayList<ApplicationInfo>(mPackages.size());
3914                for (PackageParser.Package p : mPackages.values()) {
3915                    if (p.mExtras != null) {
3916                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3917                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3918                        if (ai != null) {
3919                            list.add(ai);
3920                        }
3921                    }
3922                }
3923            }
3924
3925            return new ParceledListSlice<ApplicationInfo>(list);
3926        }
3927    }
3928
3929    public List<ApplicationInfo> getPersistentApplications(int flags) {
3930        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3931
3932        // reader
3933        synchronized (mPackages) {
3934            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3935            final int userId = UserHandle.getCallingUserId();
3936            while (i.hasNext()) {
3937                final PackageParser.Package p = i.next();
3938                if (p.applicationInfo != null
3939                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3940                        && (!mSafeMode || isSystemApp(p))) {
3941                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3942                    if (ps != null) {
3943                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3944                                ps.readUserState(userId), userId);
3945                        if (ai != null) {
3946                            finalList.add(ai);
3947                        }
3948                    }
3949                }
3950            }
3951        }
3952
3953        return finalList;
3954    }
3955
3956    @Override
3957    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3958        if (!sUserManager.exists(userId)) return null;
3959        // reader
3960        synchronized (mPackages) {
3961            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3962            PackageSetting ps = provider != null
3963                    ? mSettings.mPackages.get(provider.owner.packageName)
3964                    : null;
3965            return ps != null
3966                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3967                    && (!mSafeMode || (provider.info.applicationInfo.flags
3968                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3969                    ? PackageParser.generateProviderInfo(provider, flags,
3970                            ps.readUserState(userId), userId)
3971                    : null;
3972        }
3973    }
3974
3975    /**
3976     * @deprecated
3977     */
3978    @Deprecated
3979    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3980        // reader
3981        synchronized (mPackages) {
3982            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3983                    .entrySet().iterator();
3984            final int userId = UserHandle.getCallingUserId();
3985            while (i.hasNext()) {
3986                Map.Entry<String, PackageParser.Provider> entry = i.next();
3987                PackageParser.Provider p = entry.getValue();
3988                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3989
3990                if (ps != null && p.syncable
3991                        && (!mSafeMode || (p.info.applicationInfo.flags
3992                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3993                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3994                            ps.readUserState(userId), userId);
3995                    if (info != null) {
3996                        outNames.add(entry.getKey());
3997                        outInfo.add(info);
3998                    }
3999                }
4000            }
4001        }
4002    }
4003
4004    @Override
4005    public List<ProviderInfo> queryContentProviders(String processName,
4006            int uid, int flags) {
4007        ArrayList<ProviderInfo> finalList = null;
4008        // reader
4009        synchronized (mPackages) {
4010            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4011            final int userId = processName != null ?
4012                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4013            while (i.hasNext()) {
4014                final PackageParser.Provider p = i.next();
4015                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4016                if (ps != null && p.info.authority != null
4017                        && (processName == null
4018                                || (p.info.processName.equals(processName)
4019                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4020                        && mSettings.isEnabledLPr(p.info, flags, userId)
4021                        && (!mSafeMode
4022                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4023                    if (finalList == null) {
4024                        finalList = new ArrayList<ProviderInfo>(3);
4025                    }
4026                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4027                            ps.readUserState(userId), userId);
4028                    if (info != null) {
4029                        finalList.add(info);
4030                    }
4031                }
4032            }
4033        }
4034
4035        if (finalList != null) {
4036            Collections.sort(finalList, mProviderInitOrderSorter);
4037        }
4038
4039        return finalList;
4040    }
4041
4042    @Override
4043    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4044            int flags) {
4045        // reader
4046        synchronized (mPackages) {
4047            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4048            return PackageParser.generateInstrumentationInfo(i, flags);
4049        }
4050    }
4051
4052    @Override
4053    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4054            int flags) {
4055        ArrayList<InstrumentationInfo> finalList =
4056            new ArrayList<InstrumentationInfo>();
4057
4058        // reader
4059        synchronized (mPackages) {
4060            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4061            while (i.hasNext()) {
4062                final PackageParser.Instrumentation p = i.next();
4063                if (targetPackage == null
4064                        || targetPackage.equals(p.info.targetPackage)) {
4065                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4066                            flags);
4067                    if (ii != null) {
4068                        finalList.add(ii);
4069                    }
4070                }
4071            }
4072        }
4073
4074        return finalList;
4075    }
4076
4077    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4078        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4079        if (overlays == null) {
4080            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4081            return;
4082        }
4083        for (PackageParser.Package opkg : overlays.values()) {
4084            // Not much to do if idmap fails: we already logged the error
4085            // and we certainly don't want to abort installation of pkg simply
4086            // because an overlay didn't fit properly. For these reasons,
4087            // ignore the return value of createIdmapForPackagePairLI.
4088            createIdmapForPackagePairLI(pkg, opkg);
4089        }
4090    }
4091
4092    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4093            PackageParser.Package opkg) {
4094        if (!opkg.mTrustedOverlay) {
4095            Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " +
4096                    opkg.mScanPath + ": overlay not trusted");
4097            return false;
4098        }
4099        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4100        if (overlaySet == null) {
4101            Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " +
4102                    opkg.mScanPath + " but target package has no known overlays");
4103            return false;
4104        }
4105        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4106        if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) {
4107            Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath);
4108            return false;
4109        }
4110        PackageParser.Package[] overlayArray =
4111            overlaySet.values().toArray(new PackageParser.Package[0]);
4112        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4113            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4114                return p1.mOverlayPriority - p2.mOverlayPriority;
4115            }
4116        };
4117        Arrays.sort(overlayArray, cmp);
4118
4119        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4120        int i = 0;
4121        for (PackageParser.Package p : overlayArray) {
4122            pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir;
4123        }
4124        return true;
4125    }
4126
4127    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4128        String[] files = dir.list();
4129        if (files == null) {
4130            Log.d(TAG, "No files in app dir " + dir);
4131            return;
4132        }
4133
4134        if (DEBUG_PACKAGE_SCANNING) {
4135            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4136                    + " flags=0x" + Integer.toHexString(flags));
4137        }
4138
4139        int i;
4140        for (i=0; i<files.length; i++) {
4141            File file = new File(dir, files[i]);
4142            if (!isPackageFilename(files[i])) {
4143                // Ignore entries which are not apk's
4144                continue;
4145            }
4146            PackageParser.Package pkg = scanPackageLI(file,
4147                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
4148            // Don't mess around with apps in system partition.
4149            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4150                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
4151                // Delete the apk
4152                Slog.w(TAG, "Cleaning up failed install of " + file);
4153                file.delete();
4154            }
4155        }
4156    }
4157
4158    private static File getSettingsProblemFile() {
4159        File dataDir = Environment.getDataDirectory();
4160        File systemDir = new File(dataDir, "system");
4161        File fname = new File(systemDir, "uiderrors.txt");
4162        return fname;
4163    }
4164
4165    static void reportSettingsProblem(int priority, String msg) {
4166        try {
4167            File fname = getSettingsProblemFile();
4168            FileOutputStream out = new FileOutputStream(fname, true);
4169            PrintWriter pw = new FastPrintWriter(out);
4170            SimpleDateFormat formatter = new SimpleDateFormat();
4171            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4172            pw.println(dateString + ": " + msg);
4173            pw.close();
4174            FileUtils.setPermissions(
4175                    fname.toString(),
4176                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4177                    -1, -1);
4178        } catch (java.io.IOException e) {
4179        }
4180        Slog.println(priority, TAG, msg);
4181    }
4182
4183    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
4184            PackageParser.Package pkg, File srcFile, int parseFlags) {
4185        if (ps != null
4186                && ps.codePath.equals(srcFile)
4187                && ps.timeStamp == srcFile.lastModified()
4188                && !isCompatSignatureUpdateNeeded(pkg)) {
4189            if (ps.signatures.mSignatures != null
4190                    && ps.signatures.mSignatures.length != 0) {
4191                // Optimization: reuse the existing cached certificates
4192                // if the package appears to be unchanged.
4193                pkg.mSignatures = ps.signatures.mSignatures;
4194                return true;
4195            }
4196
4197            Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
4198        } else {
4199            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4200        }
4201
4202        if (!pp.collectCertificates(pkg, parseFlags)) {
4203            mLastScanError = pp.getParseError();
4204            return false;
4205        }
4206        return true;
4207    }
4208
4209    /*
4210     *  Scan a package and return the newly parsed package.
4211     *  Returns null in case of errors and the error code is stored in mLastScanError
4212     */
4213    private PackageParser.Package scanPackageLI(File scanFile,
4214            int parseFlags, int scanMode, long currentTime, UserHandle user) {
4215        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4216        String scanPath = scanFile.getPath();
4217        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
4218        parseFlags |= mDefParseFlags;
4219        PackageParser pp = new PackageParser(scanPath);
4220        pp.setSeparateProcesses(mSeparateProcesses);
4221        pp.setOnlyCoreApps(mOnlyCore);
4222        final PackageParser.Package pkg = pp.parsePackage(scanFile,
4223                scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0);
4224
4225        if (pkg == null) {
4226            mLastScanError = pp.getParseError();
4227            return null;
4228        }
4229
4230        PackageSetting ps = null;
4231        PackageSetting updatedPkg;
4232        // reader
4233        synchronized (mPackages) {
4234            // Look to see if we already know about this package.
4235            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4236            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4237                // This package has been renamed to its original name.  Let's
4238                // use that.
4239                ps = mSettings.peekPackageLPr(oldName);
4240            }
4241            // If there was no original package, see one for the real package name.
4242            if (ps == null) {
4243                ps = mSettings.peekPackageLPr(pkg.packageName);
4244            }
4245            // Check to see if this package could be hiding/updating a system
4246            // package.  Must look for it either under the original or real
4247            // package name depending on our state.
4248            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4249            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4250        }
4251        boolean updatedPkgBetter = false;
4252        // First check if this is a system package that may involve an update
4253        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4254            if (ps != null && !ps.codePath.equals(scanFile)) {
4255                // The path has changed from what was last scanned...  check the
4256                // version of the new path against what we have stored to determine
4257                // what to do.
4258                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4259                if (pkg.mVersionCode < ps.versionCode) {
4260                    // The system package has been updated and the code path does not match
4261                    // Ignore entry. Skip it.
4262                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4263                            + " ignored: updated version " + ps.versionCode
4264                            + " better than this " + pkg.mVersionCode);
4265                    if (!updatedPkg.codePath.equals(scanFile)) {
4266                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4267                                + ps.name + " changing from " + updatedPkg.codePathString
4268                                + " to " + scanFile);
4269                        updatedPkg.codePath = scanFile;
4270                        updatedPkg.codePathString = scanFile.toString();
4271                        // This is the point at which we know that the system-disk APK
4272                        // for this package has moved during a reboot (e.g. due to an OTA),
4273                        // so we need to reevaluate it for privilege policy.
4274                        if (locationIsPrivileged(scanFile)) {
4275                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4276                        }
4277                    }
4278                    updatedPkg.pkg = pkg;
4279                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4280                    return null;
4281                } else {
4282                    // The current app on the system partion is better than
4283                    // what we have updated to on the data partition; switch
4284                    // back to the system partition version.
4285                    // At this point, its safely assumed that package installation for
4286                    // apps in system partition will go through. If not there won't be a working
4287                    // version of the app
4288                    // writer
4289                    synchronized (mPackages) {
4290                        // Just remove the loaded entries from package lists.
4291                        mPackages.remove(ps.name);
4292                    }
4293                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4294                            + "reverting from " + ps.codePathString
4295                            + ": new version " + pkg.mVersionCode
4296                            + " better than installed " + ps.versionCode);
4297
4298                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4299                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4300                            getAppInstructionSetFromSettings(ps));
4301                    synchronized (mInstallLock) {
4302                        args.cleanUpResourcesLI();
4303                    }
4304                    synchronized (mPackages) {
4305                        mSettings.enableSystemPackageLPw(ps.name);
4306                    }
4307                    updatedPkgBetter = true;
4308                }
4309            }
4310        }
4311
4312        if (updatedPkg != null) {
4313            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4314            // initially
4315            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4316
4317            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4318            // flag set initially
4319            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4320                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4321            }
4322        }
4323        // Verify certificates against what was last scanned
4324        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
4325            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
4326            return null;
4327        }
4328
4329        /*
4330         * A new system app appeared, but we already had a non-system one of the
4331         * same name installed earlier.
4332         */
4333        boolean shouldHideSystemApp = false;
4334        if (updatedPkg == null && ps != null
4335                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4336            /*
4337             * Check to make sure the signatures match first. If they don't,
4338             * wipe the installed application and its data.
4339             */
4340            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4341                    != PackageManager.SIGNATURE_MATCH) {
4342                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4343                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4344                ps = null;
4345            } else {
4346                /*
4347                 * If the newly-added system app is an older version than the
4348                 * already installed version, hide it. It will be scanned later
4349                 * and re-added like an update.
4350                 */
4351                if (pkg.mVersionCode < ps.versionCode) {
4352                    shouldHideSystemApp = true;
4353                } else {
4354                    /*
4355                     * The newly found system app is a newer version that the
4356                     * one previously installed. Simply remove the
4357                     * already-installed application and replace it with our own
4358                     * while keeping the application data.
4359                     */
4360                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4361                            + ps.codePathString + ": new version " + pkg.mVersionCode
4362                            + " better than installed " + ps.versionCode);
4363                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4364                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4365                            getAppInstructionSetFromSettings(ps));
4366                    synchronized (mInstallLock) {
4367                        args.cleanUpResourcesLI();
4368                    }
4369                }
4370            }
4371        }
4372
4373        // The apk is forward locked (not public) if its code and resources
4374        // are kept in different files. (except for app in either system or
4375        // vendor path).
4376        // TODO grab this value from PackageSettings
4377        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4378            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4379                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4380            }
4381        }
4382
4383        String codePath = null;
4384        String resPath = null;
4385        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4386            if (ps != null && ps.resourcePathString != null) {
4387                resPath = ps.resourcePathString;
4388            } else {
4389                // Should not happen at all. Just log an error.
4390                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4391            }
4392        } else {
4393            resPath = pkg.mScanPath;
4394        }
4395
4396        codePath = pkg.mScanPath;
4397        // Set application objects path explicitly.
4398        setApplicationInfoPaths(pkg, codePath, resPath);
4399        // Note that we invoke the following method only if we are about to unpack an application
4400        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4401                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4402
4403        /*
4404         * If the system app should be overridden by a previously installed
4405         * data, hide the system app now and let the /data/app scan pick it up
4406         * again.
4407         */
4408        if (shouldHideSystemApp) {
4409            synchronized (mPackages) {
4410                /*
4411                 * We have to grant systems permissions before we hide, because
4412                 * grantPermissions will assume the package update is trying to
4413                 * expand its permissions.
4414                 */
4415                grantPermissionsLPw(pkg, true);
4416                mSettings.disableSystemPackageLPw(pkg.packageName);
4417            }
4418        }
4419
4420        return scannedPkg;
4421    }
4422
4423    private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
4424            String destResPath) {
4425        pkg.mPath = pkg.mScanPath = destCodePath;
4426        pkg.applicationInfo.sourceDir = destCodePath;
4427        pkg.applicationInfo.publicSourceDir = destResPath;
4428    }
4429
4430    private static String fixProcessName(String defProcessName,
4431            String processName, int uid) {
4432        if (processName == null) {
4433            return defProcessName;
4434        }
4435        return processName;
4436    }
4437
4438    private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) {
4439        if (pkgSetting.signatures.mSignatures != null) {
4440            // Already existing package. Make sure signatures match
4441            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4442                    == PackageManager.SIGNATURE_MATCH;
4443            if (!match) {
4444                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4445                        == PackageManager.SIGNATURE_MATCH;
4446            }
4447            if (!match) {
4448                Slog.e(TAG, "Package " + pkg.packageName
4449                        + " signatures do not match the previously installed version; ignoring!");
4450                mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
4451                return false;
4452            }
4453        }
4454        // Check for shared user signatures
4455        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4456            // Already existing package. Make sure signatures match
4457            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4458                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4459            if (!match) {
4460                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4461                        == PackageManager.SIGNATURE_MATCH;
4462            }
4463            if (!match) {
4464                Slog.e(TAG, "Package " + pkg.packageName
4465                        + " has no signatures that match those in shared user "
4466                        + pkgSetting.sharedUser.name + "; ignoring!");
4467                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
4468                return false;
4469            }
4470        }
4471        return true;
4472    }
4473
4474    /**
4475     * Enforces that only the system UID or root's UID can call a method exposed
4476     * via Binder.
4477     *
4478     * @param message used as message if SecurityException is thrown
4479     * @throws SecurityException if the caller is not system or root
4480     */
4481    private static final void enforceSystemOrRoot(String message) {
4482        final int uid = Binder.getCallingUid();
4483        if (uid != Process.SYSTEM_UID && uid != 0) {
4484            throw new SecurityException(message);
4485        }
4486    }
4487
4488    @Override
4489    public void performBootDexOpt() {
4490        enforceSystemOrRoot("Only the system can request dexopt be performed");
4491
4492        final HashSet<PackageParser.Package> pkgs;
4493        synchronized (mPackages) {
4494            pkgs = mDeferredDexOpt;
4495            mDeferredDexOpt = null;
4496        }
4497
4498        if (pkgs != null) {
4499            // Filter out packages that aren't recently used.
4500            //
4501            // The exception is first boot of a non-eng device, which
4502            // should do a full dexopt.
4503            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4504            if (eng || !isFirstBoot()) {
4505                // TODO: add a property to control this?
4506                long dexOptLRUThresholdInMinutes;
4507                if (eng) {
4508                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4509                } else {
4510                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4511                }
4512                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4513
4514                int total = pkgs.size();
4515                int skipped = 0;
4516                long now = System.currentTimeMillis();
4517                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4518                    PackageParser.Package pkg = i.next();
4519                    long then = pkg.mLastPackageUsageTimeInMills;
4520                    if (then + dexOptLRUThresholdInMills < now) {
4521                        if (DEBUG_DEXOPT) {
4522                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4523                                  ((then == 0) ? "never" : new Date(then)));
4524                        }
4525                        i.remove();
4526                        skipped++;
4527                    }
4528                }
4529                if (DEBUG_DEXOPT) {
4530                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4531                }
4532            }
4533
4534            int i = 0;
4535            for (PackageParser.Package pkg : pkgs) {
4536                i++;
4537                if (DEBUG_DEXOPT) {
4538                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4539                          + ": " + pkg.packageName);
4540                }
4541                if (!isFirstBoot()) {
4542                    try {
4543                        ActivityManagerNative.getDefault().showBootMessage(
4544                                mContext.getResources().getString(
4545                                        R.string.android_upgrading_apk,
4546                                        i, pkgs.size()), true);
4547                    } catch (RemoteException e) {
4548                    }
4549                }
4550                PackageParser.Package p = pkg;
4551                synchronized (mInstallLock) {
4552                    if (p.mDexOptNeeded) {
4553                        performDexOptLI(p, false /* force dex */, false /* defer */,
4554                                true /* include dependencies */);
4555                    }
4556                }
4557            }
4558        }
4559    }
4560
4561    @Override
4562    public boolean performDexOpt(String packageName) {
4563        enforceSystemOrRoot("Only the system can request dexopt be performed");
4564        return performDexOpt(packageName, true);
4565    }
4566
4567    public boolean performDexOpt(String packageName, boolean updateUsage) {
4568
4569        PackageParser.Package p;
4570        synchronized (mPackages) {
4571            p = mPackages.get(packageName);
4572            if (p == null) {
4573                return false;
4574            }
4575            if (updateUsage) {
4576                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4577            }
4578            mPackageUsage.write(false);
4579            if (!p.mDexOptNeeded) {
4580                return false;
4581            }
4582        }
4583
4584        synchronized (mInstallLock) {
4585            return performDexOptLI(p, false /* force dex */, false /* defer */,
4586                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4587        }
4588    }
4589
4590    public HashSet<String> getPackagesThatNeedDexOpt() {
4591        HashSet<String> pkgs = null;
4592        synchronized (mPackages) {
4593            for (PackageParser.Package p : mPackages.values()) {
4594                if (DEBUG_DEXOPT) {
4595                    Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded);
4596                }
4597                if (!p.mDexOptNeeded) {
4598                    continue;
4599                }
4600                if (pkgs == null) {
4601                    pkgs = new HashSet<String>();
4602                }
4603                pkgs.add(p.packageName);
4604            }
4605        }
4606        return pkgs;
4607    }
4608
4609    public void shutdown() {
4610        mPackageUsage.write(true);
4611    }
4612
4613    private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet,
4614             boolean forceDex, boolean defer, HashSet<String> done) {
4615        for (int i=0; i<libs.size(); i++) {
4616            PackageParser.Package libPkg;
4617            String libName;
4618            synchronized (mPackages) {
4619                libName = libs.get(i);
4620                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4621                if (lib != null && lib.apk != null) {
4622                    libPkg = mPackages.get(lib.apk);
4623                } else {
4624                    libPkg = null;
4625                }
4626            }
4627            if (libPkg != null && !done.contains(libName)) {
4628                performDexOptLI(libPkg, instructionSet, forceDex, defer, done);
4629            }
4630        }
4631    }
4632
4633    static final int DEX_OPT_SKIPPED = 0;
4634    static final int DEX_OPT_PERFORMED = 1;
4635    static final int DEX_OPT_DEFERRED = 2;
4636    static final int DEX_OPT_FAILED = -1;
4637
4638    private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride,
4639            boolean forceDex, boolean defer, HashSet<String> done) {
4640        final String instructionSet = instructionSetOverride != null ?
4641                instructionSetOverride : getAppInstructionSet(pkg.applicationInfo);
4642
4643        if (done != null) {
4644            done.add(pkg.packageName);
4645            if (pkg.usesLibraries != null) {
4646                performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done);
4647            }
4648            if (pkg.usesOptionalLibraries != null) {
4649                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done);
4650            }
4651        }
4652
4653        boolean performed = false;
4654        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4655            String path = pkg.mScanPath;
4656            try {
4657                boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path,
4658                                                                                pkg.packageName,
4659                                                                                instructionSet,
4660                                                                                defer);
4661                // There are three basic cases here:
4662                // 1.) we need to dexopt, either because we are forced or it is needed
4663                // 2.) we are defering a needed dexopt
4664                // 3.) we are skipping an unneeded dexopt
4665                if (forceDex || (!defer && isDexOptNeededInternal)) {
4666                    Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
4667                    final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4668                    int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4669                                                pkg.packageName, instructionSet);
4670                    // Note that we ran dexopt, since rerunning will
4671                    // probably just result in an error again.
4672                    pkg.mDexOptNeeded = false;
4673                    if (ret < 0) {
4674                        return DEX_OPT_FAILED;
4675                    }
4676                    return DEX_OPT_PERFORMED;
4677                }
4678                if (defer && isDexOptNeededInternal) {
4679                    if (mDeferredDexOpt == null) {
4680                        mDeferredDexOpt = new HashSet<PackageParser.Package>();
4681                    }
4682                    mDeferredDexOpt.add(pkg);
4683                    return DEX_OPT_DEFERRED;
4684                }
4685                pkg.mDexOptNeeded = false;
4686                return DEX_OPT_SKIPPED;
4687            } catch (FileNotFoundException e) {
4688                Slog.w(TAG, "Apk not found for dexopt: " + path);
4689                return DEX_OPT_FAILED;
4690            } catch (IOException e) {
4691                Slog.w(TAG, "IOException reading apk: " + path, e);
4692                return DEX_OPT_FAILED;
4693            } catch (StaleDexCacheError e) {
4694                Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4695                return DEX_OPT_FAILED;
4696            } catch (Exception e) {
4697                Slog.w(TAG, "Exception when doing dexopt : ", e);
4698                return DEX_OPT_FAILED;
4699            }
4700        }
4701        return DEX_OPT_SKIPPED;
4702    }
4703
4704    private String getAppInstructionSet(ApplicationInfo info) {
4705        String instructionSet = getPreferredInstructionSet();
4706
4707        if (info.requiredCpuAbi != null) {
4708            instructionSet = VMRuntime.getInstructionSet(info.requiredCpuAbi);
4709        }
4710
4711        return instructionSet;
4712    }
4713
4714    private String getAppInstructionSetFromSettings(PackageSetting ps) {
4715        String instructionSet = getPreferredInstructionSet();
4716
4717        if (ps.requiredCpuAbiString != null) {
4718            instructionSet = VMRuntime.getInstructionSet(ps.requiredCpuAbiString);
4719        }
4720
4721        return instructionSet;
4722    }
4723
4724    private static String getPreferredInstructionSet() {
4725        if (sPreferredInstructionSet == null) {
4726            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4727        }
4728
4729        return sPreferredInstructionSet;
4730    }
4731
4732    private static List<String> getAllInstructionSets() {
4733        final String[] allAbis = Build.SUPPORTED_ABIS;
4734        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4735
4736        for (String abi : allAbis) {
4737            final String instructionSet = VMRuntime.getInstructionSet(abi);
4738            if (!allInstructionSets.contains(instructionSet)) {
4739                allInstructionSets.add(instructionSet);
4740            }
4741        }
4742
4743        return allInstructionSets;
4744    }
4745
4746    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4747            boolean inclDependencies) {
4748        HashSet<String> done;
4749        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4750            done = new HashSet<String>();
4751            done.add(pkg.packageName);
4752        } else {
4753            done = null;
4754        }
4755        return performDexOptLI(pkg, null /* instruction set override */,  forceDex, defer, done);
4756    }
4757
4758    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4759        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4760            Slog.w(TAG, "Unable to update from " + oldPkg.name
4761                    + " to " + newPkg.packageName
4762                    + ": old package not in system partition");
4763            return false;
4764        } else if (mPackages.get(oldPkg.name) != null) {
4765            Slog.w(TAG, "Unable to update from " + oldPkg.name
4766                    + " to " + newPkg.packageName
4767                    + ": old package still exists");
4768            return false;
4769        }
4770        return true;
4771    }
4772
4773    File getDataPathForUser(int userId) {
4774        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4775    }
4776
4777    private File getDataPathForPackage(String packageName, int userId) {
4778        /*
4779         * Until we fully support multiple users, return the directory we
4780         * previously would have. The PackageManagerTests will need to be
4781         * revised when this is changed back..
4782         */
4783        if (userId == 0) {
4784            return new File(mAppDataDir, packageName);
4785        } else {
4786            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4787                + File.separator + packageName);
4788        }
4789    }
4790
4791    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4792        int[] users = sUserManager.getUserIds();
4793        int res = mInstaller.install(packageName, uid, uid, seinfo);
4794        if (res < 0) {
4795            return res;
4796        }
4797        for (int user : users) {
4798            if (user != 0) {
4799                res = mInstaller.createUserData(packageName,
4800                        UserHandle.getUid(user, uid), user, seinfo);
4801                if (res < 0) {
4802                    return res;
4803                }
4804            }
4805        }
4806        return res;
4807    }
4808
4809    private int removeDataDirsLI(String packageName) {
4810        int[] users = sUserManager.getUserIds();
4811        int res = 0;
4812        for (int user : users) {
4813            int resInner = mInstaller.remove(packageName, user);
4814            if (resInner < 0) {
4815                res = resInner;
4816            }
4817        }
4818
4819        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4820        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4821        if (!nativeLibraryFile.delete()) {
4822            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4823        }
4824
4825        return res;
4826    }
4827
4828    private int addSharedLibraryLPw(final SharedLibraryEntry file, int num,
4829            PackageParser.Package changingLib) {
4830        if (file.path != null) {
4831            mTmpSharedLibraries[num] = file.path;
4832            return num+1;
4833        }
4834        PackageParser.Package p = mPackages.get(file.apk);
4835        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4836            // If we are doing this while in the middle of updating a library apk,
4837            // then we need to make sure to use that new apk for determining the
4838            // dependencies here.  (We haven't yet finished committing the new apk
4839            // to the package manager state.)
4840            if (p == null || p.packageName.equals(changingLib.packageName)) {
4841                p = changingLib;
4842            }
4843        }
4844        if (p != null) {
4845            String path = p.mPath;
4846            for (int i=0; i<num; i++) {
4847                if (mTmpSharedLibraries[i].equals(path)) {
4848                    return num;
4849                }
4850            }
4851            mTmpSharedLibraries[num] = p.mPath;
4852            return num+1;
4853        }
4854        return num;
4855    }
4856
4857    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4858            PackageParser.Package changingLib) {
4859        // We might be upgrading from a version of the platform that did not
4860        // provide per-package native library directories for system apps.
4861        // Fix that up here.
4862        if (isSystemApp(pkg)) {
4863            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4864            setInternalAppNativeLibraryPath(pkg, ps);
4865        }
4866
4867        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4868            if (mTmpSharedLibraries == null ||
4869                    mTmpSharedLibraries.length < mSharedLibraries.size()) {
4870                mTmpSharedLibraries = new String[mSharedLibraries.size()];
4871            }
4872            int num = 0;
4873            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4874            for (int i=0; i<N; i++) {
4875                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4876                if (file == null) {
4877                    Slog.e(TAG, "Package " + pkg.packageName
4878                            + " requires unavailable shared library "
4879                            + pkg.usesLibraries.get(i) + "; failing!");
4880                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4881                    return false;
4882                }
4883                num = addSharedLibraryLPw(file, num, changingLib);
4884            }
4885            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4886            for (int i=0; i<N; i++) {
4887                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4888                if (file == null) {
4889                    Slog.w(TAG, "Package " + pkg.packageName
4890                            + " desires unavailable shared library "
4891                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4892                } else {
4893                    num = addSharedLibraryLPw(file, num, changingLib);
4894                }
4895            }
4896            if (num > 0) {
4897                pkg.usesLibraryFiles = new String[num];
4898                System.arraycopy(mTmpSharedLibraries, 0,
4899                        pkg.usesLibraryFiles, 0, num);
4900            } else {
4901                pkg.usesLibraryFiles = null;
4902            }
4903        }
4904        return true;
4905    }
4906
4907    private static boolean hasString(List<String> list, List<String> which) {
4908        if (list == null) {
4909            return false;
4910        }
4911        for (int i=list.size()-1; i>=0; i--) {
4912            for (int j=which.size()-1; j>=0; j--) {
4913                if (which.get(j).equals(list.get(i))) {
4914                    return true;
4915                }
4916            }
4917        }
4918        return false;
4919    }
4920
4921    private void updateAllSharedLibrariesLPw() {
4922        for (PackageParser.Package pkg : mPackages.values()) {
4923            updateSharedLibrariesLPw(pkg, null);
4924        }
4925    }
4926
4927    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4928            PackageParser.Package changingPkg) {
4929        ArrayList<PackageParser.Package> res = null;
4930        for (PackageParser.Package pkg : mPackages.values()) {
4931            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4932                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4933                if (res == null) {
4934                    res = new ArrayList<PackageParser.Package>();
4935                }
4936                res.add(pkg);
4937                updateSharedLibrariesLPw(pkg, changingPkg);
4938            }
4939        }
4940        return res;
4941    }
4942
4943    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4944            int parseFlags, int scanMode, long currentTime, UserHandle user) {
4945        File scanFile = new File(pkg.mScanPath);
4946        if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
4947                pkg.applicationInfo.publicSourceDir == null) {
4948            // Bail out. The resource and code paths haven't been set.
4949            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4950            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4951            return null;
4952        }
4953
4954        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4955            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4956        }
4957
4958        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4959            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4960        }
4961
4962        if (mCustomResolverComponentName != null &&
4963                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4964            setUpCustomResolverActivity(pkg);
4965        }
4966
4967        if (pkg.packageName.equals("android")) {
4968            synchronized (mPackages) {
4969                if (mAndroidApplication != null) {
4970                    Slog.w(TAG, "*************************************************");
4971                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4972                    Slog.w(TAG, " file=" + scanFile);
4973                    Slog.w(TAG, "*************************************************");
4974                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4975                    return null;
4976                }
4977
4978                // Set up information for our fall-back user intent resolution activity.
4979                mPlatformPackage = pkg;
4980                pkg.mVersionCode = mSdkVersion;
4981                mAndroidApplication = pkg.applicationInfo;
4982
4983                if (!mResolverReplaced) {
4984                    mResolveActivity.applicationInfo = mAndroidApplication;
4985                    mResolveActivity.name = ResolverActivity.class.getName();
4986                    mResolveActivity.packageName = mAndroidApplication.packageName;
4987                    mResolveActivity.processName = "system:ui";
4988                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4989                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4990                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
4991                    mResolveActivity.exported = true;
4992                    mResolveActivity.enabled = true;
4993                    mResolveInfo.activityInfo = mResolveActivity;
4994                    mResolveInfo.priority = 0;
4995                    mResolveInfo.preferredOrder = 0;
4996                    mResolveInfo.match = 0;
4997                    mResolveComponentName = new ComponentName(
4998                            mAndroidApplication.packageName, mResolveActivity.name);
4999                }
5000            }
5001        }
5002
5003        if (DEBUG_PACKAGE_SCANNING) {
5004            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5005                Log.d(TAG, "Scanning package " + pkg.packageName);
5006        }
5007
5008        if (mPackages.containsKey(pkg.packageName)
5009                || mSharedLibraries.containsKey(pkg.packageName)) {
5010            Slog.w(TAG, "Application package " + pkg.packageName
5011                    + " already installed.  Skipping duplicate.");
5012            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
5013            return null;
5014        }
5015
5016        // Initialize package source and resource directories
5017        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
5018        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
5019
5020        SharedUserSetting suid = null;
5021        PackageSetting pkgSetting = null;
5022
5023        if (!isSystemApp(pkg)) {
5024            // Only system apps can use these features.
5025            pkg.mOriginalPackages = null;
5026            pkg.mRealPackage = null;
5027            pkg.mAdoptPermissions = null;
5028        }
5029
5030        // writer
5031        synchronized (mPackages) {
5032            if (pkg.mSharedUserId != null) {
5033                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5034                if (suid == null) {
5035                    Slog.w(TAG, "Creating application package " + pkg.packageName
5036                            + " for shared user failed");
5037                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5038                    return null;
5039                }
5040                if (DEBUG_PACKAGE_SCANNING) {
5041                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5042                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5043                                + "): packages=" + suid.packages);
5044                }
5045            }
5046
5047            // Check if we are renaming from an original package name.
5048            PackageSetting origPackage = null;
5049            String realName = null;
5050            if (pkg.mOriginalPackages != null) {
5051                // This package may need to be renamed to a previously
5052                // installed name.  Let's check on that...
5053                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5054                if (pkg.mOriginalPackages.contains(renamed)) {
5055                    // This package had originally been installed as the
5056                    // original name, and we have already taken care of
5057                    // transitioning to the new one.  Just update the new
5058                    // one to continue using the old name.
5059                    realName = pkg.mRealPackage;
5060                    if (!pkg.packageName.equals(renamed)) {
5061                        // Callers into this function may have already taken
5062                        // care of renaming the package; only do it here if
5063                        // it is not already done.
5064                        pkg.setPackageName(renamed);
5065                    }
5066
5067                } else {
5068                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5069                        if ((origPackage = mSettings.peekPackageLPr(
5070                                pkg.mOriginalPackages.get(i))) != null) {
5071                            // We do have the package already installed under its
5072                            // original name...  should we use it?
5073                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5074                                // New package is not compatible with original.
5075                                origPackage = null;
5076                                continue;
5077                            } else if (origPackage.sharedUser != null) {
5078                                // Make sure uid is compatible between packages.
5079                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5080                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5081                                            + " to " + pkg.packageName + ": old uid "
5082                                            + origPackage.sharedUser.name
5083                                            + " differs from " + pkg.mSharedUserId);
5084                                    origPackage = null;
5085                                    continue;
5086                                }
5087                            } else {
5088                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5089                                        + pkg.packageName + " to old name " + origPackage.name);
5090                            }
5091                            break;
5092                        }
5093                    }
5094                }
5095            }
5096
5097            if (mTransferedPackages.contains(pkg.packageName)) {
5098                Slog.w(TAG, "Package " + pkg.packageName
5099                        + " was transferred to another, but its .apk remains");
5100            }
5101
5102            // Just create the setting, don't add it yet. For already existing packages
5103            // the PkgSetting exists already and doesn't have to be created.
5104            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5105                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
5106                    pkg.applicationInfo.requiredCpuAbi,
5107                    pkg.applicationInfo.flags, user, false);
5108            if (pkgSetting == null) {
5109                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
5110                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5111                return null;
5112            }
5113
5114            if (pkgSetting.origPackage != null) {
5115                // If we are first transitioning from an original package,
5116                // fix up the new package's name now.  We need to do this after
5117                // looking up the package under its new name, so getPackageLP
5118                // can take care of fiddling things correctly.
5119                pkg.setPackageName(origPackage.name);
5120
5121                // File a report about this.
5122                String msg = "New package " + pkgSetting.realName
5123                        + " renamed to replace old package " + pkgSetting.name;
5124                reportSettingsProblem(Log.WARN, msg);
5125
5126                // Make a note of it.
5127                mTransferedPackages.add(origPackage.name);
5128
5129                // No longer need to retain this.
5130                pkgSetting.origPackage = null;
5131            }
5132
5133            if (realName != null) {
5134                // Make a note of it.
5135                mTransferedPackages.add(pkg.packageName);
5136            }
5137
5138            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5139                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5140            }
5141
5142            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5143                // Check all shared libraries and map to their actual file path.
5144                // We only do this here for apps not on a system dir, because those
5145                // are the only ones that can fail an install due to this.  We
5146                // will take care of the system apps by updating all of their
5147                // library paths after the scan is done.
5148                if (!updateSharedLibrariesLPw(pkg, null)) {
5149                    return null;
5150                }
5151            }
5152
5153            if (mFoundPolicyFile) {
5154                SELinuxMMAC.assignSeinfoValue(pkg);
5155            }
5156
5157            pkg.applicationInfo.uid = pkgSetting.appId;
5158            pkg.mExtras = pkgSetting;
5159
5160            if (!verifySignaturesLP(pkgSetting, pkg)) {
5161                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5162                    return null;
5163                }
5164                // The signature has changed, but this package is in the system
5165                // image...  let's recover!
5166                pkgSetting.signatures.mSignatures = pkg.mSignatures;
5167                // However...  if this package is part of a shared user, but it
5168                // doesn't match the signature of the shared user, let's fail.
5169                // What this means is that you can't change the signatures
5170                // associated with an overall shared user, which doesn't seem all
5171                // that unreasonable.
5172                if (pkgSetting.sharedUser != null) {
5173                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5174                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5175                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
5176                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5177                        return null;
5178                    }
5179                }
5180                // File a report about this.
5181                String msg = "System package " + pkg.packageName
5182                        + " signature changed; retaining data.";
5183                reportSettingsProblem(Log.WARN, msg);
5184            }
5185
5186            // Verify that this new package doesn't have any content providers
5187            // that conflict with existing packages.  Only do this if the
5188            // package isn't already installed, since we don't want to break
5189            // things that are installed.
5190            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5191                final int N = pkg.providers.size();
5192                int i;
5193                for (i=0; i<N; i++) {
5194                    PackageParser.Provider p = pkg.providers.get(i);
5195                    if (p.info.authority != null) {
5196                        String names[] = p.info.authority.split(";");
5197                        for (int j = 0; j < names.length; j++) {
5198                            if (mProvidersByAuthority.containsKey(names[j])) {
5199                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5200                                Slog.w(TAG, "Can't install because provider name " + names[j] +
5201                                        " (in package " + pkg.applicationInfo.packageName +
5202                                        ") is already used by "
5203                                        + ((other != null && other.getComponentName() != null)
5204                                                ? other.getComponentName().getPackageName() : "?"));
5205                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
5206                                return null;
5207                            }
5208                        }
5209                    }
5210                }
5211            }
5212
5213            if (pkg.mAdoptPermissions != null) {
5214                // This package wants to adopt ownership of permissions from
5215                // another package.
5216                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5217                    final String origName = pkg.mAdoptPermissions.get(i);
5218                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5219                    if (orig != null) {
5220                        if (verifyPackageUpdateLPr(orig, pkg)) {
5221                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5222                                    + pkg.packageName);
5223                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5224                        }
5225                    }
5226                }
5227            }
5228        }
5229
5230        final String pkgName = pkg.packageName;
5231
5232        final long scanFileTime = scanFile.lastModified();
5233        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5234        pkg.applicationInfo.processName = fixProcessName(
5235                pkg.applicationInfo.packageName,
5236                pkg.applicationInfo.processName,
5237                pkg.applicationInfo.uid);
5238
5239        File dataPath;
5240        if (mPlatformPackage == pkg) {
5241            // The system package is special.
5242            dataPath = new File (Environment.getDataDirectory(), "system");
5243            pkg.applicationInfo.dataDir = dataPath.getPath();
5244        } else {
5245            // This is a normal package, need to make its data directory.
5246            dataPath = getDataPathForPackage(pkg.packageName, 0);
5247
5248            boolean uidError = false;
5249
5250            if (dataPath.exists()) {
5251                int currentUid = 0;
5252                try {
5253                    StructStat stat = Os.stat(dataPath.getPath());
5254                    currentUid = stat.st_uid;
5255                } catch (ErrnoException e) {
5256                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5257                }
5258
5259                // If we have mismatched owners for the data path, we have a problem.
5260                if (currentUid != pkg.applicationInfo.uid) {
5261                    boolean recovered = false;
5262                    if (currentUid == 0) {
5263                        // The directory somehow became owned by root.  Wow.
5264                        // This is probably because the system was stopped while
5265                        // installd was in the middle of messing with its libs
5266                        // directory.  Ask installd to fix that.
5267                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5268                                pkg.applicationInfo.uid);
5269                        if (ret >= 0) {
5270                            recovered = true;
5271                            String msg = "Package " + pkg.packageName
5272                                    + " unexpectedly changed to uid 0; recovered to " +
5273                                    + pkg.applicationInfo.uid;
5274                            reportSettingsProblem(Log.WARN, msg);
5275                        }
5276                    }
5277                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5278                            || (scanMode&SCAN_BOOTING) != 0)) {
5279                        // If this is a system app, we can at least delete its
5280                        // current data so the application will still work.
5281                        int ret = removeDataDirsLI(pkgName);
5282                        if (ret >= 0) {
5283                            // TODO: Kill the processes first
5284                            // Old data gone!
5285                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5286                                    ? "System package " : "Third party package ";
5287                            String msg = prefix + pkg.packageName
5288                                    + " has changed from uid: "
5289                                    + currentUid + " to "
5290                                    + pkg.applicationInfo.uid + "; old data erased";
5291                            reportSettingsProblem(Log.WARN, msg);
5292                            recovered = true;
5293
5294                            // And now re-install the app.
5295                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5296                                                   pkg.applicationInfo.seinfo);
5297                            if (ret == -1) {
5298                                // Ack should not happen!
5299                                msg = prefix + pkg.packageName
5300                                        + " could not have data directory re-created after delete.";
5301                                reportSettingsProblem(Log.WARN, msg);
5302                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5303                                return null;
5304                            }
5305                        }
5306                        if (!recovered) {
5307                            mHasSystemUidErrors = true;
5308                        }
5309                    } else if (!recovered) {
5310                        // If we allow this install to proceed, we will be broken.
5311                        // Abort, abort!
5312                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
5313                        return null;
5314                    }
5315                    if (!recovered) {
5316                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5317                            + pkg.applicationInfo.uid + "/fs_"
5318                            + currentUid;
5319                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5320                        String msg = "Package " + pkg.packageName
5321                                + " has mismatched uid: "
5322                                + currentUid + " on disk, "
5323                                + pkg.applicationInfo.uid + " in settings";
5324                        // writer
5325                        synchronized (mPackages) {
5326                            mSettings.mReadMessages.append(msg);
5327                            mSettings.mReadMessages.append('\n');
5328                            uidError = true;
5329                            if (!pkgSetting.uidError) {
5330                                reportSettingsProblem(Log.ERROR, msg);
5331                            }
5332                        }
5333                    }
5334                }
5335                pkg.applicationInfo.dataDir = dataPath.getPath();
5336                if (mShouldRestoreconData) {
5337                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5338                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5339                                pkg.applicationInfo.uid);
5340                }
5341            } else {
5342                if (DEBUG_PACKAGE_SCANNING) {
5343                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5344                        Log.v(TAG, "Want this data dir: " + dataPath);
5345                }
5346                //invoke installer to do the actual installation
5347                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5348                                           pkg.applicationInfo.seinfo);
5349                if (ret < 0) {
5350                    // Error from installer
5351                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5352                    return null;
5353                }
5354
5355                if (dataPath.exists()) {
5356                    pkg.applicationInfo.dataDir = dataPath.getPath();
5357                } else {
5358                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5359                    pkg.applicationInfo.dataDir = null;
5360                }
5361            }
5362
5363            /*
5364             * Set the data dir to the default "/data/data/<package name>/lib"
5365             * if we got here without anyone telling us different (e.g., apps
5366             * stored on SD card have their native libraries stored in the ASEC
5367             * container with the APK).
5368             *
5369             * This happens during an upgrade from a package settings file that
5370             * doesn't have a native library path attribute at all.
5371             */
5372            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
5373                if (pkgSetting.nativeLibraryPathString == null) {
5374                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
5375                } else {
5376                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
5377                }
5378            }
5379            pkgSetting.uidError = uidError;
5380        }
5381
5382        String path = scanFile.getPath();
5383        /* Note: We don't want to unpack the native binaries for
5384         *        system applications, unless they have been updated
5385         *        (the binaries are already under /system/lib).
5386         *        Also, don't unpack libs for apps on the external card
5387         *        since they should have their libraries in the ASEC
5388         *        container already.
5389         *
5390         *        In other words, we're going to unpack the binaries
5391         *        only for non-system apps and system app upgrades.
5392         */
5393        if (pkg.applicationInfo.nativeLibraryDir != null) {
5394            try {
5395                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5396                final String dataPathString = dataPath.getCanonicalPath();
5397
5398                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5399                    /*
5400                     * Upgrading from a previous version of the OS sometimes
5401                     * leaves native libraries in the /data/data/<app>/lib
5402                     * directory for system apps even when they shouldn't be.
5403                     * Recent changes in the JNI library search path
5404                     * necessitates we remove those to match previous behavior.
5405                     */
5406                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
5407                        Log.i(TAG, "removed obsolete native libraries for system package "
5408                                + path);
5409                    }
5410
5411                    setInternalAppAbi(pkg, pkgSetting);
5412                } else {
5413                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
5414                        /*
5415                         * Update native library dir if it starts with
5416                         * /data/data
5417                         */
5418                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
5419                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
5420                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5421                        }
5422
5423                        try {
5424                            int copyRet = copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir);
5425                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5426                                Slog.e(TAG, "Unable to copy native libraries");
5427                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5428                                return null;
5429                            }
5430
5431                            // We've successfully copied native libraries across, so we make a
5432                            // note of what ABI we're using
5433                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5434                                pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[copyRet];
5435                            } else {
5436                                pkg.applicationInfo.requiredCpuAbi = null;
5437                            }
5438                        } catch (IOException e) {
5439                            Slog.e(TAG, "Unable to copy native libraries", e);
5440                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5441                            return null;
5442                        }
5443                    } else {
5444                        // We don't have to copy the shared libraries if we're in the ASEC container
5445                        // but we still need to scan the file to figure out what ABI the app needs.
5446                        //
5447                        // TODO: This duplicates work done in the default container service. It's possible
5448                        // to clean this up but we'll need to change the interface between this service
5449                        // and IMediaContainerService (but doing so will spread this logic out, rather
5450                        // than centralizing it).
5451                        final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5452                        final int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS);
5453                        if (abi >= 0) {
5454                            pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[abi];
5455                        } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) {
5456                            // Note that (non upgraded) system apps will not have any native
5457                            // libraries bundled in their APK, but we're guaranteed not to be
5458                            // such an app at this point.
5459                            pkg.applicationInfo.requiredCpuAbi = null;
5460                        } else {
5461                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5462                            return null;
5463                        }
5464                        handle.close();
5465                    }
5466
5467                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5468                    final int[] userIds = sUserManager.getUserIds();
5469                    synchronized (mInstallLock) {
5470                        for (int userId : userIds) {
5471                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
5472                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
5473                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
5474                                        + ")");
5475                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5476                                return null;
5477                            }
5478                        }
5479                    }
5480                }
5481            } catch (IOException ioe) {
5482                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5483            }
5484        }
5485        pkg.mScanPath = path;
5486
5487        if ((scanMode&SCAN_NO_DEX) == 0) {
5488            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5489                    == DEX_OPT_FAILED) {
5490                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5491                    removeDataDirsLI(pkg.packageName);
5492                }
5493
5494                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5495                return null;
5496            }
5497        }
5498
5499        if (mFactoryTest && pkg.requestedPermissions.contains(
5500                android.Manifest.permission.FACTORY_TEST)) {
5501            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5502        }
5503
5504        ArrayList<PackageParser.Package> clientLibPkgs = null;
5505
5506        // writer
5507        synchronized (mPackages) {
5508            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5509                // Only system apps can add new shared libraries.
5510                if (pkg.libraryNames != null) {
5511                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5512                        String name = pkg.libraryNames.get(i);
5513                        boolean allowed = false;
5514                        if (isUpdatedSystemApp(pkg)) {
5515                            // New library entries can only be added through the
5516                            // system image.  This is important to get rid of a lot
5517                            // of nasty edge cases: for example if we allowed a non-
5518                            // system update of the app to add a library, then uninstalling
5519                            // the update would make the library go away, and assumptions
5520                            // we made such as through app install filtering would now
5521                            // have allowed apps on the device which aren't compatible
5522                            // with it.  Better to just have the restriction here, be
5523                            // conservative, and create many fewer cases that can negatively
5524                            // impact the user experience.
5525                            final PackageSetting sysPs = mSettings
5526                                    .getDisabledSystemPkgLPr(pkg.packageName);
5527                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5528                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5529                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5530                                        allowed = true;
5531                                        allowed = true;
5532                                        break;
5533                                    }
5534                                }
5535                            }
5536                        } else {
5537                            allowed = true;
5538                        }
5539                        if (allowed) {
5540                            if (!mSharedLibraries.containsKey(name)) {
5541                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5542                            } else if (!name.equals(pkg.packageName)) {
5543                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5544                                        + name + " already exists; skipping");
5545                            }
5546                        } else {
5547                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5548                                    + name + " that is not declared on system image; skipping");
5549                        }
5550                    }
5551                    if ((scanMode&SCAN_BOOTING) == 0) {
5552                        // If we are not booting, we need to update any applications
5553                        // that are clients of our shared library.  If we are booting,
5554                        // this will all be done once the scan is complete.
5555                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5556                    }
5557                }
5558            }
5559        }
5560
5561        // We also need to dexopt any apps that are dependent on this library.  Note that
5562        // if these fail, we should abort the install since installing the library will
5563        // result in some apps being broken.
5564        if (clientLibPkgs != null) {
5565            if ((scanMode&SCAN_NO_DEX) == 0) {
5566                for (int i=0; i<clientLibPkgs.size(); i++) {
5567                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5568                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5569                            == DEX_OPT_FAILED) {
5570                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5571                            removeDataDirsLI(pkg.packageName);
5572                        }
5573
5574                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5575                        return null;
5576                    }
5577                }
5578            }
5579        }
5580
5581        // Request the ActivityManager to kill the process(only for existing packages)
5582        // so that we do not end up in a confused state while the user is still using the older
5583        // version of the application while the new one gets installed.
5584        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5585            // If the package lives in an asec, tell everyone that the container is going
5586            // away so they can clean up any references to its resources (which would prevent
5587            // vold from being able to unmount the asec)
5588            if (isForwardLocked(pkg) || isExternal(pkg)) {
5589                if (DEBUG_INSTALL) {
5590                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5591                }
5592                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5593                final ArrayList<String> pkgList = new ArrayList<String>(1);
5594                pkgList.add(pkg.applicationInfo.packageName);
5595                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5596            }
5597
5598            // Post the request that it be killed now that the going-away broadcast is en route
5599            killApplication(pkg.applicationInfo.packageName,
5600                        pkg.applicationInfo.uid, "update pkg");
5601        }
5602
5603        // Also need to kill any apps that are dependent on the library.
5604        if (clientLibPkgs != null) {
5605            for (int i=0; i<clientLibPkgs.size(); i++) {
5606                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5607                killApplication(clientPkg.applicationInfo.packageName,
5608                        clientPkg.applicationInfo.uid, "update lib");
5609            }
5610        }
5611
5612        // writer
5613        synchronized (mPackages) {
5614            if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5615                // We don't do this here during boot because we can do it all
5616                // at once after scanning all existing packages.
5617                adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5618                        true, forceDex, (scanMode & SCAN_DEFER_DEX) != 0);
5619            }
5620            // We don't expect installation to fail beyond this point,
5621            if ((scanMode&SCAN_MONITOR) != 0) {
5622                mAppDirs.put(pkg.mPath, pkg);
5623            }
5624            // Add the new setting to mSettings
5625            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5626            // Add the new setting to mPackages
5627            mPackages.put(pkg.applicationInfo.packageName, pkg);
5628            // Make sure we don't accidentally delete its data.
5629            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5630            while (iter.hasNext()) {
5631                PackageCleanItem item = iter.next();
5632                if (pkgName.equals(item.packageName)) {
5633                    iter.remove();
5634                }
5635            }
5636
5637            // Take care of first install / last update times.
5638            if (currentTime != 0) {
5639                if (pkgSetting.firstInstallTime == 0) {
5640                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5641                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5642                    pkgSetting.lastUpdateTime = currentTime;
5643                }
5644            } else if (pkgSetting.firstInstallTime == 0) {
5645                // We need *something*.  Take time time stamp of the file.
5646                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5647            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5648                if (scanFileTime != pkgSetting.timeStamp) {
5649                    // A package on the system image has changed; consider this
5650                    // to be an update.
5651                    pkgSetting.lastUpdateTime = scanFileTime;
5652                }
5653            }
5654
5655            // Add the package's KeySets to the global KeySetManager
5656            KeySetManager ksm = mSettings.mKeySetManager;
5657            try {
5658                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5659                if (pkg.mKeySetMapping != null) {
5660                    for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) {
5661                        if (entry.getValue() != null) {
5662                            ksm.addDefinedKeySetToPackage(pkg.packageName,
5663                                entry.getValue(), entry.getKey());
5664                        }
5665                    }
5666                }
5667            } catch (NullPointerException e) {
5668                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5669            } catch (IllegalArgumentException e) {
5670                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5671            }
5672
5673            int N = pkg.providers.size();
5674            StringBuilder r = null;
5675            int i;
5676            for (i=0; i<N; i++) {
5677                PackageParser.Provider p = pkg.providers.get(i);
5678                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5679                        p.info.processName, pkg.applicationInfo.uid);
5680                mProviders.addProvider(p);
5681                p.syncable = p.info.isSyncable;
5682                if (p.info.authority != null) {
5683                    String names[] = p.info.authority.split(";");
5684                    p.info.authority = null;
5685                    for (int j = 0; j < names.length; j++) {
5686                        if (j == 1 && p.syncable) {
5687                            // We only want the first authority for a provider to possibly be
5688                            // syncable, so if we already added this provider using a different
5689                            // authority clear the syncable flag. We copy the provider before
5690                            // changing it because the mProviders object contains a reference
5691                            // to a provider that we don't want to change.
5692                            // Only do this for the second authority since the resulting provider
5693                            // object can be the same for all future authorities for this provider.
5694                            p = new PackageParser.Provider(p);
5695                            p.syncable = false;
5696                        }
5697                        if (!mProvidersByAuthority.containsKey(names[j])) {
5698                            mProvidersByAuthority.put(names[j], p);
5699                            if (p.info.authority == null) {
5700                                p.info.authority = names[j];
5701                            } else {
5702                                p.info.authority = p.info.authority + ";" + names[j];
5703                            }
5704                            if (DEBUG_PACKAGE_SCANNING) {
5705                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5706                                    Log.d(TAG, "Registered content provider: " + names[j]
5707                                            + ", className = " + p.info.name + ", isSyncable = "
5708                                            + p.info.isSyncable);
5709                            }
5710                        } else {
5711                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5712                            Slog.w(TAG, "Skipping provider name " + names[j] +
5713                                    " (in package " + pkg.applicationInfo.packageName +
5714                                    "): name already used by "
5715                                    + ((other != null && other.getComponentName() != null)
5716                                            ? other.getComponentName().getPackageName() : "?"));
5717                        }
5718                    }
5719                }
5720                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5721                    if (r == null) {
5722                        r = new StringBuilder(256);
5723                    } else {
5724                        r.append(' ');
5725                    }
5726                    r.append(p.info.name);
5727                }
5728            }
5729            if (r != null) {
5730                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5731            }
5732
5733            N = pkg.services.size();
5734            r = null;
5735            for (i=0; i<N; i++) {
5736                PackageParser.Service s = pkg.services.get(i);
5737                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5738                        s.info.processName, pkg.applicationInfo.uid);
5739                mServices.addService(s);
5740                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5741                    if (r == null) {
5742                        r = new StringBuilder(256);
5743                    } else {
5744                        r.append(' ');
5745                    }
5746                    r.append(s.info.name);
5747                }
5748            }
5749            if (r != null) {
5750                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5751            }
5752
5753            N = pkg.receivers.size();
5754            r = null;
5755            for (i=0; i<N; i++) {
5756                PackageParser.Activity a = pkg.receivers.get(i);
5757                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5758                        a.info.processName, pkg.applicationInfo.uid);
5759                mReceivers.addActivity(a, "receiver");
5760                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5761                    if (r == null) {
5762                        r = new StringBuilder(256);
5763                    } else {
5764                        r.append(' ');
5765                    }
5766                    r.append(a.info.name);
5767                }
5768            }
5769            if (r != null) {
5770                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5771            }
5772
5773            N = pkg.activities.size();
5774            r = null;
5775            for (i=0; i<N; i++) {
5776                PackageParser.Activity a = pkg.activities.get(i);
5777                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5778                        a.info.processName, pkg.applicationInfo.uid);
5779                mActivities.addActivity(a, "activity");
5780                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5781                    if (r == null) {
5782                        r = new StringBuilder(256);
5783                    } else {
5784                        r.append(' ');
5785                    }
5786                    r.append(a.info.name);
5787                }
5788            }
5789            if (r != null) {
5790                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5791            }
5792
5793            N = pkg.permissionGroups.size();
5794            r = null;
5795            for (i=0; i<N; i++) {
5796                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5797                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5798                if (cur == null) {
5799                    mPermissionGroups.put(pg.info.name, pg);
5800                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5801                        if (r == null) {
5802                            r = new StringBuilder(256);
5803                        } else {
5804                            r.append(' ');
5805                        }
5806                        r.append(pg.info.name);
5807                    }
5808                } else {
5809                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5810                            + pg.info.packageName + " ignored: original from "
5811                            + cur.info.packageName);
5812                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5813                        if (r == null) {
5814                            r = new StringBuilder(256);
5815                        } else {
5816                            r.append(' ');
5817                        }
5818                        r.append("DUP:");
5819                        r.append(pg.info.name);
5820                    }
5821                }
5822            }
5823            if (r != null) {
5824                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5825            }
5826
5827            N = pkg.permissions.size();
5828            r = null;
5829            for (i=0; i<N; i++) {
5830                PackageParser.Permission p = pkg.permissions.get(i);
5831                HashMap<String, BasePermission> permissionMap =
5832                        p.tree ? mSettings.mPermissionTrees
5833                        : mSettings.mPermissions;
5834                p.group = mPermissionGroups.get(p.info.group);
5835                if (p.info.group == null || p.group != null) {
5836                    BasePermission bp = permissionMap.get(p.info.name);
5837                    if (bp == null) {
5838                        bp = new BasePermission(p.info.name, p.info.packageName,
5839                                BasePermission.TYPE_NORMAL);
5840                        permissionMap.put(p.info.name, bp);
5841                    }
5842                    if (bp.perm == null) {
5843                        if (bp.sourcePackage != null
5844                                && !bp.sourcePackage.equals(p.info.packageName)) {
5845                            // If this is a permission that was formerly defined by a non-system
5846                            // app, but is now defined by a system app (following an upgrade),
5847                            // discard the previous declaration and consider the system's to be
5848                            // canonical.
5849                            if (isSystemApp(p.owner)) {
5850                                String msg = "New decl " + p.owner + " of permission  "
5851                                        + p.info.name + " is system";
5852                                reportSettingsProblem(Log.WARN, msg);
5853                                bp.sourcePackage = null;
5854                            }
5855                        }
5856                        if (bp.sourcePackage == null
5857                                || bp.sourcePackage.equals(p.info.packageName)) {
5858                            BasePermission tree = findPermissionTreeLP(p.info.name);
5859                            if (tree == null
5860                                    || tree.sourcePackage.equals(p.info.packageName)) {
5861                                bp.packageSetting = pkgSetting;
5862                                bp.perm = p;
5863                                bp.uid = pkg.applicationInfo.uid;
5864                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5865                                    if (r == null) {
5866                                        r = new StringBuilder(256);
5867                                    } else {
5868                                        r.append(' ');
5869                                    }
5870                                    r.append(p.info.name);
5871                                }
5872                            } else {
5873                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5874                                        + p.info.packageName + " ignored: base tree "
5875                                        + tree.name + " is from package "
5876                                        + tree.sourcePackage);
5877                            }
5878                        } else {
5879                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5880                                    + p.info.packageName + " ignored: original from "
5881                                    + bp.sourcePackage);
5882                        }
5883                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5884                        if (r == null) {
5885                            r = new StringBuilder(256);
5886                        } else {
5887                            r.append(' ');
5888                        }
5889                        r.append("DUP:");
5890                        r.append(p.info.name);
5891                    }
5892                    if (bp.perm == p) {
5893                        bp.protectionLevel = p.info.protectionLevel;
5894                    }
5895                } else {
5896                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5897                            + p.info.packageName + " ignored: no group "
5898                            + p.group);
5899                }
5900            }
5901            if (r != null) {
5902                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5903            }
5904
5905            N = pkg.instrumentation.size();
5906            r = null;
5907            for (i=0; i<N; i++) {
5908                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5909                a.info.packageName = pkg.applicationInfo.packageName;
5910                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5911                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5912                a.info.dataDir = pkg.applicationInfo.dataDir;
5913                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5914                mInstrumentation.put(a.getComponentName(), a);
5915                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5916                    if (r == null) {
5917                        r = new StringBuilder(256);
5918                    } else {
5919                        r.append(' ');
5920                    }
5921                    r.append(a.info.name);
5922                }
5923            }
5924            if (r != null) {
5925                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5926            }
5927
5928            if (pkg.protectedBroadcasts != null) {
5929                N = pkg.protectedBroadcasts.size();
5930                for (i=0; i<N; i++) {
5931                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5932                }
5933            }
5934
5935            pkgSetting.setTimeStamp(scanFileTime);
5936
5937            // Create idmap files for pairs of (packages, overlay packages).
5938            // Note: "android", ie framework-res.apk, is handled by native layers.
5939            if (pkg.mOverlayTarget != null) {
5940                // This is an overlay package.
5941                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5942                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5943                        mOverlays.put(pkg.mOverlayTarget,
5944                                new HashMap<String, PackageParser.Package>());
5945                    }
5946                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5947                    map.put(pkg.packageName, pkg);
5948                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5949                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5950                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5951                        return null;
5952                    }
5953                }
5954            } else if (mOverlays.containsKey(pkg.packageName) &&
5955                    !pkg.packageName.equals("android")) {
5956                // This is a regular package, with one or more known overlay packages.
5957                createIdmapsForPackageLI(pkg);
5958            }
5959        }
5960
5961        return pkg;
5962    }
5963
5964    public void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
5965            boolean doDexOpt, boolean forceDexOpt, boolean deferDexOpt) {
5966        String requiredInstructionSet = null;
5967        PackageSetting requirer = null;
5968        for (PackageSetting ps : packagesForUser) {
5969            if (ps.requiredCpuAbiString != null) {
5970                final String instructionSet = VMRuntime.getInstructionSet(ps.requiredCpuAbiString);
5971                if (requiredInstructionSet != null) {
5972                    if (!instructionSet.equals(requiredInstructionSet)) {
5973                        // We have a mismatch between instruction sets (say arm vs arm64).
5974                        //
5975                        // TODO: We should rescan all the packages in a shared UID to check if
5976                        // they do contain shared libs for other ABIs in addition to the ones we've
5977                        // already extracted. For example, the package might contain both arm64-v8a
5978                        // and armeabi-v7a shared libs, and we'd have chosen arm64-v8a on 64 bit
5979                        // devices.
5980                        String errorMessage = "Instruction set mismatch, " + requirer.pkg.packageName
5981                                + " requires " + requiredInstructionSet + " whereas " + ps.pkg.packageName
5982                                + " requires " + instructionSet;
5983                        Slog.e(TAG, errorMessage);
5984
5985                        reportSettingsProblem(Log.WARN, errorMessage);
5986                        // Give up, don't bother making any other changes to the package settings.
5987                        return;
5988                    }
5989                } else {
5990                    requiredInstructionSet = instructionSet;
5991                    requirer = ps;
5992                }
5993            }
5994        }
5995
5996        if (requiredInstructionSet != null) {
5997            for (PackageSetting ps : packagesForUser) {
5998                if (ps.requiredCpuAbiString == null) {
5999                    ps.requiredCpuAbiString = requirer.requiredCpuAbiString;
6000                    if (ps.pkg != null) {
6001                        ps.pkg.applicationInfo.requiredCpuAbi = requirer.requiredCpuAbiString;
6002                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + ps.requiredCpuAbiString);
6003                        if (doDexOpt) {
6004                            performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true);
6005                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
6006                        }
6007                    }
6008                }
6009            }
6010        }
6011    }
6012
6013    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6014        synchronized (mPackages) {
6015            mResolverReplaced = true;
6016            // Set up information for custom user intent resolution activity.
6017            mResolveActivity.applicationInfo = pkg.applicationInfo;
6018            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6019            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6020            mResolveActivity.processName = null;
6021            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6022            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6023                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6024            mResolveActivity.theme = 0;
6025            mResolveActivity.exported = true;
6026            mResolveActivity.enabled = true;
6027            mResolveInfo.activityInfo = mResolveActivity;
6028            mResolveInfo.priority = 0;
6029            mResolveInfo.preferredOrder = 0;
6030            mResolveInfo.match = 0;
6031            mResolveComponentName = mCustomResolverComponentName;
6032            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6033                    mResolveComponentName);
6034        }
6035    }
6036
6037    private String calculateApkRoot(final String codePathString) {
6038        final File codePath = new File(codePathString);
6039        final File codeRoot;
6040        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6041            codeRoot = Environment.getRootDirectory();
6042        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6043            codeRoot = Environment.getOemDirectory();
6044        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6045            codeRoot = Environment.getVendorDirectory();
6046        } else {
6047            // Unrecognized code path; take its top real segment as the apk root:
6048            // e.g. /something/app/blah.apk => /something
6049            try {
6050                File f = codePath.getCanonicalFile();
6051                File parent = f.getParentFile();    // non-null because codePath is a file
6052                File tmp;
6053                while ((tmp = parent.getParentFile()) != null) {
6054                    f = parent;
6055                    parent = tmp;
6056                }
6057                codeRoot = f;
6058                Slog.w(TAG, "Unrecognized code path "
6059                        + codePath + " - using " + codeRoot);
6060            } catch (IOException e) {
6061                // Can't canonicalize the lib path -- shenanigans?
6062                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6063                return Environment.getRootDirectory().getPath();
6064            }
6065        }
6066        return codeRoot.getPath();
6067    }
6068
6069    // This is the initial scan-time determination of how to handle a given
6070    // package for purposes of native library location.
6071    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
6072            PackageSetting pkgSetting) {
6073        // "bundled" here means system-installed with no overriding update
6074        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
6075        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6076        final File libDir;
6077        if (bundledApk) {
6078            // If "/system/lib64/apkname" exists, assume that is the per-package
6079            // native library directory to use; otherwise use "/system/lib/apkname".
6080            String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6081            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
6082            File packLib64 = new File(lib64, apkName);
6083            libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
6084        } else {
6085            libDir = mAppLibInstallDir;
6086        }
6087        final String nativeLibraryPath = (new File(libDir, apkName)).getPath();
6088        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
6089        pkgSetting.nativeLibraryPathString = nativeLibraryPath;
6090    }
6091
6092    // Deduces the required ABI of an upgraded system app.
6093    private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) {
6094        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6095        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6096
6097        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
6098        // or similar.
6099        final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath());
6100        final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath());
6101
6102        // Assume that the bundled native libraries always correspond to the
6103        // most preferred 32 or 64 bit ABI.
6104        if (lib64.exists()) {
6105            pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6106            pkgSetting.requiredCpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0];
6107        } else if (lib.exists()) {
6108            pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6109            pkgSetting.requiredCpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0];
6110        } else {
6111            // This is the case where the app has no native code.
6112            pkg.applicationInfo.requiredCpuAbi = null;
6113            pkgSetting.requiredCpuAbiString = null;
6114        }
6115    }
6116
6117    private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir)
6118            throws IOException {
6119        if (!nativeLibraryDir.isDirectory()) {
6120            nativeLibraryDir.delete();
6121
6122            if (!nativeLibraryDir.mkdir()) {
6123                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
6124            }
6125
6126            try {
6127                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6128            } catch (ErrnoException e) {
6129                throw new IOException("Cannot chmod native library directory "
6130                        + nativeLibraryDir.getPath(), e);
6131            }
6132        } else if (!SELinux.restorecon(nativeLibraryDir)) {
6133            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
6134        }
6135
6136        /*
6137         * If this is an internal application or our nativeLibraryPath points to
6138         * the app-lib directory, unpack the libraries if necessary.
6139         */
6140        final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
6141        try {
6142            int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS);
6143            if (abi >= 0) {
6144                int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
6145                        nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
6146                if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6147                    return copyRet;
6148                }
6149            }
6150
6151            return abi;
6152        } finally {
6153            handle.close();
6154        }
6155    }
6156
6157    private void killApplication(String pkgName, int appId, String reason) {
6158        // Request the ActivityManager to kill the process(only for existing packages)
6159        // so that we do not end up in a confused state while the user is still using the older
6160        // version of the application while the new one gets installed.
6161        IActivityManager am = ActivityManagerNative.getDefault();
6162        if (am != null) {
6163            try {
6164                am.killApplicationWithAppId(pkgName, appId, reason);
6165            } catch (RemoteException e) {
6166            }
6167        }
6168    }
6169
6170    void removePackageLI(PackageSetting ps, boolean chatty) {
6171        if (DEBUG_INSTALL) {
6172            if (chatty)
6173                Log.d(TAG, "Removing package " + ps.name);
6174        }
6175
6176        // writer
6177        synchronized (mPackages) {
6178            mPackages.remove(ps.name);
6179            if (ps.codePathString != null) {
6180                mAppDirs.remove(ps.codePathString);
6181            }
6182
6183            final PackageParser.Package pkg = ps.pkg;
6184            if (pkg != null) {
6185                cleanPackageDataStructuresLILPw(pkg, chatty);
6186            }
6187        }
6188    }
6189
6190    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6191        if (DEBUG_INSTALL) {
6192            if (chatty)
6193                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6194        }
6195
6196        // writer
6197        synchronized (mPackages) {
6198            mPackages.remove(pkg.applicationInfo.packageName);
6199            if (pkg.mPath != null) {
6200                mAppDirs.remove(pkg.mPath);
6201            }
6202            cleanPackageDataStructuresLILPw(pkg, chatty);
6203        }
6204    }
6205
6206    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6207        int N = pkg.providers.size();
6208        StringBuilder r = null;
6209        int i;
6210        for (i=0; i<N; i++) {
6211            PackageParser.Provider p = pkg.providers.get(i);
6212            mProviders.removeProvider(p);
6213            if (p.info.authority == null) {
6214
6215                /* There was another ContentProvider with this authority when
6216                 * this app was installed so this authority is null,
6217                 * Ignore it as we don't have to unregister the provider.
6218                 */
6219                continue;
6220            }
6221            String names[] = p.info.authority.split(";");
6222            for (int j = 0; j < names.length; j++) {
6223                if (mProvidersByAuthority.get(names[j]) == p) {
6224                    mProvidersByAuthority.remove(names[j]);
6225                    if (DEBUG_REMOVE) {
6226                        if (chatty)
6227                            Log.d(TAG, "Unregistered content provider: " + names[j]
6228                                    + ", className = " + p.info.name + ", isSyncable = "
6229                                    + p.info.isSyncable);
6230                    }
6231                }
6232            }
6233            if (DEBUG_REMOVE && chatty) {
6234                if (r == null) {
6235                    r = new StringBuilder(256);
6236                } else {
6237                    r.append(' ');
6238                }
6239                r.append(p.info.name);
6240            }
6241        }
6242        if (r != null) {
6243            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6244        }
6245
6246        N = pkg.services.size();
6247        r = null;
6248        for (i=0; i<N; i++) {
6249            PackageParser.Service s = pkg.services.get(i);
6250            mServices.removeService(s);
6251            if (chatty) {
6252                if (r == null) {
6253                    r = new StringBuilder(256);
6254                } else {
6255                    r.append(' ');
6256                }
6257                r.append(s.info.name);
6258            }
6259        }
6260        if (r != null) {
6261            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6262        }
6263
6264        N = pkg.receivers.size();
6265        r = null;
6266        for (i=0; i<N; i++) {
6267            PackageParser.Activity a = pkg.receivers.get(i);
6268            mReceivers.removeActivity(a, "receiver");
6269            if (DEBUG_REMOVE && chatty) {
6270                if (r == null) {
6271                    r = new StringBuilder(256);
6272                } else {
6273                    r.append(' ');
6274                }
6275                r.append(a.info.name);
6276            }
6277        }
6278        if (r != null) {
6279            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6280        }
6281
6282        N = pkg.activities.size();
6283        r = null;
6284        for (i=0; i<N; i++) {
6285            PackageParser.Activity a = pkg.activities.get(i);
6286            mActivities.removeActivity(a, "activity");
6287            if (DEBUG_REMOVE && chatty) {
6288                if (r == null) {
6289                    r = new StringBuilder(256);
6290                } else {
6291                    r.append(' ');
6292                }
6293                r.append(a.info.name);
6294            }
6295        }
6296        if (r != null) {
6297            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6298        }
6299
6300        N = pkg.permissions.size();
6301        r = null;
6302        for (i=0; i<N; i++) {
6303            PackageParser.Permission p = pkg.permissions.get(i);
6304            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6305            if (bp == null) {
6306                bp = mSettings.mPermissionTrees.get(p.info.name);
6307            }
6308            if (bp != null && bp.perm == p) {
6309                bp.perm = null;
6310                if (DEBUG_REMOVE && chatty) {
6311                    if (r == null) {
6312                        r = new StringBuilder(256);
6313                    } else {
6314                        r.append(' ');
6315                    }
6316                    r.append(p.info.name);
6317                }
6318            }
6319        }
6320        if (r != null) {
6321            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6322        }
6323
6324        N = pkg.instrumentation.size();
6325        r = null;
6326        for (i=0; i<N; i++) {
6327            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6328            mInstrumentation.remove(a.getComponentName());
6329            if (DEBUG_REMOVE && chatty) {
6330                if (r == null) {
6331                    r = new StringBuilder(256);
6332                } else {
6333                    r.append(' ');
6334                }
6335                r.append(a.info.name);
6336            }
6337        }
6338        if (r != null) {
6339            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6340        }
6341
6342        r = null;
6343        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6344            // Only system apps can hold shared libraries.
6345            if (pkg.libraryNames != null) {
6346                for (i=0; i<pkg.libraryNames.size(); i++) {
6347                    String name = pkg.libraryNames.get(i);
6348                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6349                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6350                        mSharedLibraries.remove(name);
6351                        if (DEBUG_REMOVE && chatty) {
6352                            if (r == null) {
6353                                r = new StringBuilder(256);
6354                            } else {
6355                                r.append(' ');
6356                            }
6357                            r.append(name);
6358                        }
6359                    }
6360                }
6361            }
6362        }
6363        if (r != null) {
6364            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6365        }
6366    }
6367
6368    private static final boolean isPackageFilename(String name) {
6369        return name != null && name.endsWith(".apk");
6370    }
6371
6372    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6373        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6374            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6375                return true;
6376            }
6377        }
6378        return false;
6379    }
6380
6381    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6382    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6383    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6384
6385    private void updatePermissionsLPw(String changingPkg,
6386            PackageParser.Package pkgInfo, int flags) {
6387        // Make sure there are no dangling permission trees.
6388        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6389        while (it.hasNext()) {
6390            final BasePermission bp = it.next();
6391            if (bp.packageSetting == null) {
6392                // We may not yet have parsed the package, so just see if
6393                // we still know about its settings.
6394                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6395            }
6396            if (bp.packageSetting == null) {
6397                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6398                        + " from package " + bp.sourcePackage);
6399                it.remove();
6400            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6401                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6402                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6403                            + " from package " + bp.sourcePackage);
6404                    flags |= UPDATE_PERMISSIONS_ALL;
6405                    it.remove();
6406                }
6407            }
6408        }
6409
6410        // Make sure all dynamic permissions have been assigned to a package,
6411        // and make sure there are no dangling permissions.
6412        it = mSettings.mPermissions.values().iterator();
6413        while (it.hasNext()) {
6414            final BasePermission bp = it.next();
6415            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6416                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6417                        + bp.name + " pkg=" + bp.sourcePackage
6418                        + " info=" + bp.pendingInfo);
6419                if (bp.packageSetting == null && bp.pendingInfo != null) {
6420                    final BasePermission tree = findPermissionTreeLP(bp.name);
6421                    if (tree != null && tree.perm != null) {
6422                        bp.packageSetting = tree.packageSetting;
6423                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6424                                new PermissionInfo(bp.pendingInfo));
6425                        bp.perm.info.packageName = tree.perm.info.packageName;
6426                        bp.perm.info.name = bp.name;
6427                        bp.uid = tree.uid;
6428                    }
6429                }
6430            }
6431            if (bp.packageSetting == null) {
6432                // We may not yet have parsed the package, so just see if
6433                // we still know about its settings.
6434                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6435            }
6436            if (bp.packageSetting == null) {
6437                Slog.w(TAG, "Removing dangling permission: " + bp.name
6438                        + " from package " + bp.sourcePackage);
6439                it.remove();
6440            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6441                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6442                    Slog.i(TAG, "Removing old permission: " + bp.name
6443                            + " from package " + bp.sourcePackage);
6444                    flags |= UPDATE_PERMISSIONS_ALL;
6445                    it.remove();
6446                }
6447            }
6448        }
6449
6450        // Now update the permissions for all packages, in particular
6451        // replace the granted permissions of the system packages.
6452        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6453            for (PackageParser.Package pkg : mPackages.values()) {
6454                if (pkg != pkgInfo) {
6455                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6456                }
6457            }
6458        }
6459
6460        if (pkgInfo != null) {
6461            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6462        }
6463    }
6464
6465    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6466        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6467        if (ps == null) {
6468            return;
6469        }
6470        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6471        HashSet<String> origPermissions = gp.grantedPermissions;
6472        boolean changedPermission = false;
6473
6474        if (replace) {
6475            ps.permissionsFixed = false;
6476            if (gp == ps) {
6477                origPermissions = new HashSet<String>(gp.grantedPermissions);
6478                gp.grantedPermissions.clear();
6479                gp.gids = mGlobalGids;
6480            }
6481        }
6482
6483        if (gp.gids == null) {
6484            gp.gids = mGlobalGids;
6485        }
6486
6487        final int N = pkg.requestedPermissions.size();
6488        for (int i=0; i<N; i++) {
6489            final String name = pkg.requestedPermissions.get(i);
6490            final boolean required = pkg.requestedPermissionsRequired.get(i);
6491            final BasePermission bp = mSettings.mPermissions.get(name);
6492            if (DEBUG_INSTALL) {
6493                if (gp != ps) {
6494                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6495                }
6496            }
6497
6498            if (bp == null || bp.packageSetting == null) {
6499                Slog.w(TAG, "Unknown permission " + name
6500                        + " in package " + pkg.packageName);
6501                continue;
6502            }
6503
6504            final String perm = bp.name;
6505            boolean allowed;
6506            boolean allowedSig = false;
6507            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6508            if (level == PermissionInfo.PROTECTION_NORMAL
6509                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6510                // We grant a normal or dangerous permission if any of the following
6511                // are true:
6512                // 1) The permission is required
6513                // 2) The permission is optional, but was granted in the past
6514                // 3) The permission is optional, but was requested by an
6515                //    app in /system (not /data)
6516                //
6517                // Otherwise, reject the permission.
6518                allowed = (required || origPermissions.contains(perm)
6519                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6520            } else if (bp.packageSetting == null) {
6521                // This permission is invalid; skip it.
6522                allowed = false;
6523            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6524                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6525                if (allowed) {
6526                    allowedSig = true;
6527                }
6528            } else {
6529                allowed = false;
6530            }
6531            if (DEBUG_INSTALL) {
6532                if (gp != ps) {
6533                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6534                }
6535            }
6536            if (allowed) {
6537                if (!isSystemApp(ps) && ps.permissionsFixed) {
6538                    // If this is an existing, non-system package, then
6539                    // we can't add any new permissions to it.
6540                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6541                        // Except...  if this is a permission that was added
6542                        // to the platform (note: need to only do this when
6543                        // updating the platform).
6544                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6545                    }
6546                }
6547                if (allowed) {
6548                    if (!gp.grantedPermissions.contains(perm)) {
6549                        changedPermission = true;
6550                        gp.grantedPermissions.add(perm);
6551                        gp.gids = appendInts(gp.gids, bp.gids);
6552                    } else if (!ps.haveGids) {
6553                        gp.gids = appendInts(gp.gids, bp.gids);
6554                    }
6555                } else {
6556                    Slog.w(TAG, "Not granting permission " + perm
6557                            + " to package " + pkg.packageName
6558                            + " because it was previously installed without");
6559                }
6560            } else {
6561                if (gp.grantedPermissions.remove(perm)) {
6562                    changedPermission = true;
6563                    gp.gids = removeInts(gp.gids, bp.gids);
6564                    Slog.i(TAG, "Un-granting permission " + perm
6565                            + " from package " + pkg.packageName
6566                            + " (protectionLevel=" + bp.protectionLevel
6567                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6568                            + ")");
6569                } else {
6570                    Slog.w(TAG, "Not granting permission " + perm
6571                            + " to package " + pkg.packageName
6572                            + " (protectionLevel=" + bp.protectionLevel
6573                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6574                            + ")");
6575                }
6576            }
6577        }
6578
6579        if ((changedPermission || replace) && !ps.permissionsFixed &&
6580                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6581            // This is the first that we have heard about this package, so the
6582            // permissions we have now selected are fixed until explicitly
6583            // changed.
6584            ps.permissionsFixed = true;
6585        }
6586        ps.haveGids = true;
6587    }
6588
6589    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6590        boolean allowed = false;
6591        final int NP = PackageParser.NEW_PERMISSIONS.length;
6592        for (int ip=0; ip<NP; ip++) {
6593            final PackageParser.NewPermissionInfo npi
6594                    = PackageParser.NEW_PERMISSIONS[ip];
6595            if (npi.name.equals(perm)
6596                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6597                allowed = true;
6598                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6599                        + pkg.packageName);
6600                break;
6601            }
6602        }
6603        return allowed;
6604    }
6605
6606    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6607                                          BasePermission bp, HashSet<String> origPermissions) {
6608        boolean allowed;
6609        allowed = (compareSignatures(
6610                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6611                        == PackageManager.SIGNATURE_MATCH)
6612                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6613                        == PackageManager.SIGNATURE_MATCH);
6614        if (!allowed && (bp.protectionLevel
6615                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6616            if (isSystemApp(pkg)) {
6617                // For updated system applications, a system permission
6618                // is granted only if it had been defined by the original application.
6619                if (isUpdatedSystemApp(pkg)) {
6620                    final PackageSetting sysPs = mSettings
6621                            .getDisabledSystemPkgLPr(pkg.packageName);
6622                    final GrantedPermissions origGp = sysPs.sharedUser != null
6623                            ? sysPs.sharedUser : sysPs;
6624
6625                    if (origGp.grantedPermissions.contains(perm)) {
6626                        // If the original was granted this permission, we take
6627                        // that grant decision as read and propagate it to the
6628                        // update.
6629                        allowed = true;
6630                    } else {
6631                        // The system apk may have been updated with an older
6632                        // version of the one on the data partition, but which
6633                        // granted a new system permission that it didn't have
6634                        // before.  In this case we do want to allow the app to
6635                        // now get the new permission if the ancestral apk is
6636                        // privileged to get it.
6637                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6638                            for (int j=0;
6639                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6640                                if (perm.equals(
6641                                        sysPs.pkg.requestedPermissions.get(j))) {
6642                                    allowed = true;
6643                                    break;
6644                                }
6645                            }
6646                        }
6647                    }
6648                } else {
6649                    allowed = isPrivilegedApp(pkg);
6650                }
6651            }
6652        }
6653        if (!allowed && (bp.protectionLevel
6654                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6655            // For development permissions, a development permission
6656            // is granted only if it was already granted.
6657            allowed = origPermissions.contains(perm);
6658        }
6659        return allowed;
6660    }
6661
6662    final class ActivityIntentResolver
6663            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6664        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6665                boolean defaultOnly, int userId) {
6666            if (!sUserManager.exists(userId)) return null;
6667            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6668            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6669        }
6670
6671        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6672                int userId) {
6673            if (!sUserManager.exists(userId)) return null;
6674            mFlags = flags;
6675            return super.queryIntent(intent, resolvedType,
6676                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6677        }
6678
6679        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6680                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6681            if (!sUserManager.exists(userId)) return null;
6682            if (packageActivities == null) {
6683                return null;
6684            }
6685            mFlags = flags;
6686            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6687            final int N = packageActivities.size();
6688            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6689                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6690
6691            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6692            for (int i = 0; i < N; ++i) {
6693                intentFilters = packageActivities.get(i).intents;
6694                if (intentFilters != null && intentFilters.size() > 0) {
6695                    PackageParser.ActivityIntentInfo[] array =
6696                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6697                    intentFilters.toArray(array);
6698                    listCut.add(array);
6699                }
6700            }
6701            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6702        }
6703
6704        public final void addActivity(PackageParser.Activity a, String type) {
6705            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6706            mActivities.put(a.getComponentName(), a);
6707            if (DEBUG_SHOW_INFO)
6708                Log.v(
6709                TAG, "  " + type + " " +
6710                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6711            if (DEBUG_SHOW_INFO)
6712                Log.v(TAG, "    Class=" + a.info.name);
6713            final int NI = a.intents.size();
6714            for (int j=0; j<NI; j++) {
6715                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6716                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6717                    intent.setPriority(0);
6718                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6719                            + a.className + " with priority > 0, forcing to 0");
6720                }
6721                if (DEBUG_SHOW_INFO) {
6722                    Log.v(TAG, "    IntentFilter:");
6723                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6724                }
6725                if (!intent.debugCheck()) {
6726                    Log.w(TAG, "==> For Activity " + a.info.name);
6727                }
6728                addFilter(intent);
6729            }
6730        }
6731
6732        public final void removeActivity(PackageParser.Activity a, String type) {
6733            mActivities.remove(a.getComponentName());
6734            if (DEBUG_SHOW_INFO) {
6735                Log.v(TAG, "  " + type + " "
6736                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6737                                : a.info.name) + ":");
6738                Log.v(TAG, "    Class=" + a.info.name);
6739            }
6740            final int NI = a.intents.size();
6741            for (int j=0; j<NI; j++) {
6742                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6743                if (DEBUG_SHOW_INFO) {
6744                    Log.v(TAG, "    IntentFilter:");
6745                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6746                }
6747                removeFilter(intent);
6748            }
6749        }
6750
6751        @Override
6752        protected boolean allowFilterResult(
6753                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6754            ActivityInfo filterAi = filter.activity.info;
6755            for (int i=dest.size()-1; i>=0; i--) {
6756                ActivityInfo destAi = dest.get(i).activityInfo;
6757                if (destAi.name == filterAi.name
6758                        && destAi.packageName == filterAi.packageName) {
6759                    return false;
6760                }
6761            }
6762            return true;
6763        }
6764
6765        @Override
6766        protected ActivityIntentInfo[] newArray(int size) {
6767            return new ActivityIntentInfo[size];
6768        }
6769
6770        @Override
6771        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6772            if (!sUserManager.exists(userId)) return true;
6773            PackageParser.Package p = filter.activity.owner;
6774            if (p != null) {
6775                PackageSetting ps = (PackageSetting)p.mExtras;
6776                if (ps != null) {
6777                    // System apps are never considered stopped for purposes of
6778                    // filtering, because there may be no way for the user to
6779                    // actually re-launch them.
6780                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6781                            && ps.getStopped(userId);
6782                }
6783            }
6784            return false;
6785        }
6786
6787        @Override
6788        protected boolean isPackageForFilter(String packageName,
6789                PackageParser.ActivityIntentInfo info) {
6790            return packageName.equals(info.activity.owner.packageName);
6791        }
6792
6793        @Override
6794        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6795                int match, int userId) {
6796            if (!sUserManager.exists(userId)) return null;
6797            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6798                return null;
6799            }
6800            final PackageParser.Activity activity = info.activity;
6801            if (mSafeMode && (activity.info.applicationInfo.flags
6802                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6803                return null;
6804            }
6805            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6806            if (ps == null) {
6807                return null;
6808            }
6809            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6810                    ps.readUserState(userId), userId);
6811            if (ai == null) {
6812                return null;
6813            }
6814            final ResolveInfo res = new ResolveInfo();
6815            res.activityInfo = ai;
6816            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6817                res.filter = info;
6818            }
6819            res.priority = info.getPriority();
6820            res.preferredOrder = activity.owner.mPreferredOrder;
6821            //System.out.println("Result: " + res.activityInfo.className +
6822            //                   " = " + res.priority);
6823            res.match = match;
6824            res.isDefault = info.hasDefault;
6825            res.labelRes = info.labelRes;
6826            res.nonLocalizedLabel = info.nonLocalizedLabel;
6827            res.icon = info.icon;
6828            res.system = isSystemApp(res.activityInfo.applicationInfo);
6829            return res;
6830        }
6831
6832        @Override
6833        protected void sortResults(List<ResolveInfo> results) {
6834            Collections.sort(results, mResolvePrioritySorter);
6835        }
6836
6837        @Override
6838        protected void dumpFilter(PrintWriter out, String prefix,
6839                PackageParser.ActivityIntentInfo filter) {
6840            out.print(prefix); out.print(
6841                    Integer.toHexString(System.identityHashCode(filter.activity)));
6842                    out.print(' ');
6843                    filter.activity.printComponentShortName(out);
6844                    out.print(" filter ");
6845                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6846        }
6847
6848//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6849//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6850//            final List<ResolveInfo> retList = Lists.newArrayList();
6851//            while (i.hasNext()) {
6852//                final ResolveInfo resolveInfo = i.next();
6853//                if (isEnabledLP(resolveInfo.activityInfo)) {
6854//                    retList.add(resolveInfo);
6855//                }
6856//            }
6857//            return retList;
6858//        }
6859
6860        // Keys are String (activity class name), values are Activity.
6861        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6862                = new HashMap<ComponentName, PackageParser.Activity>();
6863        private int mFlags;
6864    }
6865
6866    private final class ServiceIntentResolver
6867            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6868        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6869                boolean defaultOnly, int userId) {
6870            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6871            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6872        }
6873
6874        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6875                int userId) {
6876            if (!sUserManager.exists(userId)) return null;
6877            mFlags = flags;
6878            return super.queryIntent(intent, resolvedType,
6879                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6880        }
6881
6882        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6883                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6884            if (!sUserManager.exists(userId)) return null;
6885            if (packageServices == null) {
6886                return null;
6887            }
6888            mFlags = flags;
6889            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6890            final int N = packageServices.size();
6891            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6892                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6893
6894            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6895            for (int i = 0; i < N; ++i) {
6896                intentFilters = packageServices.get(i).intents;
6897                if (intentFilters != null && intentFilters.size() > 0) {
6898                    PackageParser.ServiceIntentInfo[] array =
6899                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6900                    intentFilters.toArray(array);
6901                    listCut.add(array);
6902                }
6903            }
6904            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6905        }
6906
6907        public final void addService(PackageParser.Service s) {
6908            mServices.put(s.getComponentName(), s);
6909            if (DEBUG_SHOW_INFO) {
6910                Log.v(TAG, "  "
6911                        + (s.info.nonLocalizedLabel != null
6912                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6913                Log.v(TAG, "    Class=" + s.info.name);
6914            }
6915            final int NI = s.intents.size();
6916            int j;
6917            for (j=0; j<NI; j++) {
6918                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6919                if (DEBUG_SHOW_INFO) {
6920                    Log.v(TAG, "    IntentFilter:");
6921                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6922                }
6923                if (!intent.debugCheck()) {
6924                    Log.w(TAG, "==> For Service " + s.info.name);
6925                }
6926                addFilter(intent);
6927            }
6928        }
6929
6930        public final void removeService(PackageParser.Service s) {
6931            mServices.remove(s.getComponentName());
6932            if (DEBUG_SHOW_INFO) {
6933                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
6934                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6935                Log.v(TAG, "    Class=" + s.info.name);
6936            }
6937            final int NI = s.intents.size();
6938            int j;
6939            for (j=0; j<NI; j++) {
6940                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6941                if (DEBUG_SHOW_INFO) {
6942                    Log.v(TAG, "    IntentFilter:");
6943                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6944                }
6945                removeFilter(intent);
6946            }
6947        }
6948
6949        @Override
6950        protected boolean allowFilterResult(
6951                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
6952            ServiceInfo filterSi = filter.service.info;
6953            for (int i=dest.size()-1; i>=0; i--) {
6954                ServiceInfo destAi = dest.get(i).serviceInfo;
6955                if (destAi.name == filterSi.name
6956                        && destAi.packageName == filterSi.packageName) {
6957                    return false;
6958                }
6959            }
6960            return true;
6961        }
6962
6963        @Override
6964        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
6965            return new PackageParser.ServiceIntentInfo[size];
6966        }
6967
6968        @Override
6969        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
6970            if (!sUserManager.exists(userId)) return true;
6971            PackageParser.Package p = filter.service.owner;
6972            if (p != null) {
6973                PackageSetting ps = (PackageSetting)p.mExtras;
6974                if (ps != null) {
6975                    // System apps are never considered stopped for purposes of
6976                    // filtering, because there may be no way for the user to
6977                    // actually re-launch them.
6978                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6979                            && ps.getStopped(userId);
6980                }
6981            }
6982            return false;
6983        }
6984
6985        @Override
6986        protected boolean isPackageForFilter(String packageName,
6987                PackageParser.ServiceIntentInfo info) {
6988            return packageName.equals(info.service.owner.packageName);
6989        }
6990
6991        @Override
6992        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
6993                int match, int userId) {
6994            if (!sUserManager.exists(userId)) return null;
6995            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
6996            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
6997                return null;
6998            }
6999            final PackageParser.Service service = info.service;
7000            if (mSafeMode && (service.info.applicationInfo.flags
7001                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7002                return null;
7003            }
7004            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7005            if (ps == null) {
7006                return null;
7007            }
7008            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7009                    ps.readUserState(userId), userId);
7010            if (si == null) {
7011                return null;
7012            }
7013            final ResolveInfo res = new ResolveInfo();
7014            res.serviceInfo = si;
7015            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7016                res.filter = filter;
7017            }
7018            res.priority = info.getPriority();
7019            res.preferredOrder = service.owner.mPreferredOrder;
7020            //System.out.println("Result: " + res.activityInfo.className +
7021            //                   " = " + res.priority);
7022            res.match = match;
7023            res.isDefault = info.hasDefault;
7024            res.labelRes = info.labelRes;
7025            res.nonLocalizedLabel = info.nonLocalizedLabel;
7026            res.icon = info.icon;
7027            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7028            return res;
7029        }
7030
7031        @Override
7032        protected void sortResults(List<ResolveInfo> results) {
7033            Collections.sort(results, mResolvePrioritySorter);
7034        }
7035
7036        @Override
7037        protected void dumpFilter(PrintWriter out, String prefix,
7038                PackageParser.ServiceIntentInfo filter) {
7039            out.print(prefix); out.print(
7040                    Integer.toHexString(System.identityHashCode(filter.service)));
7041                    out.print(' ');
7042                    filter.service.printComponentShortName(out);
7043                    out.print(" filter ");
7044                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7045        }
7046
7047//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7048//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7049//            final List<ResolveInfo> retList = Lists.newArrayList();
7050//            while (i.hasNext()) {
7051//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7052//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7053//                    retList.add(resolveInfo);
7054//                }
7055//            }
7056//            return retList;
7057//        }
7058
7059        // Keys are String (activity class name), values are Activity.
7060        private final HashMap<ComponentName, PackageParser.Service> mServices
7061                = new HashMap<ComponentName, PackageParser.Service>();
7062        private int mFlags;
7063    };
7064
7065    private final class ProviderIntentResolver
7066            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7067        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7068                boolean defaultOnly, int userId) {
7069            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7070            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7071        }
7072
7073        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7074                int userId) {
7075            if (!sUserManager.exists(userId))
7076                return null;
7077            mFlags = flags;
7078            return super.queryIntent(intent, resolvedType,
7079                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7080        }
7081
7082        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7083                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7084            if (!sUserManager.exists(userId))
7085                return null;
7086            if (packageProviders == null) {
7087                return null;
7088            }
7089            mFlags = flags;
7090            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7091            final int N = packageProviders.size();
7092            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7093                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7094
7095            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7096            for (int i = 0; i < N; ++i) {
7097                intentFilters = packageProviders.get(i).intents;
7098                if (intentFilters != null && intentFilters.size() > 0) {
7099                    PackageParser.ProviderIntentInfo[] array =
7100                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7101                    intentFilters.toArray(array);
7102                    listCut.add(array);
7103                }
7104            }
7105            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7106        }
7107
7108        public final void addProvider(PackageParser.Provider p) {
7109            if (mProviders.containsKey(p.getComponentName())) {
7110                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7111                return;
7112            }
7113
7114            mProviders.put(p.getComponentName(), p);
7115            if (DEBUG_SHOW_INFO) {
7116                Log.v(TAG, "  "
7117                        + (p.info.nonLocalizedLabel != null
7118                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7119                Log.v(TAG, "    Class=" + p.info.name);
7120            }
7121            final int NI = p.intents.size();
7122            int j;
7123            for (j = 0; j < NI; j++) {
7124                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7125                if (DEBUG_SHOW_INFO) {
7126                    Log.v(TAG, "    IntentFilter:");
7127                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7128                }
7129                if (!intent.debugCheck()) {
7130                    Log.w(TAG, "==> For Provider " + p.info.name);
7131                }
7132                addFilter(intent);
7133            }
7134        }
7135
7136        public final void removeProvider(PackageParser.Provider p) {
7137            mProviders.remove(p.getComponentName());
7138            if (DEBUG_SHOW_INFO) {
7139                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7140                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7141                Log.v(TAG, "    Class=" + p.info.name);
7142            }
7143            final int NI = p.intents.size();
7144            int j;
7145            for (j = 0; j < NI; j++) {
7146                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7147                if (DEBUG_SHOW_INFO) {
7148                    Log.v(TAG, "    IntentFilter:");
7149                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7150                }
7151                removeFilter(intent);
7152            }
7153        }
7154
7155        @Override
7156        protected boolean allowFilterResult(
7157                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7158            ProviderInfo filterPi = filter.provider.info;
7159            for (int i = dest.size() - 1; i >= 0; i--) {
7160                ProviderInfo destPi = dest.get(i).providerInfo;
7161                if (destPi.name == filterPi.name
7162                        && destPi.packageName == filterPi.packageName) {
7163                    return false;
7164                }
7165            }
7166            return true;
7167        }
7168
7169        @Override
7170        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7171            return new PackageParser.ProviderIntentInfo[size];
7172        }
7173
7174        @Override
7175        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7176            if (!sUserManager.exists(userId))
7177                return true;
7178            PackageParser.Package p = filter.provider.owner;
7179            if (p != null) {
7180                PackageSetting ps = (PackageSetting) p.mExtras;
7181                if (ps != null) {
7182                    // System apps are never considered stopped for purposes of
7183                    // filtering, because there may be no way for the user to
7184                    // actually re-launch them.
7185                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7186                            && ps.getStopped(userId);
7187                }
7188            }
7189            return false;
7190        }
7191
7192        @Override
7193        protected boolean isPackageForFilter(String packageName,
7194                PackageParser.ProviderIntentInfo info) {
7195            return packageName.equals(info.provider.owner.packageName);
7196        }
7197
7198        @Override
7199        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7200                int match, int userId) {
7201            if (!sUserManager.exists(userId))
7202                return null;
7203            final PackageParser.ProviderIntentInfo info = filter;
7204            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7205                return null;
7206            }
7207            final PackageParser.Provider provider = info.provider;
7208            if (mSafeMode && (provider.info.applicationInfo.flags
7209                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7210                return null;
7211            }
7212            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7213            if (ps == null) {
7214                return null;
7215            }
7216            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7217                    ps.readUserState(userId), userId);
7218            if (pi == null) {
7219                return null;
7220            }
7221            final ResolveInfo res = new ResolveInfo();
7222            res.providerInfo = pi;
7223            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7224                res.filter = filter;
7225            }
7226            res.priority = info.getPriority();
7227            res.preferredOrder = provider.owner.mPreferredOrder;
7228            res.match = match;
7229            res.isDefault = info.hasDefault;
7230            res.labelRes = info.labelRes;
7231            res.nonLocalizedLabel = info.nonLocalizedLabel;
7232            res.icon = info.icon;
7233            res.system = isSystemApp(res.providerInfo.applicationInfo);
7234            return res;
7235        }
7236
7237        @Override
7238        protected void sortResults(List<ResolveInfo> results) {
7239            Collections.sort(results, mResolvePrioritySorter);
7240        }
7241
7242        @Override
7243        protected void dumpFilter(PrintWriter out, String prefix,
7244                PackageParser.ProviderIntentInfo filter) {
7245            out.print(prefix);
7246            out.print(
7247                    Integer.toHexString(System.identityHashCode(filter.provider)));
7248            out.print(' ');
7249            filter.provider.printComponentShortName(out);
7250            out.print(" filter ");
7251            out.println(Integer.toHexString(System.identityHashCode(filter)));
7252        }
7253
7254        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7255                = new HashMap<ComponentName, PackageParser.Provider>();
7256        private int mFlags;
7257    };
7258
7259    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7260            new Comparator<ResolveInfo>() {
7261        public int compare(ResolveInfo r1, ResolveInfo r2) {
7262            int v1 = r1.priority;
7263            int v2 = r2.priority;
7264            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7265            if (v1 != v2) {
7266                return (v1 > v2) ? -1 : 1;
7267            }
7268            v1 = r1.preferredOrder;
7269            v2 = r2.preferredOrder;
7270            if (v1 != v2) {
7271                return (v1 > v2) ? -1 : 1;
7272            }
7273            if (r1.isDefault != r2.isDefault) {
7274                return r1.isDefault ? -1 : 1;
7275            }
7276            v1 = r1.match;
7277            v2 = r2.match;
7278            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7279            if (v1 != v2) {
7280                return (v1 > v2) ? -1 : 1;
7281            }
7282            if (r1.system != r2.system) {
7283                return r1.system ? -1 : 1;
7284            }
7285            return 0;
7286        }
7287    };
7288
7289    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7290            new Comparator<ProviderInfo>() {
7291        public int compare(ProviderInfo p1, ProviderInfo p2) {
7292            final int v1 = p1.initOrder;
7293            final int v2 = p2.initOrder;
7294            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7295        }
7296    };
7297
7298    static final void sendPackageBroadcast(String action, String pkg,
7299            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7300            int[] userIds) {
7301        IActivityManager am = ActivityManagerNative.getDefault();
7302        if (am != null) {
7303            try {
7304                if (userIds == null) {
7305                    userIds = am.getRunningUserIds();
7306                }
7307                for (int id : userIds) {
7308                    final Intent intent = new Intent(action,
7309                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7310                    if (extras != null) {
7311                        intent.putExtras(extras);
7312                    }
7313                    if (targetPkg != null) {
7314                        intent.setPackage(targetPkg);
7315                    }
7316                    // Modify the UID when posting to other users
7317                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7318                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7319                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7320                        intent.putExtra(Intent.EXTRA_UID, uid);
7321                    }
7322                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7323                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7324                    if (DEBUG_BROADCASTS) {
7325                        RuntimeException here = new RuntimeException("here");
7326                        here.fillInStackTrace();
7327                        Slog.d(TAG, "Sending to user " + id + ": "
7328                                + intent.toShortString(false, true, false, false)
7329                                + " " + intent.getExtras(), here);
7330                    }
7331                    am.broadcastIntent(null, intent, null, finishedReceiver,
7332                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7333                            finishedReceiver != null, false, id);
7334                }
7335            } catch (RemoteException ex) {
7336            }
7337        }
7338    }
7339
7340    /**
7341     * Check if the external storage media is available. This is true if there
7342     * is a mounted external storage medium or if the external storage is
7343     * emulated.
7344     */
7345    private boolean isExternalMediaAvailable() {
7346        return mMediaMounted || Environment.isExternalStorageEmulated();
7347    }
7348
7349    @Override
7350    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7351        // writer
7352        synchronized (mPackages) {
7353            if (!isExternalMediaAvailable()) {
7354                // If the external storage is no longer mounted at this point,
7355                // the caller may not have been able to delete all of this
7356                // packages files and can not delete any more.  Bail.
7357                return null;
7358            }
7359            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7360            if (lastPackage != null) {
7361                pkgs.remove(lastPackage);
7362            }
7363            if (pkgs.size() > 0) {
7364                return pkgs.get(0);
7365            }
7366        }
7367        return null;
7368    }
7369
7370    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7371        if (false) {
7372            RuntimeException here = new RuntimeException("here");
7373            here.fillInStackTrace();
7374            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7375                    + " andCode=" + andCode, here);
7376        }
7377        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7378                userId, andCode ? 1 : 0, packageName));
7379    }
7380
7381    void startCleaningPackages() {
7382        // reader
7383        synchronized (mPackages) {
7384            if (!isExternalMediaAvailable()) {
7385                return;
7386            }
7387            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7388                return;
7389            }
7390        }
7391        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7392        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7393        IActivityManager am = ActivityManagerNative.getDefault();
7394        if (am != null) {
7395            try {
7396                am.startService(null, intent, null, UserHandle.USER_OWNER);
7397            } catch (RemoteException e) {
7398            }
7399        }
7400    }
7401
7402    private final class AppDirObserver extends FileObserver {
7403        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7404            super(path, mask);
7405            mRootDir = path;
7406            mIsRom = isrom;
7407            mIsPrivileged = isPrivileged;
7408        }
7409
7410        public void onEvent(int event, String path) {
7411            String removedPackage = null;
7412            int removedAppId = -1;
7413            int[] removedUsers = null;
7414            String addedPackage = null;
7415            int addedAppId = -1;
7416            int[] addedUsers = null;
7417
7418            // TODO post a message to the handler to obtain serial ordering
7419            synchronized (mInstallLock) {
7420                String fullPathStr = null;
7421                File fullPath = null;
7422                if (path != null) {
7423                    fullPath = new File(mRootDir, path);
7424                    fullPathStr = fullPath.getPath();
7425                }
7426
7427                if (DEBUG_APP_DIR_OBSERVER)
7428                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7429
7430                if (!isPackageFilename(path)) {
7431                    if (DEBUG_APP_DIR_OBSERVER)
7432                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7433                    return;
7434                }
7435
7436                // Ignore packages that are being installed or
7437                // have just been installed.
7438                if (ignoreCodePath(fullPathStr)) {
7439                    return;
7440                }
7441                PackageParser.Package p = null;
7442                PackageSetting ps = null;
7443                // reader
7444                synchronized (mPackages) {
7445                    p = mAppDirs.get(fullPathStr);
7446                    if (p != null) {
7447                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7448                        if (ps != null) {
7449                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7450                        } else {
7451                            removedUsers = sUserManager.getUserIds();
7452                        }
7453                    }
7454                    addedUsers = sUserManager.getUserIds();
7455                }
7456                if ((event&REMOVE_EVENTS) != 0) {
7457                    if (ps != null) {
7458                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7459                        removePackageLI(ps, true);
7460                        removedPackage = ps.name;
7461                        removedAppId = ps.appId;
7462                    }
7463                }
7464
7465                if ((event&ADD_EVENTS) != 0) {
7466                    if (p == null) {
7467                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7468                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7469                        if (mIsRom) {
7470                            flags |= PackageParser.PARSE_IS_SYSTEM
7471                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7472                            if (mIsPrivileged) {
7473                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7474                            }
7475                        }
7476                        p = scanPackageLI(fullPath, flags,
7477                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7478                                System.currentTimeMillis(), UserHandle.ALL);
7479                        if (p != null) {
7480                            /*
7481                             * TODO this seems dangerous as the package may have
7482                             * changed since we last acquired the mPackages
7483                             * lock.
7484                             */
7485                            // writer
7486                            synchronized (mPackages) {
7487                                updatePermissionsLPw(p.packageName, p,
7488                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7489                            }
7490                            addedPackage = p.applicationInfo.packageName;
7491                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7492                        }
7493                    }
7494                }
7495
7496                // reader
7497                synchronized (mPackages) {
7498                    mSettings.writeLPr();
7499                }
7500            }
7501
7502            if (removedPackage != null) {
7503                Bundle extras = new Bundle(1);
7504                extras.putInt(Intent.EXTRA_UID, removedAppId);
7505                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7506                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7507                        extras, null, null, removedUsers);
7508            }
7509            if (addedPackage != null) {
7510                Bundle extras = new Bundle(1);
7511                extras.putInt(Intent.EXTRA_UID, addedAppId);
7512                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7513                        extras, null, null, addedUsers);
7514            }
7515        }
7516
7517        private final String mRootDir;
7518        private final boolean mIsRom;
7519        private final boolean mIsPrivileged;
7520    }
7521
7522    /*
7523     * The old-style observer methods all just trampoline to the newer signature with
7524     * expanded install observer API.  The older API continues to work but does not
7525     * supply the additional details of the Observer2 API.
7526     */
7527
7528    /* Called when a downloaded package installation has been confirmed by the user */
7529    public void installPackage(
7530            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
7531        installPackageEtc(packageURI, observer, null, flags, null);
7532    }
7533
7534    /* Called when a downloaded package installation has been confirmed by the user */
7535    @Override
7536    public void installPackage(
7537            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
7538            final String installerPackageName) {
7539        installPackageWithVerificationEtc(packageURI, observer, null, flags,
7540                installerPackageName, null, null, null);
7541    }
7542
7543    @Override
7544    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
7545            int flags, String installerPackageName, Uri verificationURI,
7546            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7547        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7548                VerificationParams.NO_UID, manifestDigest);
7549        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7550                installerPackageName, verificationParams, encryptionParams);
7551    }
7552
7553    @Override
7554    public void installPackageWithVerificationAndEncryption(Uri packageURI,
7555            IPackageInstallObserver observer, int flags, String installerPackageName,
7556            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7557        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7558                installerPackageName, verificationParams, encryptionParams);
7559    }
7560
7561    /*
7562     * And here are the "live" versions that take both observer arguments
7563     */
7564    public void installPackageEtc(
7565            final Uri packageURI, final IPackageInstallObserver observer,
7566            IPackageInstallObserver2 observer2, final int flags) {
7567        installPackageEtc(packageURI, observer, observer2, flags, null);
7568    }
7569
7570    public void installPackageEtc(
7571            final Uri packageURI, final IPackageInstallObserver observer,
7572            final IPackageInstallObserver2 observer2, final int flags,
7573            final String installerPackageName) {
7574        installPackageWithVerificationEtc(packageURI, observer, observer2, flags,
7575                installerPackageName, null, null, null);
7576    }
7577
7578    @Override
7579    public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer,
7580            IPackageInstallObserver2 observer2,
7581            int flags, String installerPackageName, Uri verificationURI,
7582            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7583        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7584                VerificationParams.NO_UID, manifestDigest);
7585        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags,
7586                installerPackageName, verificationParams, encryptionParams);
7587    }
7588
7589    /*
7590     * All of the installPackage...*() methods redirect to this one for the master implementation
7591     */
7592    public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI,
7593            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7594            int flags, String installerPackageName,
7595            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7596        if (observer == null && observer2 == null) {
7597            throw new IllegalArgumentException("No install observer supplied");
7598        }
7599        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7600                null);
7601
7602        final int uid = Binder.getCallingUid();
7603        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7604            try {
7605                if (observer != null) {
7606                    observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7607                }
7608                if (observer2 != null) {
7609                    observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7610                }
7611            } catch (RemoteException re) {
7612            }
7613            return;
7614        }
7615
7616        UserHandle user;
7617        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7618            user = UserHandle.ALL;
7619        } else {
7620            user = new UserHandle(UserHandle.getUserId(uid));
7621        }
7622
7623        final int filteredFlags;
7624
7625        if (uid == Process.SHELL_UID || uid == 0) {
7626            if (DEBUG_INSTALL) {
7627                Slog.v(TAG, "Install from ADB");
7628            }
7629            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7630        } else {
7631            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7632        }
7633
7634        verificationParams.setInstallerUid(uid);
7635
7636        final Message msg = mHandler.obtainMessage(INIT_COPY);
7637        msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags,
7638                installerPackageName, verificationParams, encryptionParams, user);
7639        mHandler.sendMessage(msg);
7640    }
7641
7642    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7643        Bundle extras = new Bundle(1);
7644        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7645
7646        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7647                packageName, extras, null, null, new int[] {userId});
7648        try {
7649            IActivityManager am = ActivityManagerNative.getDefault();
7650            final boolean isSystem =
7651                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7652            if (isSystem && am.isUserRunning(userId, false)) {
7653                // The just-installed/enabled app is bundled on the system, so presumed
7654                // to be able to run automatically without needing an explicit launch.
7655                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7656                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7657                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7658                        .setPackage(packageName);
7659                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7660                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7661            }
7662        } catch (RemoteException e) {
7663            // shouldn't happen
7664            Slog.w(TAG, "Unable to bootstrap installed package", e);
7665        }
7666    }
7667
7668    @Override
7669    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7670            int userId) {
7671        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7672        PackageSetting pkgSetting;
7673        final int uid = Binder.getCallingUid();
7674        if (UserHandle.getUserId(uid) != userId) {
7675            mContext.enforceCallingOrSelfPermission(
7676                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7677                    "setApplicationBlockedSetting for user " + userId);
7678        }
7679
7680        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7681            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7682            return false;
7683        }
7684
7685        long callingId = Binder.clearCallingIdentity();
7686        try {
7687            boolean sendAdded = false;
7688            boolean sendRemoved = false;
7689            // writer
7690            synchronized (mPackages) {
7691                pkgSetting = mSettings.mPackages.get(packageName);
7692                if (pkgSetting == null) {
7693                    return false;
7694                }
7695                if (pkgSetting.getBlocked(userId) != blocked) {
7696                    pkgSetting.setBlocked(blocked, userId);
7697                    mSettings.writePackageRestrictionsLPr(userId);
7698                    if (blocked) {
7699                        sendRemoved = true;
7700                    } else {
7701                        sendAdded = true;
7702                    }
7703                }
7704            }
7705            if (sendAdded) {
7706                sendPackageAddedForUser(packageName, pkgSetting, userId);
7707                return true;
7708            }
7709            if (sendRemoved) {
7710                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7711                        "blocking pkg");
7712                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7713            }
7714        } finally {
7715            Binder.restoreCallingIdentity(callingId);
7716        }
7717        return false;
7718    }
7719
7720    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7721            int userId) {
7722        final PackageRemovedInfo info = new PackageRemovedInfo();
7723        info.removedPackage = packageName;
7724        info.removedUsers = new int[] {userId};
7725        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7726        info.sendBroadcast(false, false, false);
7727    }
7728
7729    /**
7730     * Returns true if application is not found or there was an error. Otherwise it returns
7731     * the blocked state of the package for the given user.
7732     */
7733    @Override
7734    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7735        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7736        PackageSetting pkgSetting;
7737        final int uid = Binder.getCallingUid();
7738        if (UserHandle.getUserId(uid) != userId) {
7739            mContext.enforceCallingPermission(
7740                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7741                    "getApplicationBlocked for user " + userId);
7742        }
7743        long callingId = Binder.clearCallingIdentity();
7744        try {
7745            // writer
7746            synchronized (mPackages) {
7747                pkgSetting = mSettings.mPackages.get(packageName);
7748                if (pkgSetting == null) {
7749                    return true;
7750                }
7751                return pkgSetting.getBlocked(userId);
7752            }
7753        } finally {
7754            Binder.restoreCallingIdentity(callingId);
7755        }
7756    }
7757
7758    void installStage(String basePackageName, File stageDir, IPackageInstallObserver2 observer,
7759            int flags) {
7760        // TODO: install stage!
7761        try {
7762            observer.packageInstalled(basePackageName, null,
7763                    PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
7764        } catch (RemoteException ignored) {
7765        }
7766    }
7767
7768    /**
7769     * @hide
7770     */
7771    @Override
7772    public int installExistingPackageAsUser(String packageName, int userId) {
7773        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7774                null);
7775        PackageSetting pkgSetting;
7776        final int uid = Binder.getCallingUid();
7777        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7778        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7779            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7780        }
7781
7782        long callingId = Binder.clearCallingIdentity();
7783        try {
7784            boolean sendAdded = false;
7785            Bundle extras = new Bundle(1);
7786
7787            // writer
7788            synchronized (mPackages) {
7789                pkgSetting = mSettings.mPackages.get(packageName);
7790                if (pkgSetting == null) {
7791                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7792                }
7793                if (!pkgSetting.getInstalled(userId)) {
7794                    pkgSetting.setInstalled(true, userId);
7795                    pkgSetting.setBlocked(false, userId);
7796                    mSettings.writePackageRestrictionsLPr(userId);
7797                    sendAdded = true;
7798                }
7799            }
7800
7801            if (sendAdded) {
7802                sendPackageAddedForUser(packageName, pkgSetting, userId);
7803            }
7804        } finally {
7805            Binder.restoreCallingIdentity(callingId);
7806        }
7807
7808        return PackageManager.INSTALL_SUCCEEDED;
7809    }
7810
7811    boolean isUserRestricted(int userId, String restrictionKey) {
7812        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7813        if (restrictions.getBoolean(restrictionKey, false)) {
7814            Log.w(TAG, "User is restricted: " + restrictionKey);
7815            return true;
7816        }
7817        return false;
7818    }
7819
7820    @Override
7821    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7822        mContext.enforceCallingOrSelfPermission(
7823                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7824                "Only package verification agents can verify applications");
7825
7826        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7827        final PackageVerificationResponse response = new PackageVerificationResponse(
7828                verificationCode, Binder.getCallingUid());
7829        msg.arg1 = id;
7830        msg.obj = response;
7831        mHandler.sendMessage(msg);
7832    }
7833
7834    @Override
7835    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7836            long millisecondsToDelay) {
7837        mContext.enforceCallingOrSelfPermission(
7838                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7839                "Only package verification agents can extend verification timeouts");
7840
7841        final PackageVerificationState state = mPendingVerification.get(id);
7842        final PackageVerificationResponse response = new PackageVerificationResponse(
7843                verificationCodeAtTimeout, Binder.getCallingUid());
7844
7845        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7846            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7847        }
7848        if (millisecondsToDelay < 0) {
7849            millisecondsToDelay = 0;
7850        }
7851        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7852                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7853            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7854        }
7855
7856        if ((state != null) && !state.timeoutExtended()) {
7857            state.extendTimeout();
7858
7859            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7860            msg.arg1 = id;
7861            msg.obj = response;
7862            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7863        }
7864    }
7865
7866    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7867            int verificationCode, UserHandle user) {
7868        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7869        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7870        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7871        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7872        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7873
7874        mContext.sendBroadcastAsUser(intent, user,
7875                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7876    }
7877
7878    private ComponentName matchComponentForVerifier(String packageName,
7879            List<ResolveInfo> receivers) {
7880        ActivityInfo targetReceiver = null;
7881
7882        final int NR = receivers.size();
7883        for (int i = 0; i < NR; i++) {
7884            final ResolveInfo info = receivers.get(i);
7885            if (info.activityInfo == null) {
7886                continue;
7887            }
7888
7889            if (packageName.equals(info.activityInfo.packageName)) {
7890                targetReceiver = info.activityInfo;
7891                break;
7892            }
7893        }
7894
7895        if (targetReceiver == null) {
7896            return null;
7897        }
7898
7899        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7900    }
7901
7902    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7903            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7904        if (pkgInfo.verifiers.length == 0) {
7905            return null;
7906        }
7907
7908        final int N = pkgInfo.verifiers.length;
7909        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7910        for (int i = 0; i < N; i++) {
7911            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7912
7913            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7914                    receivers);
7915            if (comp == null) {
7916                continue;
7917            }
7918
7919            final int verifierUid = getUidForVerifier(verifierInfo);
7920            if (verifierUid == -1) {
7921                continue;
7922            }
7923
7924            if (DEBUG_VERIFY) {
7925                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
7926                        + " with the correct signature");
7927            }
7928            sufficientVerifiers.add(comp);
7929            verificationState.addSufficientVerifier(verifierUid);
7930        }
7931
7932        return sufficientVerifiers;
7933    }
7934
7935    private int getUidForVerifier(VerifierInfo verifierInfo) {
7936        synchronized (mPackages) {
7937            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
7938            if (pkg == null) {
7939                return -1;
7940            } else if (pkg.mSignatures.length != 1) {
7941                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7942                        + " has more than one signature; ignoring");
7943                return -1;
7944            }
7945
7946            /*
7947             * If the public key of the package's signature does not match
7948             * our expected public key, then this is a different package and
7949             * we should skip.
7950             */
7951
7952            final byte[] expectedPublicKey;
7953            try {
7954                final Signature verifierSig = pkg.mSignatures[0];
7955                final PublicKey publicKey = verifierSig.getPublicKey();
7956                expectedPublicKey = publicKey.getEncoded();
7957            } catch (CertificateException e) {
7958                return -1;
7959            }
7960
7961            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
7962
7963            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
7964                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7965                        + " does not have the expected public key; ignoring");
7966                return -1;
7967            }
7968
7969            return pkg.applicationInfo.uid;
7970        }
7971    }
7972
7973    @Override
7974    public void finishPackageInstall(int token) {
7975        enforceSystemOrRoot("Only the system is allowed to finish installs");
7976
7977        if (DEBUG_INSTALL) {
7978            Slog.v(TAG, "BM finishing package install for " + token);
7979        }
7980
7981        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7982        mHandler.sendMessage(msg);
7983    }
7984
7985    /**
7986     * Get the verification agent timeout.
7987     *
7988     * @return verification timeout in milliseconds
7989     */
7990    private long getVerificationTimeout() {
7991        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
7992                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
7993                DEFAULT_VERIFICATION_TIMEOUT);
7994    }
7995
7996    /**
7997     * Get the default verification agent response code.
7998     *
7999     * @return default verification response code
8000     */
8001    private int getDefaultVerificationResponse() {
8002        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8003                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8004                DEFAULT_VERIFICATION_RESPONSE);
8005    }
8006
8007    /**
8008     * Check whether or not package verification has been enabled.
8009     *
8010     * @return true if verification should be performed
8011     */
8012    private boolean isVerificationEnabled(int flags) {
8013        if (!DEFAULT_VERIFY_ENABLE) {
8014            return false;
8015        }
8016
8017        // Check if installing from ADB
8018        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8019            // Do not run verification in a test harness environment
8020            if (ActivityManager.isRunningInTestHarness()) {
8021                return false;
8022            }
8023            // Check if the developer does not want package verification for ADB installs
8024            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8025                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8026                return false;
8027            }
8028        }
8029
8030        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8031                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8032    }
8033
8034    /**
8035     * Get the "allow unknown sources" setting.
8036     *
8037     * @return the current "allow unknown sources" setting
8038     */
8039    private int getUnknownSourcesSettings() {
8040        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8041                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8042                -1);
8043    }
8044
8045    @Override
8046    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8047        final int uid = Binder.getCallingUid();
8048        // writer
8049        synchronized (mPackages) {
8050            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8051            if (targetPackageSetting == null) {
8052                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8053            }
8054
8055            PackageSetting installerPackageSetting;
8056            if (installerPackageName != null) {
8057                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8058                if (installerPackageSetting == null) {
8059                    throw new IllegalArgumentException("Unknown installer package: "
8060                            + installerPackageName);
8061                }
8062            } else {
8063                installerPackageSetting = null;
8064            }
8065
8066            Signature[] callerSignature;
8067            Object obj = mSettings.getUserIdLPr(uid);
8068            if (obj != null) {
8069                if (obj instanceof SharedUserSetting) {
8070                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8071                } else if (obj instanceof PackageSetting) {
8072                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8073                } else {
8074                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8075                }
8076            } else {
8077                throw new SecurityException("Unknown calling uid " + uid);
8078            }
8079
8080            // Verify: can't set installerPackageName to a package that is
8081            // not signed with the same cert as the caller.
8082            if (installerPackageSetting != null) {
8083                if (compareSignatures(callerSignature,
8084                        installerPackageSetting.signatures.mSignatures)
8085                        != PackageManager.SIGNATURE_MATCH) {
8086                    throw new SecurityException(
8087                            "Caller does not have same cert as new installer package "
8088                            + installerPackageName);
8089                }
8090            }
8091
8092            // Verify: if target already has an installer package, it must
8093            // be signed with the same cert as the caller.
8094            if (targetPackageSetting.installerPackageName != null) {
8095                PackageSetting setting = mSettings.mPackages.get(
8096                        targetPackageSetting.installerPackageName);
8097                // If the currently set package isn't valid, then it's always
8098                // okay to change it.
8099                if (setting != null) {
8100                    if (compareSignatures(callerSignature,
8101                            setting.signatures.mSignatures)
8102                            != PackageManager.SIGNATURE_MATCH) {
8103                        throw new SecurityException(
8104                                "Caller does not have same cert as old installer package "
8105                                + targetPackageSetting.installerPackageName);
8106                    }
8107                }
8108            }
8109
8110            // Okay!
8111            targetPackageSetting.installerPackageName = installerPackageName;
8112            scheduleWriteSettingsLocked();
8113        }
8114    }
8115
8116    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8117        // Queue up an async operation since the package installation may take a little while.
8118        mHandler.post(new Runnable() {
8119            public void run() {
8120                mHandler.removeCallbacks(this);
8121                 // Result object to be returned
8122                PackageInstalledInfo res = new PackageInstalledInfo();
8123                res.returnCode = currentStatus;
8124                res.uid = -1;
8125                res.pkg = null;
8126                res.removedInfo = new PackageRemovedInfo();
8127                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8128                    args.doPreInstall(res.returnCode);
8129                    synchronized (mInstallLock) {
8130                        installPackageLI(args, true, res);
8131                    }
8132                    args.doPostInstall(res.returnCode, res.uid);
8133                }
8134
8135                // A restore should be performed at this point if (a) the install
8136                // succeeded, (b) the operation is not an update, and (c) the new
8137                // package has a backupAgent defined.
8138                final boolean update = res.removedInfo.removedPackage != null;
8139                boolean doRestore = (!update
8140                        && res.pkg != null
8141                        && res.pkg.applicationInfo.backupAgentName != null);
8142
8143                // Set up the post-install work request bookkeeping.  This will be used
8144                // and cleaned up by the post-install event handling regardless of whether
8145                // there's a restore pass performed.  Token values are >= 1.
8146                int token;
8147                if (mNextInstallToken < 0) mNextInstallToken = 1;
8148                token = mNextInstallToken++;
8149
8150                PostInstallData data = new PostInstallData(args, res);
8151                mRunningInstalls.put(token, data);
8152                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8153
8154                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8155                    // Pass responsibility to the Backup Manager.  It will perform a
8156                    // restore if appropriate, then pass responsibility back to the
8157                    // Package Manager to run the post-install observer callbacks
8158                    // and broadcasts.
8159                    IBackupManager bm = IBackupManager.Stub.asInterface(
8160                            ServiceManager.getService(Context.BACKUP_SERVICE));
8161                    if (bm != null) {
8162                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8163                                + " to BM for possible restore");
8164                        try {
8165                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8166                        } catch (RemoteException e) {
8167                            // can't happen; the backup manager is local
8168                        } catch (Exception e) {
8169                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8170                            doRestore = false;
8171                        }
8172                    } else {
8173                        Slog.e(TAG, "Backup Manager not found!");
8174                        doRestore = false;
8175                    }
8176                }
8177
8178                if (!doRestore) {
8179                    // No restore possible, or the Backup Manager was mysteriously not
8180                    // available -- just fire the post-install work request directly.
8181                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8182                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8183                    mHandler.sendMessage(msg);
8184                }
8185            }
8186        });
8187    }
8188
8189    private abstract class HandlerParams {
8190        private static final int MAX_RETRIES = 4;
8191
8192        /**
8193         * Number of times startCopy() has been attempted and had a non-fatal
8194         * error.
8195         */
8196        private int mRetries = 0;
8197
8198        /** User handle for the user requesting the information or installation. */
8199        private final UserHandle mUser;
8200
8201        HandlerParams(UserHandle user) {
8202            mUser = user;
8203        }
8204
8205        UserHandle getUser() {
8206            return mUser;
8207        }
8208
8209        final boolean startCopy() {
8210            boolean res;
8211            try {
8212                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8213
8214                if (++mRetries > MAX_RETRIES) {
8215                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8216                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8217                    handleServiceError();
8218                    return false;
8219                } else {
8220                    handleStartCopy();
8221                    res = true;
8222                }
8223            } catch (RemoteException e) {
8224                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8225                mHandler.sendEmptyMessage(MCS_RECONNECT);
8226                res = false;
8227            }
8228            handleReturnCode();
8229            return res;
8230        }
8231
8232        final void serviceError() {
8233            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8234            handleServiceError();
8235            handleReturnCode();
8236        }
8237
8238        abstract void handleStartCopy() throws RemoteException;
8239        abstract void handleServiceError();
8240        abstract void handleReturnCode();
8241    }
8242
8243    class MeasureParams extends HandlerParams {
8244        private final PackageStats mStats;
8245        private boolean mSuccess;
8246
8247        private final IPackageStatsObserver mObserver;
8248
8249        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8250            super(new UserHandle(stats.userHandle));
8251            mObserver = observer;
8252            mStats = stats;
8253        }
8254
8255        @Override
8256        public String toString() {
8257            return "MeasureParams{"
8258                + Integer.toHexString(System.identityHashCode(this))
8259                + " " + mStats.packageName + "}";
8260        }
8261
8262        @Override
8263        void handleStartCopy() throws RemoteException {
8264            synchronized (mInstallLock) {
8265                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8266            }
8267
8268            if (mSuccess) {
8269                final boolean mounted;
8270                if (Environment.isExternalStorageEmulated()) {
8271                    mounted = true;
8272                } else {
8273                    final String status = Environment.getExternalStorageState();
8274                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8275                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8276                }
8277
8278                if (mounted) {
8279                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8280
8281                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8282                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8283
8284                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8285                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8286
8287                    // Always subtract cache size, since it's a subdirectory
8288                    mStats.externalDataSize -= mStats.externalCacheSize;
8289
8290                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8291                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8292
8293                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8294                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8295                }
8296            }
8297        }
8298
8299        @Override
8300        void handleReturnCode() {
8301            if (mObserver != null) {
8302                try {
8303                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8304                } catch (RemoteException e) {
8305                    Slog.i(TAG, "Observer no longer exists.");
8306                }
8307            }
8308        }
8309
8310        @Override
8311        void handleServiceError() {
8312            Slog.e(TAG, "Could not measure application " + mStats.packageName
8313                            + " external storage");
8314        }
8315    }
8316
8317    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8318            throws RemoteException {
8319        long result = 0;
8320        for (File path : paths) {
8321            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8322        }
8323        return result;
8324    }
8325
8326    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8327        for (File path : paths) {
8328            try {
8329                mcs.clearDirectory(path.getAbsolutePath());
8330            } catch (RemoteException e) {
8331            }
8332        }
8333    }
8334
8335    class InstallParams extends HandlerParams {
8336        final IPackageInstallObserver observer;
8337        final IPackageInstallObserver2 observer2;
8338        int flags;
8339
8340        private final Uri mPackageURI;
8341        final String installerPackageName;
8342        final VerificationParams verificationParams;
8343        private InstallArgs mArgs;
8344        private int mRet;
8345        private File mTempPackage;
8346        final ContainerEncryptionParams encryptionParams;
8347
8348        InstallParams(Uri packageURI,
8349                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8350                int flags, String installerPackageName, VerificationParams verificationParams,
8351                ContainerEncryptionParams encryptionParams, UserHandle user) {
8352            super(user);
8353            this.mPackageURI = packageURI;
8354            this.flags = flags;
8355            this.observer = observer;
8356            this.observer2 = observer2;
8357            this.installerPackageName = installerPackageName;
8358            this.verificationParams = verificationParams;
8359            this.encryptionParams = encryptionParams;
8360        }
8361
8362        @Override
8363        public String toString() {
8364            return "InstallParams{"
8365                + Integer.toHexString(System.identityHashCode(this))
8366                + " " + mPackageURI + "}";
8367        }
8368
8369        public ManifestDigest getManifestDigest() {
8370            if (verificationParams == null) {
8371                return null;
8372            }
8373            return verificationParams.getManifestDigest();
8374        }
8375
8376        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8377            String packageName = pkgLite.packageName;
8378            int installLocation = pkgLite.installLocation;
8379            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8380            // reader
8381            synchronized (mPackages) {
8382                PackageParser.Package pkg = mPackages.get(packageName);
8383                if (pkg != null) {
8384                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8385                        // Check for downgrading.
8386                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8387                            if (pkgLite.versionCode < pkg.mVersionCode) {
8388                                Slog.w(TAG, "Can't install update of " + packageName
8389                                        + " update version " + pkgLite.versionCode
8390                                        + " is older than installed version "
8391                                        + pkg.mVersionCode);
8392                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8393                            }
8394                        }
8395                        // Check for updated system application.
8396                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8397                            if (onSd) {
8398                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8399                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8400                            }
8401                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8402                        } else {
8403                            if (onSd) {
8404                                // Install flag overrides everything.
8405                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8406                            }
8407                            // If current upgrade specifies particular preference
8408                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8409                                // Application explicitly specified internal.
8410                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8411                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8412                                // App explictly prefers external. Let policy decide
8413                            } else {
8414                                // Prefer previous location
8415                                if (isExternal(pkg)) {
8416                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8417                                }
8418                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8419                            }
8420                        }
8421                    } else {
8422                        // Invalid install. Return error code
8423                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8424                    }
8425                }
8426            }
8427            // All the special cases have been taken care of.
8428            // Return result based on recommended install location.
8429            if (onSd) {
8430                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8431            }
8432            return pkgLite.recommendedInstallLocation;
8433        }
8434
8435        private long getMemoryLowThreshold() {
8436            final DeviceStorageMonitorInternal
8437                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8438            if (dsm == null) {
8439                return 0L;
8440            }
8441            return dsm.getMemoryLowThreshold();
8442        }
8443
8444        /*
8445         * Invoke remote method to get package information and install
8446         * location values. Override install location based on default
8447         * policy if needed and then create install arguments based
8448         * on the install location.
8449         */
8450        public void handleStartCopy() throws RemoteException {
8451            int ret = PackageManager.INSTALL_SUCCEEDED;
8452            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8453            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8454            PackageInfoLite pkgLite = null;
8455
8456            if (onInt && onSd) {
8457                // Check if both bits are set.
8458                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8459                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8460            } else {
8461                final long lowThreshold = getMemoryLowThreshold();
8462                if (lowThreshold == 0L) {
8463                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8464                }
8465
8466                try {
8467                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
8468                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8469
8470                    final File packageFile;
8471                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
8472                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
8473                        if (mTempPackage != null) {
8474                            ParcelFileDescriptor out;
8475                            try {
8476                                out = ParcelFileDescriptor.open(mTempPackage,
8477                                        ParcelFileDescriptor.MODE_READ_WRITE);
8478                            } catch (FileNotFoundException e) {
8479                                out = null;
8480                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
8481                            }
8482
8483                            // Make a temporary file for decryption.
8484                            ret = mContainerService
8485                                    .copyResource(mPackageURI, encryptionParams, out);
8486                            IoUtils.closeQuietly(out);
8487
8488                            packageFile = mTempPackage;
8489
8490                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
8491                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
8492                                            | FileUtils.S_IROTH,
8493                                    -1, -1);
8494                        } else {
8495                            packageFile = null;
8496                        }
8497                    } else {
8498                        packageFile = new File(mPackageURI.getPath());
8499                    }
8500
8501                    if (packageFile != null) {
8502                        // Remote call to find out default install location
8503                        final String packageFilePath = packageFile.getAbsolutePath();
8504                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
8505                                lowThreshold);
8506
8507                        /*
8508                         * If we have too little free space, try to free cache
8509                         * before giving up.
8510                         */
8511                        if (pkgLite.recommendedInstallLocation
8512                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8513                            final long size = mContainerService.calculateInstalledSize(
8514                                    packageFilePath, isForwardLocked());
8515                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8516                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
8517                                        flags, lowThreshold);
8518                            }
8519                            /*
8520                             * The cache free must have deleted the file we
8521                             * downloaded to install.
8522                             *
8523                             * TODO: fix the "freeCache" call to not delete
8524                             *       the file we care about.
8525                             */
8526                            if (pkgLite.recommendedInstallLocation
8527                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8528                                pkgLite.recommendedInstallLocation
8529                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8530                            }
8531                        }
8532                    }
8533                } finally {
8534                    mContext.revokeUriPermission(mPackageURI,
8535                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8536                }
8537            }
8538
8539            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8540                int loc = pkgLite.recommendedInstallLocation;
8541                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8542                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8543                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8544                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8545                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8546                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8547                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8548                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8549                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8550                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8551                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8552                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8553                } else {
8554                    // Override with defaults if needed.
8555                    loc = installLocationPolicy(pkgLite, flags);
8556                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8557                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8558                    } else if (!onSd && !onInt) {
8559                        // Override install location with flags
8560                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8561                            // Set the flag to install on external media.
8562                            flags |= PackageManager.INSTALL_EXTERNAL;
8563                            flags &= ~PackageManager.INSTALL_INTERNAL;
8564                        } else {
8565                            // Make sure the flag for installing on external
8566                            // media is unset
8567                            flags |= PackageManager.INSTALL_INTERNAL;
8568                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8569                        }
8570                    }
8571                }
8572            }
8573
8574            final InstallArgs args = createInstallArgs(this);
8575            mArgs = args;
8576
8577            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8578                 /*
8579                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8580                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8581                 */
8582                int userIdentifier = getUser().getIdentifier();
8583                if (userIdentifier == UserHandle.USER_ALL
8584                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8585                    userIdentifier = UserHandle.USER_OWNER;
8586                }
8587
8588                /*
8589                 * Determine if we have any installed package verifiers. If we
8590                 * do, then we'll defer to them to verify the packages.
8591                 */
8592                final int requiredUid = mRequiredVerifierPackage == null ? -1
8593                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8594                if (requiredUid != -1 && isVerificationEnabled(flags)) {
8595                    final Intent verification = new Intent(
8596                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8597                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
8598                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8599
8600                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8601                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8602                            0 /* TODO: Which userId? */);
8603
8604                    if (DEBUG_VERIFY) {
8605                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8606                                + verification.toString() + " with " + pkgLite.verifiers.length
8607                                + " optional verifiers");
8608                    }
8609
8610                    final int verificationId = mPendingVerificationToken++;
8611
8612                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8613
8614                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8615                            installerPackageName);
8616
8617                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8618
8619                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8620                            pkgLite.packageName);
8621
8622                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8623                            pkgLite.versionCode);
8624
8625                    if (verificationParams != null) {
8626                        if (verificationParams.getVerificationURI() != null) {
8627                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8628                                 verificationParams.getVerificationURI());
8629                        }
8630                        if (verificationParams.getOriginatingURI() != null) {
8631                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8632                                  verificationParams.getOriginatingURI());
8633                        }
8634                        if (verificationParams.getReferrer() != null) {
8635                            verification.putExtra(Intent.EXTRA_REFERRER,
8636                                  verificationParams.getReferrer());
8637                        }
8638                        if (verificationParams.getOriginatingUid() >= 0) {
8639                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8640                                  verificationParams.getOriginatingUid());
8641                        }
8642                        if (verificationParams.getInstallerUid() >= 0) {
8643                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8644                                  verificationParams.getInstallerUid());
8645                        }
8646                    }
8647
8648                    final PackageVerificationState verificationState = new PackageVerificationState(
8649                            requiredUid, args);
8650
8651                    mPendingVerification.append(verificationId, verificationState);
8652
8653                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8654                            receivers, verificationState);
8655
8656                    /*
8657                     * If any sufficient verifiers were listed in the package
8658                     * manifest, attempt to ask them.
8659                     */
8660                    if (sufficientVerifiers != null) {
8661                        final int N = sufficientVerifiers.size();
8662                        if (N == 0) {
8663                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8664                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8665                        } else {
8666                            for (int i = 0; i < N; i++) {
8667                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8668
8669                                final Intent sufficientIntent = new Intent(verification);
8670                                sufficientIntent.setComponent(verifierComponent);
8671
8672                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8673                            }
8674                        }
8675                    }
8676
8677                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8678                            mRequiredVerifierPackage, receivers);
8679                    if (ret == PackageManager.INSTALL_SUCCEEDED
8680                            && mRequiredVerifierPackage != null) {
8681                        /*
8682                         * Send the intent to the required verification agent,
8683                         * but only start the verification timeout after the
8684                         * target BroadcastReceivers have run.
8685                         */
8686                        verification.setComponent(requiredVerifierComponent);
8687                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8688                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8689                                new BroadcastReceiver() {
8690                                    @Override
8691                                    public void onReceive(Context context, Intent intent) {
8692                                        final Message msg = mHandler
8693                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8694                                        msg.arg1 = verificationId;
8695                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8696                                    }
8697                                }, null, 0, null, null);
8698
8699                        /*
8700                         * We don't want the copy to proceed until verification
8701                         * succeeds, so null out this field.
8702                         */
8703                        mArgs = null;
8704                    }
8705                } else {
8706                    /*
8707                     * No package verification is enabled, so immediately start
8708                     * the remote call to initiate copy using temporary file.
8709                     */
8710                    ret = args.copyApk(mContainerService, true);
8711                }
8712            }
8713
8714            mRet = ret;
8715        }
8716
8717        @Override
8718        void handleReturnCode() {
8719            // If mArgs is null, then MCS couldn't be reached. When it
8720            // reconnects, it will try again to install. At that point, this
8721            // will succeed.
8722            if (mArgs != null) {
8723                processPendingInstall(mArgs, mRet);
8724
8725                if (mTempPackage != null) {
8726                    if (!mTempPackage.delete()) {
8727                        Slog.w(TAG, "Couldn't delete temporary file: " +
8728                                mTempPackage.getAbsolutePath());
8729                    }
8730                }
8731            }
8732        }
8733
8734        @Override
8735        void handleServiceError() {
8736            mArgs = createInstallArgs(this);
8737            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8738        }
8739
8740        public boolean isForwardLocked() {
8741            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8742        }
8743
8744        public Uri getPackageUri() {
8745            if (mTempPackage != null) {
8746                return Uri.fromFile(mTempPackage);
8747            } else {
8748                return mPackageURI;
8749            }
8750        }
8751    }
8752
8753    /*
8754     * Utility class used in movePackage api.
8755     * srcArgs and targetArgs are not set for invalid flags and make
8756     * sure to do null checks when invoking methods on them.
8757     * We probably want to return ErrorPrams for both failed installs
8758     * and moves.
8759     */
8760    class MoveParams extends HandlerParams {
8761        final IPackageMoveObserver observer;
8762        final int flags;
8763        final String packageName;
8764        final InstallArgs srcArgs;
8765        final InstallArgs targetArgs;
8766        int uid;
8767        int mRet;
8768
8769        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8770                String packageName, String dataDir, String instructionSet,
8771                int uid, UserHandle user) {
8772            super(user);
8773            this.srcArgs = srcArgs;
8774            this.observer = observer;
8775            this.flags = flags;
8776            this.packageName = packageName;
8777            this.uid = uid;
8778            if (srcArgs != null) {
8779                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
8780                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet);
8781            } else {
8782                targetArgs = null;
8783            }
8784        }
8785
8786        @Override
8787        public String toString() {
8788            return "MoveParams{"
8789                + Integer.toHexString(System.identityHashCode(this))
8790                + " " + packageName + "}";
8791        }
8792
8793        public void handleStartCopy() throws RemoteException {
8794            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8795            // Check for storage space on target medium
8796            if (!targetArgs.checkFreeStorage(mContainerService)) {
8797                Log.w(TAG, "Insufficient storage to install");
8798                return;
8799            }
8800
8801            mRet = srcArgs.doPreCopy();
8802            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8803                return;
8804            }
8805
8806            mRet = targetArgs.copyApk(mContainerService, false);
8807            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8808                srcArgs.doPostCopy(uid);
8809                return;
8810            }
8811
8812            mRet = srcArgs.doPostCopy(uid);
8813            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8814                return;
8815            }
8816
8817            mRet = targetArgs.doPreInstall(mRet);
8818            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8819                return;
8820            }
8821
8822            if (DEBUG_SD_INSTALL) {
8823                StringBuilder builder = new StringBuilder();
8824                if (srcArgs != null) {
8825                    builder.append("src: ");
8826                    builder.append(srcArgs.getCodePath());
8827                }
8828                if (targetArgs != null) {
8829                    builder.append(" target : ");
8830                    builder.append(targetArgs.getCodePath());
8831                }
8832                Log.i(TAG, builder.toString());
8833            }
8834        }
8835
8836        @Override
8837        void handleReturnCode() {
8838            targetArgs.doPostInstall(mRet, uid);
8839            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8840            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8841                currentStatus = PackageManager.MOVE_SUCCEEDED;
8842            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8843                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8844            }
8845            processPendingMove(this, currentStatus);
8846        }
8847
8848        @Override
8849        void handleServiceError() {
8850            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8851        }
8852    }
8853
8854    /**
8855     * Used during creation of InstallArgs
8856     *
8857     * @param flags package installation flags
8858     * @return true if should be installed on external storage
8859     */
8860    private static boolean installOnSd(int flags) {
8861        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8862            return false;
8863        }
8864        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8865            return true;
8866        }
8867        return false;
8868    }
8869
8870    /**
8871     * Used during creation of InstallArgs
8872     *
8873     * @param flags package installation flags
8874     * @return true if should be installed as forward locked
8875     */
8876    private static boolean installForwardLocked(int flags) {
8877        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8878    }
8879
8880    private InstallArgs createInstallArgs(InstallParams params) {
8881        if (installOnSd(params.flags) || params.isForwardLocked()) {
8882            return new AsecInstallArgs(params);
8883        } else {
8884            return new FileInstallArgs(params);
8885        }
8886    }
8887
8888    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
8889            String nativeLibraryPath, String instructionSet) {
8890        final boolean isInAsec;
8891        if (installOnSd(flags)) {
8892            /* Apps on SD card are always in ASEC containers. */
8893            isInAsec = true;
8894        } else if (installForwardLocked(flags)
8895                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8896            /*
8897             * Forward-locked apps are only in ASEC containers if they're the
8898             * new style
8899             */
8900            isInAsec = true;
8901        } else {
8902            isInAsec = false;
8903        }
8904
8905        if (isInAsec) {
8906            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8907                    instructionSet, installOnSd(flags), installForwardLocked(flags));
8908        } else {
8909            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8910                    instructionSet);
8911        }
8912    }
8913
8914    // Used by package mover
8915    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir,
8916            String instructionSet) {
8917        if (installOnSd(flags) || installForwardLocked(flags)) {
8918            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
8919                    + AsecInstallArgs.RES_FILE_NAME);
8920            return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags),
8921                    installForwardLocked(flags));
8922        } else {
8923            return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet);
8924        }
8925    }
8926
8927    static abstract class InstallArgs {
8928        final IPackageInstallObserver observer;
8929        final IPackageInstallObserver2 observer2;
8930        // Always refers to PackageManager flags only
8931        final int flags;
8932        final Uri packageURI;
8933        final String installerPackageName;
8934        final ManifestDigest manifestDigest;
8935        final UserHandle user;
8936        final String instructionSet;
8937
8938        InstallArgs(Uri packageURI,
8939                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8940                int flags, String installerPackageName, ManifestDigest manifestDigest,
8941                UserHandle user, String instructionSet) {
8942            this.packageURI = packageURI;
8943            this.flags = flags;
8944            this.observer = observer;
8945            this.observer2 = observer2;
8946            this.installerPackageName = installerPackageName;
8947            this.manifestDigest = manifestDigest;
8948            this.user = user;
8949            this.instructionSet = instructionSet;
8950        }
8951
8952        abstract void createCopyFile();
8953        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8954        abstract int doPreInstall(int status);
8955        abstract boolean doRename(int status, String pkgName, String oldCodePath);
8956
8957        abstract int doPostInstall(int status, int uid);
8958        abstract String getCodePath();
8959        abstract String getResourcePath();
8960        abstract String getNativeLibraryPath();
8961        // Need installer lock especially for dex file removal.
8962        abstract void cleanUpResourcesLI();
8963        abstract boolean doPostDeleteLI(boolean delete);
8964        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
8965
8966        /**
8967         * Called before the source arguments are copied. This is used mostly
8968         * for MoveParams when it needs to read the source file to put it in the
8969         * destination.
8970         */
8971        int doPreCopy() {
8972            return PackageManager.INSTALL_SUCCEEDED;
8973        }
8974
8975        /**
8976         * Called after the source arguments are copied. This is used mostly for
8977         * MoveParams when it needs to read the source file to put it in the
8978         * destination.
8979         *
8980         * @return
8981         */
8982        int doPostCopy(int uid) {
8983            return PackageManager.INSTALL_SUCCEEDED;
8984        }
8985
8986        protected boolean isFwdLocked() {
8987            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8988        }
8989
8990        UserHandle getUser() {
8991            return user;
8992        }
8993    }
8994
8995    class FileInstallArgs extends InstallArgs {
8996        File installDir;
8997        String codeFileName;
8998        String resourceFileName;
8999        String libraryPath;
9000        boolean created = false;
9001
9002        FileInstallArgs(InstallParams params) {
9003            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9004                    params.installerPackageName, params.getManifestDigest(),
9005                    params.getUser(), null /* instruction set */);
9006        }
9007
9008        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9009                String instructionSet) {
9010            super(null, null, null, 0, null, null, null, instructionSet);
9011            File codeFile = new File(fullCodePath);
9012            installDir = codeFile.getParentFile();
9013            codeFileName = fullCodePath;
9014            resourceFileName = fullResourcePath;
9015            libraryPath = nativeLibraryPath;
9016        }
9017
9018        FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) {
9019            super(packageURI, null, null, 0, null, null, null, instructionSet);
9020            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9021            String apkName = getNextCodePath(null, pkgName, ".apk");
9022            codeFileName = new File(installDir, apkName + ".apk").getPath();
9023            resourceFileName = getResourcePathFromCodePath();
9024            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
9025        }
9026
9027        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9028            final long lowThreshold;
9029
9030            final DeviceStorageMonitorInternal
9031                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9032            if (dsm == null) {
9033                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9034                lowThreshold = 0L;
9035            } else {
9036                if (dsm.isMemoryLow()) {
9037                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9038                    return false;
9039                }
9040
9041                lowThreshold = dsm.getMemoryLowThreshold();
9042            }
9043
9044            try {
9045                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9046                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9047                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
9048            } finally {
9049                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9050            }
9051        }
9052
9053        String getCodePath() {
9054            return codeFileName;
9055        }
9056
9057        void createCopyFile() {
9058            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9059            codeFileName = createTempPackageFile(installDir).getPath();
9060            resourceFileName = getResourcePathFromCodePath();
9061            libraryPath = getLibraryPathFromCodePath();
9062            created = true;
9063        }
9064
9065        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9066            if (temp) {
9067                // Generate temp file name
9068                createCopyFile();
9069            }
9070            // Get a ParcelFileDescriptor to write to the output file
9071            File codeFile = new File(codeFileName);
9072            if (!created) {
9073                try {
9074                    codeFile.createNewFile();
9075                    // Set permissions
9076                    if (!setPermissions()) {
9077                        // Failed setting permissions.
9078                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9079                    }
9080                } catch (IOException e) {
9081                   Slog.w(TAG, "Failed to create file " + codeFile);
9082                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9083                }
9084            }
9085            ParcelFileDescriptor out = null;
9086            try {
9087                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
9088            } catch (FileNotFoundException e) {
9089                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
9090                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9091            }
9092            // Copy the resource now
9093            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9094            try {
9095                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9096                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9097                ret = imcs.copyResource(packageURI, null, out);
9098            } finally {
9099                IoUtils.closeQuietly(out);
9100                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9101            }
9102
9103            if (isFwdLocked()) {
9104                final File destResourceFile = new File(getResourcePath());
9105
9106                // Copy the public files
9107                try {
9108                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
9109                } catch (IOException e) {
9110                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
9111                            + " forward-locked app.");
9112                    destResourceFile.delete();
9113                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9114                }
9115            }
9116
9117            final File nativeLibraryFile = new File(getNativeLibraryPath());
9118            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
9119            if (nativeLibraryFile.exists()) {
9120                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9121                nativeLibraryFile.delete();
9122            }
9123            try {
9124                int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile);
9125                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9126                    return copyRet;
9127                }
9128            } catch (IOException e) {
9129                Slog.e(TAG, "Copying native libraries failed", e);
9130                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9131            }
9132
9133            return ret;
9134        }
9135
9136        int doPreInstall(int status) {
9137            if (status != PackageManager.INSTALL_SUCCEEDED) {
9138                cleanUp();
9139            }
9140            return status;
9141        }
9142
9143        boolean doRename(int status, final String pkgName, String oldCodePath) {
9144            if (status != PackageManager.INSTALL_SUCCEEDED) {
9145                cleanUp();
9146                return false;
9147            } else {
9148                final File oldCodeFile = new File(getCodePath());
9149                final File oldResourceFile = new File(getResourcePath());
9150                final File oldLibraryFile = new File(getNativeLibraryPath());
9151
9152                // Rename APK file based on packageName
9153                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
9154                final File newCodeFile = new File(installDir, apkName + ".apk");
9155                if (!oldCodeFile.renameTo(newCodeFile)) {
9156                    return false;
9157                }
9158                codeFileName = newCodeFile.getPath();
9159
9160                // Rename public resource file if it's forward-locked.
9161                final File newResFile = new File(getResourcePathFromCodePath());
9162                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
9163                    return false;
9164                }
9165                resourceFileName = newResFile.getPath();
9166
9167                // Rename library path
9168                final File newLibraryFile = new File(getLibraryPathFromCodePath());
9169                if (newLibraryFile.exists()) {
9170                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
9171                    newLibraryFile.delete();
9172                }
9173                if (!oldLibraryFile.renameTo(newLibraryFile)) {
9174                    Slog.e(TAG, "Cannot rename native library directory "
9175                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
9176                    return false;
9177                }
9178                libraryPath = newLibraryFile.getPath();
9179
9180                // Attempt to set permissions
9181                if (!setPermissions()) {
9182                    return false;
9183                }
9184
9185                if (!SELinux.restorecon(newCodeFile)) {
9186                    return false;
9187                }
9188
9189                return true;
9190            }
9191        }
9192
9193        int doPostInstall(int status, int uid) {
9194            if (status != PackageManager.INSTALL_SUCCEEDED) {
9195                cleanUp();
9196            }
9197            return status;
9198        }
9199
9200        String getResourcePath() {
9201            return resourceFileName;
9202        }
9203
9204        private String getResourcePathFromCodePath() {
9205            final String codePath = getCodePath();
9206            if (isFwdLocked()) {
9207                final StringBuilder sb = new StringBuilder();
9208
9209                sb.append(mAppInstallDir.getPath());
9210                sb.append('/');
9211                sb.append(getApkName(codePath));
9212                sb.append(".zip");
9213
9214                /*
9215                 * If our APK is a temporary file, mark the resource as a
9216                 * temporary file as well so it can be cleaned up after
9217                 * catastrophic failure.
9218                 */
9219                if (codePath.endsWith(".tmp")) {
9220                    sb.append(".tmp");
9221                }
9222
9223                return sb.toString();
9224            } else {
9225                return codePath;
9226            }
9227        }
9228
9229        private String getLibraryPathFromCodePath() {
9230            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
9231        }
9232
9233        @Override
9234        String getNativeLibraryPath() {
9235            if (libraryPath == null) {
9236                libraryPath = getLibraryPathFromCodePath();
9237            }
9238            return libraryPath;
9239        }
9240
9241        private boolean cleanUp() {
9242            boolean ret = true;
9243            String sourceDir = getCodePath();
9244            String publicSourceDir = getResourcePath();
9245            if (sourceDir != null) {
9246                File sourceFile = new File(sourceDir);
9247                if (!sourceFile.exists()) {
9248                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
9249                    ret = false;
9250                }
9251                // Delete application's code and resources
9252                sourceFile.delete();
9253            }
9254            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
9255                final File publicSourceFile = new File(publicSourceDir);
9256                if (!publicSourceFile.exists()) {
9257                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
9258                }
9259                if (publicSourceFile.exists()) {
9260                    publicSourceFile.delete();
9261                }
9262            }
9263
9264            if (libraryPath != null) {
9265                File nativeLibraryFile = new File(libraryPath);
9266                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9267                if (!nativeLibraryFile.delete()) {
9268                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
9269                }
9270            }
9271
9272            return ret;
9273        }
9274
9275        void cleanUpResourcesLI() {
9276            String sourceDir = getCodePath();
9277            if (cleanUp()) {
9278                if (instructionSet == null) {
9279                    throw new IllegalStateException("instructionSet == null");
9280                }
9281                int retCode = mInstaller.rmdex(sourceDir, instructionSet);
9282                if (retCode < 0) {
9283                    Slog.w(TAG, "Couldn't remove dex file for package: "
9284                            +  " at location "
9285                            + sourceDir + ", retcode=" + retCode);
9286                    // we don't consider this to be a failure of the core package deletion
9287                }
9288            }
9289        }
9290
9291        private boolean setPermissions() {
9292            // TODO Do this in a more elegant way later on. for now just a hack
9293            if (!isFwdLocked()) {
9294                final int filePermissions =
9295                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
9296                    |FileUtils.S_IROTH;
9297                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
9298                if (retCode != 0) {
9299                    Slog.e(TAG, "Couldn't set new package file permissions for " +
9300                            getCodePath()
9301                            + ". The return code was: " + retCode);
9302                    // TODO Define new internal error
9303                    return false;
9304                }
9305                return true;
9306            }
9307            return true;
9308        }
9309
9310        boolean doPostDeleteLI(boolean delete) {
9311            // XXX err, shouldn't we respect the delete flag?
9312            cleanUpResourcesLI();
9313            return true;
9314        }
9315    }
9316
9317    private boolean isAsecExternal(String cid) {
9318        final String asecPath = PackageHelper.getSdFilesystem(cid);
9319        return !asecPath.startsWith(mAsecInternalPath);
9320    }
9321
9322    /**
9323     * Extract the MountService "container ID" from the full code path of an
9324     * .apk.
9325     */
9326    static String cidFromCodePath(String fullCodePath) {
9327        int eidx = fullCodePath.lastIndexOf("/");
9328        String subStr1 = fullCodePath.substring(0, eidx);
9329        int sidx = subStr1.lastIndexOf("/");
9330        return subStr1.substring(sidx+1, eidx);
9331    }
9332
9333    class AsecInstallArgs extends InstallArgs {
9334        static final String RES_FILE_NAME = "pkg.apk";
9335        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9336
9337        String cid;
9338        String packagePath;
9339        String resourcePath;
9340        String libraryPath;
9341
9342        AsecInstallArgs(InstallParams params) {
9343            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9344                    params.installerPackageName, params.getManifestDigest(),
9345                    params.getUser(), null /* instruction set */);
9346        }
9347
9348        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9349                String instructionSet, boolean isExternal, boolean isForwardLocked) {
9350            super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9351                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9352                    null, null, null, instructionSet);
9353            // Extract cid from fullCodePath
9354            int eidx = fullCodePath.lastIndexOf("/");
9355            String subStr1 = fullCodePath.substring(0, eidx);
9356            int sidx = subStr1.lastIndexOf("/");
9357            cid = subStr1.substring(sidx+1, eidx);
9358            setCachePath(subStr1);
9359        }
9360
9361        AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) {
9362            super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
9363                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9364                    null, null, null, instructionSet);
9365            this.cid = cid;
9366            setCachePath(PackageHelper.getSdDir(cid));
9367        }
9368
9369        AsecInstallArgs(Uri packageURI, String cid, String instructionSet,
9370                boolean isExternal, boolean isForwardLocked) {
9371            super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9372                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9373                    null, null, null, instructionSet);
9374            this.cid = cid;
9375        }
9376
9377        void createCopyFile() {
9378            cid = getTempContainerId();
9379        }
9380
9381        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9382            try {
9383                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9384                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9385                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
9386            } finally {
9387                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9388            }
9389        }
9390
9391        private final boolean isExternal() {
9392            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9393        }
9394
9395        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9396            if (temp) {
9397                createCopyFile();
9398            } else {
9399                /*
9400                 * Pre-emptively destroy the container since it's destroyed if
9401                 * copying fails due to it existing anyway.
9402                 */
9403                PackageHelper.destroySdDir(cid);
9404            }
9405
9406            final String newCachePath;
9407            try {
9408                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9409                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9410                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
9411                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
9412            } finally {
9413                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9414            }
9415
9416            if (newCachePath != null) {
9417                setCachePath(newCachePath);
9418                return PackageManager.INSTALL_SUCCEEDED;
9419            } else {
9420                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9421            }
9422        }
9423
9424        @Override
9425        String getCodePath() {
9426            return packagePath;
9427        }
9428
9429        @Override
9430        String getResourcePath() {
9431            return resourcePath;
9432        }
9433
9434        @Override
9435        String getNativeLibraryPath() {
9436            return libraryPath;
9437        }
9438
9439        int doPreInstall(int status) {
9440            if (status != PackageManager.INSTALL_SUCCEEDED) {
9441                // Destroy container
9442                PackageHelper.destroySdDir(cid);
9443            } else {
9444                boolean mounted = PackageHelper.isContainerMounted(cid);
9445                if (!mounted) {
9446                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9447                            Process.SYSTEM_UID);
9448                    if (newCachePath != null) {
9449                        setCachePath(newCachePath);
9450                    } else {
9451                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9452                    }
9453                }
9454            }
9455            return status;
9456        }
9457
9458        boolean doRename(int status, final String pkgName,
9459                String oldCodePath) {
9460            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
9461            String newCachePath = null;
9462            if (PackageHelper.isContainerMounted(cid)) {
9463                // Unmount the container
9464                if (!PackageHelper.unMountSdDir(cid)) {
9465                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9466                    return false;
9467                }
9468            }
9469            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9470                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9471                        " which might be stale. Will try to clean up.");
9472                // Clean up the stale container and proceed to recreate.
9473                if (!PackageHelper.destroySdDir(newCacheId)) {
9474                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9475                    return false;
9476                }
9477                // Successfully cleaned up stale container. Try to rename again.
9478                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9479                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9480                            + " inspite of cleaning it up.");
9481                    return false;
9482                }
9483            }
9484            if (!PackageHelper.isContainerMounted(newCacheId)) {
9485                Slog.w(TAG, "Mounting container " + newCacheId);
9486                newCachePath = PackageHelper.mountSdDir(newCacheId,
9487                        getEncryptKey(), Process.SYSTEM_UID);
9488            } else {
9489                newCachePath = PackageHelper.getSdDir(newCacheId);
9490            }
9491            if (newCachePath == null) {
9492                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9493                return false;
9494            }
9495            Log.i(TAG, "Succesfully renamed " + cid +
9496                    " to " + newCacheId +
9497                    " at new path: " + newCachePath);
9498            cid = newCacheId;
9499            setCachePath(newCachePath);
9500            return true;
9501        }
9502
9503        private void setCachePath(String newCachePath) {
9504            File cachePath = new File(newCachePath);
9505            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
9506            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9507
9508            if (isFwdLocked()) {
9509                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9510            } else {
9511                resourcePath = packagePath;
9512            }
9513        }
9514
9515        int doPostInstall(int status, int uid) {
9516            if (status != PackageManager.INSTALL_SUCCEEDED) {
9517                cleanUp();
9518            } else {
9519                final int groupOwner;
9520                final String protectedFile;
9521                if (isFwdLocked()) {
9522                    groupOwner = UserHandle.getSharedAppGid(uid);
9523                    protectedFile = RES_FILE_NAME;
9524                } else {
9525                    groupOwner = -1;
9526                    protectedFile = null;
9527                }
9528
9529                if (uid < Process.FIRST_APPLICATION_UID
9530                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9531                    Slog.e(TAG, "Failed to finalize " + cid);
9532                    PackageHelper.destroySdDir(cid);
9533                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9534                }
9535
9536                boolean mounted = PackageHelper.isContainerMounted(cid);
9537                if (!mounted) {
9538                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9539                }
9540            }
9541            return status;
9542        }
9543
9544        private void cleanUp() {
9545            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9546
9547            // Destroy secure container
9548            PackageHelper.destroySdDir(cid);
9549        }
9550
9551        void cleanUpResourcesLI() {
9552            String sourceFile = getCodePath();
9553            // Remove dex file
9554            if (instructionSet == null) {
9555                throw new IllegalStateException("instructionSet == null");
9556            }
9557            int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9558            if (retCode < 0) {
9559                Slog.w(TAG, "Couldn't remove dex file for package: "
9560                        + " at location "
9561                        + sourceFile.toString() + ", retcode=" + retCode);
9562                // we don't consider this to be a failure of the core package deletion
9563            }
9564            cleanUp();
9565        }
9566
9567        boolean matchContainer(String app) {
9568            if (cid.startsWith(app)) {
9569                return true;
9570            }
9571            return false;
9572        }
9573
9574        String getPackageName() {
9575            return getAsecPackageName(cid);
9576        }
9577
9578        boolean doPostDeleteLI(boolean delete) {
9579            boolean ret = false;
9580            boolean mounted = PackageHelper.isContainerMounted(cid);
9581            if (mounted) {
9582                // Unmount first
9583                ret = PackageHelper.unMountSdDir(cid);
9584            }
9585            if (ret && delete) {
9586                cleanUpResourcesLI();
9587            }
9588            return ret;
9589        }
9590
9591        @Override
9592        int doPreCopy() {
9593            if (isFwdLocked()) {
9594                if (!PackageHelper.fixSdPermissions(cid,
9595                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9596                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9597                }
9598            }
9599
9600            return PackageManager.INSTALL_SUCCEEDED;
9601        }
9602
9603        @Override
9604        int doPostCopy(int uid) {
9605            if (isFwdLocked()) {
9606                if (uid < Process.FIRST_APPLICATION_UID
9607                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9608                                RES_FILE_NAME)) {
9609                    Slog.e(TAG, "Failed to finalize " + cid);
9610                    PackageHelper.destroySdDir(cid);
9611                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9612                }
9613            }
9614
9615            return PackageManager.INSTALL_SUCCEEDED;
9616        }
9617    };
9618
9619    static String getAsecPackageName(String packageCid) {
9620        int idx = packageCid.lastIndexOf("-");
9621        if (idx == -1) {
9622            return packageCid;
9623        }
9624        return packageCid.substring(0, idx);
9625    }
9626
9627    // Utility method used to create code paths based on package name and available index.
9628    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9629        String idxStr = "";
9630        int idx = 1;
9631        // Fall back to default value of idx=1 if prefix is not
9632        // part of oldCodePath
9633        if (oldCodePath != null) {
9634            String subStr = oldCodePath;
9635            // Drop the suffix right away
9636            if (subStr.endsWith(suffix)) {
9637                subStr = subStr.substring(0, subStr.length() - suffix.length());
9638            }
9639            // If oldCodePath already contains prefix find out the
9640            // ending index to either increment or decrement.
9641            int sidx = subStr.lastIndexOf(prefix);
9642            if (sidx != -1) {
9643                subStr = subStr.substring(sidx + prefix.length());
9644                if (subStr != null) {
9645                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9646                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9647                    }
9648                    try {
9649                        idx = Integer.parseInt(subStr);
9650                        if (idx <= 1) {
9651                            idx++;
9652                        } else {
9653                            idx--;
9654                        }
9655                    } catch(NumberFormatException e) {
9656                    }
9657                }
9658            }
9659        }
9660        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9661        return prefix + idxStr;
9662    }
9663
9664    // Utility method used to ignore ADD/REMOVE events
9665    // by directory observer.
9666    private static boolean ignoreCodePath(String fullPathStr) {
9667        String apkName = getApkName(fullPathStr);
9668        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9669        if (idx != -1 && ((idx+1) < apkName.length())) {
9670            // Make sure the package ends with a numeral
9671            String version = apkName.substring(idx+1);
9672            try {
9673                Integer.parseInt(version);
9674                return true;
9675            } catch (NumberFormatException e) {}
9676        }
9677        return false;
9678    }
9679
9680    // Utility method that returns the relative package path with respect
9681    // to the installation directory. Like say for /data/data/com.test-1.apk
9682    // string com.test-1 is returned.
9683    static String getApkName(String codePath) {
9684        if (codePath == null) {
9685            return null;
9686        }
9687        int sidx = codePath.lastIndexOf("/");
9688        int eidx = codePath.lastIndexOf(".");
9689        if (eidx == -1) {
9690            eidx = codePath.length();
9691        } else if (eidx == 0) {
9692            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
9693            return null;
9694        }
9695        return codePath.substring(sidx+1, eidx);
9696    }
9697
9698    class PackageInstalledInfo {
9699        String name;
9700        int uid;
9701        // The set of users that originally had this package installed.
9702        int[] origUsers;
9703        // The set of users that now have this package installed.
9704        int[] newUsers;
9705        PackageParser.Package pkg;
9706        int returnCode;
9707        PackageRemovedInfo removedInfo;
9708
9709        // In some error cases we want to convey more info back to the observer
9710        String origPackage;
9711        String origPermission;
9712    }
9713
9714    /*
9715     * Install a non-existing package.
9716     */
9717    private void installNewPackageLI(PackageParser.Package pkg,
9718            int parseFlags, int scanMode, UserHandle user,
9719            String installerPackageName, PackageInstalledInfo res) {
9720        // Remember this for later, in case we need to rollback this install
9721        String pkgName = pkg.packageName;
9722
9723        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9724        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9725        synchronized(mPackages) {
9726            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9727                // A package with the same name is already installed, though
9728                // it has been renamed to an older name.  The package we
9729                // are trying to install should be installed as an update to
9730                // the existing one, but that has not been requested, so bail.
9731                Slog.w(TAG, "Attempt to re-install " + pkgName
9732                        + " without first uninstalling package running as "
9733                        + mSettings.mRenamedPackages.get(pkgName));
9734                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9735                return;
9736            }
9737            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
9738                // Don't allow installation over an existing package with the same name.
9739                Slog.w(TAG, "Attempt to re-install " + pkgName
9740                        + " without first uninstalling.");
9741                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9742                return;
9743            }
9744        }
9745        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9746        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9747                System.currentTimeMillis(), user);
9748        if (newPackage == null) {
9749            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9750            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9751                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9752            }
9753        } else {
9754            updateSettingsLI(newPackage,
9755                    installerPackageName,
9756                    null, null,
9757                    res);
9758            // delete the partially installed application. the data directory will have to be
9759            // restored if it was already existing
9760            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9761                // remove package from internal structures.  Note that we want deletePackageX to
9762                // delete the package data and cache directories that it created in
9763                // scanPackageLocked, unless those directories existed before we even tried to
9764                // install.
9765                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9766                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9767                                res.removedInfo, true);
9768            }
9769        }
9770    }
9771
9772    private void replacePackageLI(PackageParser.Package pkg,
9773            int parseFlags, int scanMode, UserHandle user,
9774            String installerPackageName, PackageInstalledInfo res) {
9775
9776        PackageParser.Package oldPackage;
9777        String pkgName = pkg.packageName;
9778        int[] allUsers;
9779        boolean[] perUserInstalled;
9780
9781        // First find the old package info and check signatures
9782        synchronized(mPackages) {
9783            oldPackage = mPackages.get(pkgName);
9784            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9785            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9786                    != PackageManager.SIGNATURE_MATCH) {
9787                Slog.w(TAG, "New package has a different signature: " + pkgName);
9788                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9789                return;
9790            }
9791
9792            // In case of rollback, remember per-user/profile install state
9793            PackageSetting ps = mSettings.mPackages.get(pkgName);
9794            allUsers = sUserManager.getUserIds();
9795            perUserInstalled = new boolean[allUsers.length];
9796            for (int i = 0; i < allUsers.length; i++) {
9797                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9798            }
9799        }
9800        boolean sysPkg = (isSystemApp(oldPackage));
9801        if (sysPkg) {
9802            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9803                    user, allUsers, perUserInstalled, installerPackageName, res);
9804        } else {
9805            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9806                    user, allUsers, perUserInstalled, installerPackageName, res);
9807        }
9808    }
9809
9810    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9811            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9812            int[] allUsers, boolean[] perUserInstalled,
9813            String installerPackageName, PackageInstalledInfo res) {
9814        PackageParser.Package newPackage = null;
9815        String pkgName = deletedPackage.packageName;
9816        boolean deletedPkg = true;
9817        boolean updatedSettings = false;
9818
9819        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9820                + deletedPackage);
9821        long origUpdateTime;
9822        if (pkg.mExtras != null) {
9823            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9824        } else {
9825            origUpdateTime = 0;
9826        }
9827
9828        // First delete the existing package while retaining the data directory
9829        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9830                res.removedInfo, true)) {
9831            // If the existing package wasn't successfully deleted
9832            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9833            deletedPkg = false;
9834        } else {
9835            // Successfully deleted the old package. Now proceed with re-installation
9836            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9837            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
9838                    System.currentTimeMillis(), user);
9839            if (newPackage == null) {
9840                Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9841                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9842                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9843                }
9844            } else {
9845                updateSettingsLI(newPackage,
9846                        installerPackageName,
9847                        allUsers, perUserInstalled,
9848                        res);
9849                updatedSettings = true;
9850            }
9851        }
9852
9853        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9854            // remove package from internal structures.  Note that we want deletePackageX to
9855            // delete the package data and cache directories that it created in
9856            // scanPackageLocked, unless those directories existed before we even tried to
9857            // install.
9858            if(updatedSettings) {
9859                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9860                deletePackageLI(
9861                        pkgName, null, true, allUsers, perUserInstalled,
9862                        PackageManager.DELETE_KEEP_DATA,
9863                                res.removedInfo, true);
9864            }
9865            // Since we failed to install the new package we need to restore the old
9866            // package that we deleted.
9867            if(deletedPkg) {
9868                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9869                File restoreFile = new File(deletedPackage.mPath);
9870                // Parse old package
9871                boolean oldOnSd = isExternal(deletedPackage);
9872                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9873                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9874                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9875                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
9876                        | SCAN_UPDATE_TIME;
9877                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
9878                        origUpdateTime, null) == null) {
9879                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
9880                    return;
9881                }
9882                // Restore of old package succeeded. Update permissions.
9883                // writer
9884                synchronized (mPackages) {
9885                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9886                            UPDATE_PERMISSIONS_ALL);
9887                    // can downgrade to reader
9888                    mSettings.writeLPr();
9889                }
9890                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9891            }
9892        }
9893    }
9894
9895    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9896            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9897            int[] allUsers, boolean[] perUserInstalled,
9898            String installerPackageName, PackageInstalledInfo res) {
9899        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9900                + ", old=" + deletedPackage);
9901        PackageParser.Package newPackage = null;
9902        boolean updatedSettings = false;
9903        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
9904                PackageParser.PARSE_IS_SYSTEM;
9905        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9906            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9907        }
9908        String packageName = deletedPackage.packageName;
9909        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9910        if (packageName == null) {
9911            Slog.w(TAG, "Attempt to delete null packageName.");
9912            return;
9913        }
9914        PackageParser.Package oldPkg;
9915        PackageSetting oldPkgSetting;
9916        // reader
9917        synchronized (mPackages) {
9918            oldPkg = mPackages.get(packageName);
9919            oldPkgSetting = mSettings.mPackages.get(packageName);
9920            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9921                    (oldPkgSetting == null)) {
9922                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
9923                return;
9924            }
9925        }
9926
9927        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9928
9929        res.removedInfo.uid = oldPkg.applicationInfo.uid;
9930        res.removedInfo.removedPackage = packageName;
9931        // Remove existing system package
9932        removePackageLI(oldPkgSetting, true);
9933        // writer
9934        synchronized (mPackages) {
9935            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
9936                // We didn't need to disable the .apk as a current system package,
9937                // which means we are replacing another update that is already
9938                // installed.  We need to make sure to delete the older one's .apk.
9939                res.removedInfo.args = createInstallArgs(0,
9940                        deletedPackage.applicationInfo.sourceDir,
9941                        deletedPackage.applicationInfo.publicSourceDir,
9942                        deletedPackage.applicationInfo.nativeLibraryDir,
9943                        getAppInstructionSet(deletedPackage.applicationInfo));
9944            } else {
9945                res.removedInfo.args = null;
9946            }
9947        }
9948
9949        // Successfully disabled the old package. Now proceed with re-installation
9950        res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9951        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9952        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
9953        if (newPackage == null) {
9954            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9955            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9956                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9957            }
9958        } else {
9959            if (newPackage.mExtras != null) {
9960                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
9961                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
9962                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
9963
9964                // is the update attempting to change shared user? that isn't going to work...
9965                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
9966                    Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser
9967                            + " to " + newPkgSetting.sharedUser);
9968                    res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
9969                    updatedSettings = true;
9970                }
9971            }
9972
9973            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9974                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9975                updatedSettings = true;
9976            }
9977        }
9978
9979        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9980            // Re installation failed. Restore old information
9981            // Remove new pkg information
9982            if (newPackage != null) {
9983                removeInstalledPackageLI(newPackage, true);
9984            }
9985            // Add back the old system package
9986            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
9987            // Restore the old system information in Settings
9988            synchronized(mPackages) {
9989                if (updatedSettings) {
9990                    mSettings.enableSystemPackageLPw(packageName);
9991                    mSettings.setInstallerPackageName(packageName,
9992                            oldPkgSetting.installerPackageName);
9993                }
9994                mSettings.writeLPr();
9995            }
9996        }
9997    }
9998
9999    // Utility method used to move dex files during install.
10000    private int moveDexFilesLI(PackageParser.Package newPackage) {
10001        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
10002            final String instructionSet = getAppInstructionSet(newPackage.applicationInfo);
10003            int retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath,
10004                                             instructionSet);
10005            if (retCode != 0) {
10006                /*
10007                 * Programs may be lazily run through dexopt, so the
10008                 * source may not exist. However, something seems to
10009                 * have gone wrong, so note that dexopt needs to be
10010                 * run again and remove the source file. In addition,
10011                 * remove the target to make sure there isn't a stale
10012                 * file from a previous version of the package.
10013                 */
10014                newPackage.mDexOptNeeded = true;
10015                mInstaller.rmdex(newPackage.mScanPath, instructionSet);
10016                mInstaller.rmdex(newPackage.mPath, instructionSet);
10017            }
10018        }
10019        return PackageManager.INSTALL_SUCCEEDED;
10020    }
10021
10022    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10023            int[] allUsers, boolean[] perUserInstalled,
10024            PackageInstalledInfo res) {
10025        String pkgName = newPackage.packageName;
10026        synchronized (mPackages) {
10027            //write settings. the installStatus will be incomplete at this stage.
10028            //note that the new package setting would have already been
10029            //added to mPackages. It hasn't been persisted yet.
10030            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10031            mSettings.writeLPr();
10032        }
10033
10034        if ((res.returnCode = moveDexFilesLI(newPackage))
10035                != PackageManager.INSTALL_SUCCEEDED) {
10036            // Discontinue if moving dex files failed.
10037            return;
10038        }
10039
10040        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath);
10041
10042        synchronized (mPackages) {
10043            updatePermissionsLPw(newPackage.packageName, newPackage,
10044                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10045                            ? UPDATE_PERMISSIONS_ALL : 0));
10046            // For system-bundled packages, we assume that installing an upgraded version
10047            // of the package implies that the user actually wants to run that new code,
10048            // so we enable the package.
10049            if (isSystemApp(newPackage)) {
10050                // NB: implicit assumption that system package upgrades apply to all users
10051                if (DEBUG_INSTALL) {
10052                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10053                }
10054                PackageSetting ps = mSettings.mPackages.get(pkgName);
10055                if (ps != null) {
10056                    if (res.origUsers != null) {
10057                        for (int userHandle : res.origUsers) {
10058                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10059                                    userHandle, installerPackageName);
10060                        }
10061                    }
10062                    // Also convey the prior install/uninstall state
10063                    if (allUsers != null && perUserInstalled != null) {
10064                        for (int i = 0; i < allUsers.length; i++) {
10065                            if (DEBUG_INSTALL) {
10066                                Slog.d(TAG, "    user " + allUsers[i]
10067                                        + " => " + perUserInstalled[i]);
10068                            }
10069                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10070                        }
10071                        // these install state changes will be persisted in the
10072                        // upcoming call to mSettings.writeLPr().
10073                    }
10074                }
10075            }
10076            res.name = pkgName;
10077            res.uid = newPackage.applicationInfo.uid;
10078            res.pkg = newPackage;
10079            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10080            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10081            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10082            //to update install status
10083            mSettings.writeLPr();
10084        }
10085    }
10086
10087    private void installPackageLI(InstallArgs args,
10088            boolean newInstall, PackageInstalledInfo res) {
10089        int pFlags = args.flags;
10090        String installerPackageName = args.installerPackageName;
10091        File tmpPackageFile = new File(args.getCodePath());
10092        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10093        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10094        boolean replace = false;
10095        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10096                | (newInstall ? SCAN_NEW_INSTALL : 0);
10097        // Result object to be returned
10098        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10099
10100        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10101        // Retrieve PackageSettings and parse package
10102        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10103                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10104                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10105        PackageParser pp = new PackageParser(tmpPackageFile.getPath());
10106        pp.setSeparateProcesses(mSeparateProcesses);
10107        final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
10108                null, mMetrics, parseFlags);
10109        if (pkg == null) {
10110            res.returnCode = pp.getParseError();
10111            return;
10112        }
10113        String pkgName = res.name = pkg.packageName;
10114        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10115            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10116                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
10117                return;
10118            }
10119        }
10120        if (!pp.collectCertificates(pkg, parseFlags)) {
10121            res.returnCode = pp.getParseError();
10122            return;
10123        }
10124
10125        /* If the installer passed in a manifest digest, compare it now. */
10126        if (args.manifestDigest != null) {
10127            if (DEBUG_INSTALL) {
10128                final String parsedManifest = pkg.manifestDigest == null ? "null"
10129                        : pkg.manifestDigest.toString();
10130                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10131                        + parsedManifest);
10132            }
10133
10134            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10135                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
10136                return;
10137            }
10138        } else if (DEBUG_INSTALL) {
10139            final String parsedManifest = pkg.manifestDigest == null
10140                    ? "null" : pkg.manifestDigest.toString();
10141            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10142        }
10143
10144        // Get rid of all references to package scan path via parser.
10145        pp = null;
10146        String oldCodePath = null;
10147        boolean systemApp = false;
10148        synchronized (mPackages) {
10149            // Check whether the newly-scanned package wants to define an already-defined perm
10150            int N = pkg.permissions.size();
10151            for (int i = 0; i < N; i++) {
10152                PackageParser.Permission perm = pkg.permissions.get(i);
10153                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10154                if (bp != null) {
10155                    // If the defining package is signed with our cert, it's okay.  This
10156                    // also includes the "updating the same package" case, of course.
10157                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10158                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10159                        Slog.w(TAG, "Package " + pkg.packageName
10160                                + " attempting to redeclare permission " + perm.info.name
10161                                + " already owned by " + bp.sourcePackage);
10162                        res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
10163                        res.origPermission = perm.info.name;
10164                        res.origPackage = bp.sourcePackage;
10165                        return;
10166                    }
10167                }
10168            }
10169
10170            // Check if installing already existing package
10171            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10172                String oldName = mSettings.mRenamedPackages.get(pkgName);
10173                if (pkg.mOriginalPackages != null
10174                        && pkg.mOriginalPackages.contains(oldName)
10175                        && mPackages.containsKey(oldName)) {
10176                    // This package is derived from an original package,
10177                    // and this device has been updating from that original
10178                    // name.  We must continue using the original name, so
10179                    // rename the new package here.
10180                    pkg.setPackageName(oldName);
10181                    pkgName = pkg.packageName;
10182                    replace = true;
10183                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10184                            + oldName + " pkgName=" + pkgName);
10185                } else if (mPackages.containsKey(pkgName)) {
10186                    // This package, under its official name, already exists
10187                    // on the device; we should replace it.
10188                    replace = true;
10189                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10190                }
10191            }
10192            PackageSetting ps = mSettings.mPackages.get(pkgName);
10193            if (ps != null) {
10194                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10195                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10196                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10197                    systemApp = (ps.pkg.applicationInfo.flags &
10198                            ApplicationInfo.FLAG_SYSTEM) != 0;
10199                }
10200                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10201            }
10202        }
10203
10204        if (systemApp && onSd) {
10205            // Disable updates to system apps on sdcard
10206            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
10207            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10208            return;
10209        }
10210
10211        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
10212            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10213            return;
10214        }
10215        // Set application objects path explicitly after the rename
10216        setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
10217        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
10218        if (replace) {
10219            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10220                    installerPackageName, res);
10221        } else {
10222            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10223                    installerPackageName, res);
10224        }
10225        synchronized (mPackages) {
10226            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10227            if (ps != null) {
10228                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10229            }
10230        }
10231    }
10232
10233    private static boolean isForwardLocked(PackageParser.Package pkg) {
10234        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10235    }
10236
10237
10238    private boolean isForwardLocked(PackageSetting ps) {
10239        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10240    }
10241
10242    private static boolean isExternal(PackageParser.Package pkg) {
10243        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10244    }
10245
10246    private static boolean isExternal(PackageSetting ps) {
10247        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10248    }
10249
10250    private static boolean isSystemApp(PackageParser.Package pkg) {
10251        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10252    }
10253
10254    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10255        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10256    }
10257
10258    private static boolean isSystemApp(ApplicationInfo info) {
10259        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10260    }
10261
10262    private static boolean isSystemApp(PackageSetting ps) {
10263        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10264    }
10265
10266    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10267        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10268    }
10269
10270    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10271        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10272    }
10273
10274    private int packageFlagsToInstallFlags(PackageSetting ps) {
10275        int installFlags = 0;
10276        if (isExternal(ps)) {
10277            installFlags |= PackageManager.INSTALL_EXTERNAL;
10278        }
10279        if (isForwardLocked(ps)) {
10280            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10281        }
10282        return installFlags;
10283    }
10284
10285    private void deleteTempPackageFiles() {
10286        final FilenameFilter filter = new FilenameFilter() {
10287            public boolean accept(File dir, String name) {
10288                return name.startsWith("vmdl") && name.endsWith(".tmp");
10289            }
10290        };
10291        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
10292        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
10293    }
10294
10295    private static final void deleteTempPackageFilesInDirectory(File directory,
10296            FilenameFilter filter) {
10297        final String[] tmpFilesList = directory.list(filter);
10298        if (tmpFilesList == null) {
10299            return;
10300        }
10301        for (int i = 0; i < tmpFilesList.length; i++) {
10302            final File tmpFile = new File(directory, tmpFilesList[i]);
10303            tmpFile.delete();
10304        }
10305    }
10306
10307    private File createTempPackageFile(File installDir) {
10308        File tmpPackageFile;
10309        try {
10310            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
10311        } catch (IOException e) {
10312            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
10313            return null;
10314        }
10315        try {
10316            FileUtils.setPermissions(
10317                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
10318                    -1, -1);
10319            if (!SELinux.restorecon(tmpPackageFile)) {
10320                return null;
10321            }
10322        } catch (IOException e) {
10323            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
10324            return null;
10325        }
10326        return tmpPackageFile;
10327    }
10328
10329    @Override
10330    public void deletePackageAsUser(final String packageName,
10331                                    final IPackageDeleteObserver observer,
10332                                    final int userId, final int flags) {
10333        mContext.enforceCallingOrSelfPermission(
10334                android.Manifest.permission.DELETE_PACKAGES, null);
10335        final int uid = Binder.getCallingUid();
10336        if (UserHandle.getUserId(uid) != userId) {
10337            mContext.enforceCallingPermission(
10338                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10339                    "deletePackage for user " + userId);
10340        }
10341        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10342            try {
10343                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10344            } catch (RemoteException re) {
10345            }
10346            return;
10347        }
10348
10349        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10350        // Queue up an async operation since the package deletion may take a little while.
10351        mHandler.post(new Runnable() {
10352            public void run() {
10353                mHandler.removeCallbacks(this);
10354                final int returnCode = deletePackageX(packageName, userId, flags);
10355                if (observer != null) {
10356                    try {
10357                        observer.packageDeleted(packageName, returnCode);
10358                    } catch (RemoteException e) {
10359                        Log.i(TAG, "Observer no longer exists.");
10360                    } //end catch
10361                } //end if
10362            } //end run
10363        });
10364    }
10365
10366    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10367        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10368                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10369        try {
10370            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10371                    || dpm.isDeviceOwner(packageName))) {
10372                return true;
10373            }
10374        } catch (RemoteException e) {
10375        }
10376        return false;
10377    }
10378
10379    /**
10380     *  This method is an internal method that could be get invoked either
10381     *  to delete an installed package or to clean up a failed installation.
10382     *  After deleting an installed package, a broadcast is sent to notify any
10383     *  listeners that the package has been installed. For cleaning up a failed
10384     *  installation, the broadcast is not necessary since the package's
10385     *  installation wouldn't have sent the initial broadcast either
10386     *  The key steps in deleting a package are
10387     *  deleting the package information in internal structures like mPackages,
10388     *  deleting the packages base directories through installd
10389     *  updating mSettings to reflect current status
10390     *  persisting settings for later use
10391     *  sending a broadcast if necessary
10392     */
10393    private int deletePackageX(String packageName, int userId, int flags) {
10394        final PackageRemovedInfo info = new PackageRemovedInfo();
10395        final boolean res;
10396
10397        if (isPackageDeviceAdmin(packageName, userId)) {
10398            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10399            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10400        }
10401
10402        boolean removedForAllUsers = false;
10403        boolean systemUpdate = false;
10404
10405        // for the uninstall-updates case and restricted profiles, remember the per-
10406        // userhandle installed state
10407        int[] allUsers;
10408        boolean[] perUserInstalled;
10409        synchronized (mPackages) {
10410            PackageSetting ps = mSettings.mPackages.get(packageName);
10411            allUsers = sUserManager.getUserIds();
10412            perUserInstalled = new boolean[allUsers.length];
10413            for (int i = 0; i < allUsers.length; i++) {
10414                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10415            }
10416        }
10417
10418        synchronized (mInstallLock) {
10419            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10420            res = deletePackageLI(packageName,
10421                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10422                            ? UserHandle.ALL : new UserHandle(userId),
10423                    true, allUsers, perUserInstalled,
10424                    flags | REMOVE_CHATTY, info, true);
10425            systemUpdate = info.isRemovedPackageSystemUpdate;
10426            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10427                removedForAllUsers = true;
10428            }
10429            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10430                    + " removedForAllUsers=" + removedForAllUsers);
10431        }
10432
10433        if (res) {
10434            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10435
10436            // If the removed package was a system update, the old system package
10437            // was re-enabled; we need to broadcast this information
10438            if (systemUpdate) {
10439                Bundle extras = new Bundle(1);
10440                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10441                        ? info.removedAppId : info.uid);
10442                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10443
10444                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10445                        extras, null, null, null);
10446                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10447                        extras, null, null, null);
10448                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10449                        null, packageName, null, null);
10450            }
10451        }
10452        // Force a gc here.
10453        Runtime.getRuntime().gc();
10454        // Delete the resources here after sending the broadcast to let
10455        // other processes clean up before deleting resources.
10456        if (info.args != null) {
10457            synchronized (mInstallLock) {
10458                info.args.doPostDeleteLI(true);
10459            }
10460        }
10461
10462        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10463    }
10464
10465    static class PackageRemovedInfo {
10466        String removedPackage;
10467        int uid = -1;
10468        int removedAppId = -1;
10469        int[] removedUsers = null;
10470        boolean isRemovedPackageSystemUpdate = false;
10471        // Clean up resources deleted packages.
10472        InstallArgs args = null;
10473
10474        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10475            Bundle extras = new Bundle(1);
10476            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10477            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10478            if (replacing) {
10479                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10480            }
10481            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10482            if (removedPackage != null) {
10483                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10484                        extras, null, null, removedUsers);
10485                if (fullRemove && !replacing) {
10486                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10487                            extras, null, null, removedUsers);
10488                }
10489            }
10490            if (removedAppId >= 0) {
10491                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10492                        removedUsers);
10493            }
10494        }
10495    }
10496
10497    /*
10498     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10499     * flag is not set, the data directory is removed as well.
10500     * make sure this flag is set for partially installed apps. If not its meaningless to
10501     * delete a partially installed application.
10502     */
10503    private void removePackageDataLI(PackageSetting ps,
10504            int[] allUserHandles, boolean[] perUserInstalled,
10505            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10506        String packageName = ps.name;
10507        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10508        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10509        // Retrieve object to delete permissions for shared user later on
10510        final PackageSetting deletedPs;
10511        // reader
10512        synchronized (mPackages) {
10513            deletedPs = mSettings.mPackages.get(packageName);
10514            if (outInfo != null) {
10515                outInfo.removedPackage = packageName;
10516                outInfo.removedUsers = deletedPs != null
10517                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10518                        : null;
10519            }
10520        }
10521        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10522            removeDataDirsLI(packageName);
10523            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10524        }
10525        // writer
10526        synchronized (mPackages) {
10527            if (deletedPs != null) {
10528                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10529                    if (outInfo != null) {
10530                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10531                    }
10532                    if (deletedPs != null) {
10533                        updatePermissionsLPw(deletedPs.name, null, 0);
10534                        if (deletedPs.sharedUser != null) {
10535                            // remove permissions associated with package
10536                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10537                        }
10538                    }
10539                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10540                }
10541                // make sure to preserve per-user disabled state if this removal was just
10542                // a downgrade of a system app to the factory package
10543                if (allUserHandles != null && perUserInstalled != null) {
10544                    if (DEBUG_REMOVE) {
10545                        Slog.d(TAG, "Propagating install state across downgrade");
10546                    }
10547                    for (int i = 0; i < allUserHandles.length; i++) {
10548                        if (DEBUG_REMOVE) {
10549                            Slog.d(TAG, "    user " + allUserHandles[i]
10550                                    + " => " + perUserInstalled[i]);
10551                        }
10552                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10553                    }
10554                }
10555            }
10556            // can downgrade to reader
10557            if (writeSettings) {
10558                // Save settings now
10559                mSettings.writeLPr();
10560            }
10561        }
10562        if (outInfo != null) {
10563            // A user ID was deleted here. Go through all users and remove it
10564            // from KeyStore.
10565            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10566        }
10567    }
10568
10569    static boolean locationIsPrivileged(File path) {
10570        try {
10571            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10572                    .getCanonicalPath();
10573            return path.getCanonicalPath().startsWith(privilegedAppDir);
10574        } catch (IOException e) {
10575            Slog.e(TAG, "Unable to access code path " + path);
10576        }
10577        return false;
10578    }
10579
10580    /*
10581     * Tries to delete system package.
10582     */
10583    private boolean deleteSystemPackageLI(PackageSetting newPs,
10584            int[] allUserHandles, boolean[] perUserInstalled,
10585            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10586        final boolean applyUserRestrictions
10587                = (allUserHandles != null) && (perUserInstalled != null);
10588        PackageSetting disabledPs = null;
10589        // Confirm if the system package has been updated
10590        // An updated system app can be deleted. This will also have to restore
10591        // the system pkg from system partition
10592        // reader
10593        synchronized (mPackages) {
10594            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10595        }
10596        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10597                + " disabledPs=" + disabledPs);
10598        if (disabledPs == null) {
10599            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10600            return false;
10601        } else if (DEBUG_REMOVE) {
10602            Slog.d(TAG, "Deleting system pkg from data partition");
10603        }
10604        if (DEBUG_REMOVE) {
10605            if (applyUserRestrictions) {
10606                Slog.d(TAG, "Remembering install states:");
10607                for (int i = 0; i < allUserHandles.length; i++) {
10608                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10609                }
10610            }
10611        }
10612        // Delete the updated package
10613        outInfo.isRemovedPackageSystemUpdate = true;
10614        if (disabledPs.versionCode < newPs.versionCode) {
10615            // Delete data for downgrades
10616            flags &= ~PackageManager.DELETE_KEEP_DATA;
10617        } else {
10618            // Preserve data by setting flag
10619            flags |= PackageManager.DELETE_KEEP_DATA;
10620        }
10621        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10622                allUserHandles, perUserInstalled, outInfo, writeSettings);
10623        if (!ret) {
10624            return false;
10625        }
10626        // writer
10627        synchronized (mPackages) {
10628            // Reinstate the old system package
10629            mSettings.enableSystemPackageLPw(newPs.name);
10630            // Remove any native libraries from the upgraded package.
10631            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
10632        }
10633        // Install the system package
10634        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10635        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10636        if (locationIsPrivileged(disabledPs.codePath)) {
10637            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10638        }
10639        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
10640                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
10641
10642        if (newPkg == null) {
10643            Slog.w(TAG, "Failed to restore system package:" + newPs.name
10644                    + " with error:" + mLastScanError);
10645            return false;
10646        }
10647        // writer
10648        synchronized (mPackages) {
10649            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10650            setInternalAppNativeLibraryPath(newPkg, ps);
10651            updatePermissionsLPw(newPkg.packageName, newPkg,
10652                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10653            if (applyUserRestrictions) {
10654                if (DEBUG_REMOVE) {
10655                    Slog.d(TAG, "Propagating install state across reinstall");
10656                }
10657                for (int i = 0; i < allUserHandles.length; i++) {
10658                    if (DEBUG_REMOVE) {
10659                        Slog.d(TAG, "    user " + allUserHandles[i]
10660                                + " => " + perUserInstalled[i]);
10661                    }
10662                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10663                }
10664                // Regardless of writeSettings we need to ensure that this restriction
10665                // state propagation is persisted
10666                mSettings.writeAllUsersPackageRestrictionsLPr();
10667            }
10668            // can downgrade to reader here
10669            if (writeSettings) {
10670                mSettings.writeLPr();
10671            }
10672        }
10673        return true;
10674    }
10675
10676    private boolean deleteInstalledPackageLI(PackageSetting ps,
10677            boolean deleteCodeAndResources, int flags,
10678            int[] allUserHandles, boolean[] perUserInstalled,
10679            PackageRemovedInfo outInfo, boolean writeSettings) {
10680        if (outInfo != null) {
10681            outInfo.uid = ps.appId;
10682        }
10683
10684        // Delete package data from internal structures and also remove data if flag is set
10685        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10686
10687        // Delete application code and resources
10688        if (deleteCodeAndResources && (outInfo != null)) {
10689            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
10690                    ps.resourcePathString, ps.nativeLibraryPathString,
10691                    getAppInstructionSetFromSettings(ps));
10692        }
10693        return true;
10694    }
10695
10696    /*
10697     * This method handles package deletion in general
10698     */
10699    private boolean deletePackageLI(String packageName, UserHandle user,
10700            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10701            int flags, PackageRemovedInfo outInfo,
10702            boolean writeSettings) {
10703        if (packageName == null) {
10704            Slog.w(TAG, "Attempt to delete null packageName.");
10705            return false;
10706        }
10707        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10708        PackageSetting ps;
10709        boolean dataOnly = false;
10710        int removeUser = -1;
10711        int appId = -1;
10712        synchronized (mPackages) {
10713            ps = mSettings.mPackages.get(packageName);
10714            if (ps == null) {
10715                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10716                return false;
10717            }
10718            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10719                    && user.getIdentifier() != UserHandle.USER_ALL) {
10720                // The caller is asking that the package only be deleted for a single
10721                // user.  To do this, we just mark its uninstalled state and delete
10722                // its data.  If this is a system app, we only allow this to happen if
10723                // they have set the special DELETE_SYSTEM_APP which requests different
10724                // semantics than normal for uninstalling system apps.
10725                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10726                ps.setUserState(user.getIdentifier(),
10727                        COMPONENT_ENABLED_STATE_DEFAULT,
10728                        false, //installed
10729                        true,  //stopped
10730                        true,  //notLaunched
10731                        false, //blocked
10732                        null, null, null);
10733                if (!isSystemApp(ps)) {
10734                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10735                        // Other user still have this package installed, so all
10736                        // we need to do is clear this user's data and save that
10737                        // it is uninstalled.
10738                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10739                        removeUser = user.getIdentifier();
10740                        appId = ps.appId;
10741                        mSettings.writePackageRestrictionsLPr(removeUser);
10742                    } else {
10743                        // We need to set it back to 'installed' so the uninstall
10744                        // broadcasts will be sent correctly.
10745                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10746                        ps.setInstalled(true, user.getIdentifier());
10747                    }
10748                } else {
10749                    // This is a system app, so we assume that the
10750                    // other users still have this package installed, so all
10751                    // we need to do is clear this user's data and save that
10752                    // it is uninstalled.
10753                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10754                    removeUser = user.getIdentifier();
10755                    appId = ps.appId;
10756                    mSettings.writePackageRestrictionsLPr(removeUser);
10757                }
10758            }
10759        }
10760
10761        if (removeUser >= 0) {
10762            // From above, we determined that we are deleting this only
10763            // for a single user.  Continue the work here.
10764            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10765            if (outInfo != null) {
10766                outInfo.removedPackage = packageName;
10767                outInfo.removedAppId = appId;
10768                outInfo.removedUsers = new int[] {removeUser};
10769            }
10770            mInstaller.clearUserData(packageName, removeUser);
10771            removeKeystoreDataIfNeeded(removeUser, appId);
10772            schedulePackageCleaning(packageName, removeUser, false);
10773            return true;
10774        }
10775
10776        if (dataOnly) {
10777            // Delete application data first
10778            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10779            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10780            return true;
10781        }
10782
10783        boolean ret = false;
10784        mSettings.mKeySetManager.removeAppKeySetData(packageName);
10785        if (isSystemApp(ps)) {
10786            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10787            // When an updated system application is deleted we delete the existing resources as well and
10788            // fall back to existing code in system partition
10789            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10790                    flags, outInfo, writeSettings);
10791        } else {
10792            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10793            // Kill application pre-emptively especially for apps on sd.
10794            killApplication(packageName, ps.appId, "uninstall pkg");
10795            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10796                    allUserHandles, perUserInstalled,
10797                    outInfo, writeSettings);
10798        }
10799
10800        return ret;
10801    }
10802
10803    private final class ClearStorageConnection implements ServiceConnection {
10804        IMediaContainerService mContainerService;
10805
10806        @Override
10807        public void onServiceConnected(ComponentName name, IBinder service) {
10808            synchronized (this) {
10809                mContainerService = IMediaContainerService.Stub.asInterface(service);
10810                notifyAll();
10811            }
10812        }
10813
10814        @Override
10815        public void onServiceDisconnected(ComponentName name) {
10816        }
10817    }
10818
10819    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10820        final boolean mounted;
10821        if (Environment.isExternalStorageEmulated()) {
10822            mounted = true;
10823        } else {
10824            final String status = Environment.getExternalStorageState();
10825
10826            mounted = status.equals(Environment.MEDIA_MOUNTED)
10827                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10828        }
10829
10830        if (!mounted) {
10831            return;
10832        }
10833
10834        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10835        int[] users;
10836        if (userId == UserHandle.USER_ALL) {
10837            users = sUserManager.getUserIds();
10838        } else {
10839            users = new int[] { userId };
10840        }
10841        final ClearStorageConnection conn = new ClearStorageConnection();
10842        if (mContext.bindServiceAsUser(
10843                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10844            try {
10845                for (int curUser : users) {
10846                    long timeout = SystemClock.uptimeMillis() + 5000;
10847                    synchronized (conn) {
10848                        long now = SystemClock.uptimeMillis();
10849                        while (conn.mContainerService == null && now < timeout) {
10850                            try {
10851                                conn.wait(timeout - now);
10852                            } catch (InterruptedException e) {
10853                            }
10854                        }
10855                    }
10856                    if (conn.mContainerService == null) {
10857                        return;
10858                    }
10859
10860                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10861                    clearDirectory(conn.mContainerService,
10862                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10863                    if (allData) {
10864                        clearDirectory(conn.mContainerService,
10865                                userEnv.buildExternalStorageAppDataDirs(packageName));
10866                        clearDirectory(conn.mContainerService,
10867                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10868                    }
10869                }
10870            } finally {
10871                mContext.unbindService(conn);
10872            }
10873        }
10874    }
10875
10876    @Override
10877    public void clearApplicationUserData(final String packageName,
10878            final IPackageDataObserver observer, final int userId) {
10879        mContext.enforceCallingOrSelfPermission(
10880                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10881        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
10882        // Queue up an async operation since the package deletion may take a little while.
10883        mHandler.post(new Runnable() {
10884            public void run() {
10885                mHandler.removeCallbacks(this);
10886                final boolean succeeded;
10887                synchronized (mInstallLock) {
10888                    succeeded = clearApplicationUserDataLI(packageName, userId);
10889                }
10890                clearExternalStorageDataSync(packageName, userId, true);
10891                if (succeeded) {
10892                    // invoke DeviceStorageMonitor's update method to clear any notifications
10893                    DeviceStorageMonitorInternal
10894                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
10895                    if (dsm != null) {
10896                        dsm.checkMemory();
10897                    }
10898                }
10899                if(observer != null) {
10900                    try {
10901                        observer.onRemoveCompleted(packageName, succeeded);
10902                    } catch (RemoteException e) {
10903                        Log.i(TAG, "Observer no longer exists.");
10904                    }
10905                } //end if observer
10906            } //end run
10907        });
10908    }
10909
10910    private boolean clearApplicationUserDataLI(String packageName, int userId) {
10911        if (packageName == null) {
10912            Slog.w(TAG, "Attempt to delete null packageName.");
10913            return false;
10914        }
10915        PackageParser.Package p;
10916        boolean dataOnly = false;
10917        final int appId;
10918        synchronized (mPackages) {
10919            p = mPackages.get(packageName);
10920            if (p == null) {
10921                dataOnly = true;
10922                PackageSetting ps = mSettings.mPackages.get(packageName);
10923                if ((ps == null) || (ps.pkg == null)) {
10924                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10925                    return false;
10926                }
10927                p = ps.pkg;
10928            }
10929            if (!dataOnly) {
10930                // need to check this only for fully installed applications
10931                if (p == null) {
10932                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10933                    return false;
10934                }
10935                final ApplicationInfo applicationInfo = p.applicationInfo;
10936                if (applicationInfo == null) {
10937                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10938                    return false;
10939                }
10940            }
10941            if (p != null && p.applicationInfo != null) {
10942                appId = p.applicationInfo.uid;
10943            } else {
10944                appId = -1;
10945            }
10946        }
10947        int retCode = mInstaller.clearUserData(packageName, userId);
10948        if (retCode < 0) {
10949            Slog.w(TAG, "Couldn't remove cache files for package: "
10950                    + packageName);
10951            return false;
10952        }
10953        removeKeystoreDataIfNeeded(userId, appId);
10954        return true;
10955    }
10956
10957    /**
10958     * Remove entries from the keystore daemon. Will only remove it if the
10959     * {@code appId} is valid.
10960     */
10961    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
10962        if (appId < 0) {
10963            return;
10964        }
10965
10966        final KeyStore keyStore = KeyStore.getInstance();
10967        if (keyStore != null) {
10968            if (userId == UserHandle.USER_ALL) {
10969                for (final int individual : sUserManager.getUserIds()) {
10970                    keyStore.clearUid(UserHandle.getUid(individual, appId));
10971                }
10972            } else {
10973                keyStore.clearUid(UserHandle.getUid(userId, appId));
10974            }
10975        } else {
10976            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
10977        }
10978    }
10979
10980    @Override
10981    public void deleteApplicationCacheFiles(final String packageName,
10982            final IPackageDataObserver observer) {
10983        mContext.enforceCallingOrSelfPermission(
10984                android.Manifest.permission.DELETE_CACHE_FILES, null);
10985        // Queue up an async operation since the package deletion may take a little while.
10986        final int userId = UserHandle.getCallingUserId();
10987        mHandler.post(new Runnable() {
10988            public void run() {
10989                mHandler.removeCallbacks(this);
10990                final boolean succeded;
10991                synchronized (mInstallLock) {
10992                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
10993                }
10994                clearExternalStorageDataSync(packageName, userId, false);
10995                if(observer != null) {
10996                    try {
10997                        observer.onRemoveCompleted(packageName, succeded);
10998                    } catch (RemoteException e) {
10999                        Log.i(TAG, "Observer no longer exists.");
11000                    }
11001                } //end if observer
11002            } //end run
11003        });
11004    }
11005
11006    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11007        if (packageName == null) {
11008            Slog.w(TAG, "Attempt to delete null packageName.");
11009            return false;
11010        }
11011        PackageParser.Package p;
11012        synchronized (mPackages) {
11013            p = mPackages.get(packageName);
11014        }
11015        if (p == null) {
11016            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11017            return false;
11018        }
11019        final ApplicationInfo applicationInfo = p.applicationInfo;
11020        if (applicationInfo == null) {
11021            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11022            return false;
11023        }
11024        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11025        if (retCode < 0) {
11026            Slog.w(TAG, "Couldn't remove cache files for package: "
11027                       + packageName + " u" + userId);
11028            return false;
11029        }
11030        return true;
11031    }
11032
11033    @Override
11034    public void getPackageSizeInfo(final String packageName, int userHandle,
11035            final IPackageStatsObserver observer) {
11036        mContext.enforceCallingOrSelfPermission(
11037                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11038        if (packageName == null) {
11039            throw new IllegalArgumentException("Attempt to get size of null packageName");
11040        }
11041
11042        PackageStats stats = new PackageStats(packageName, userHandle);
11043
11044        /*
11045         * Queue up an async operation since the package measurement may take a
11046         * little while.
11047         */
11048        Message msg = mHandler.obtainMessage(INIT_COPY);
11049        msg.obj = new MeasureParams(stats, observer);
11050        mHandler.sendMessage(msg);
11051    }
11052
11053    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11054            PackageStats pStats) {
11055        if (packageName == null) {
11056            Slog.w(TAG, "Attempt to get size of null packageName.");
11057            return false;
11058        }
11059        PackageParser.Package p;
11060        boolean dataOnly = false;
11061        String libDirPath = null;
11062        String asecPath = null;
11063        PackageSetting ps = null;
11064        synchronized (mPackages) {
11065            p = mPackages.get(packageName);
11066            ps = mSettings.mPackages.get(packageName);
11067            if(p == null) {
11068                dataOnly = true;
11069                if((ps == null) || (ps.pkg == null)) {
11070                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11071                    return false;
11072                }
11073                p = ps.pkg;
11074            }
11075            if (ps != null) {
11076                libDirPath = ps.nativeLibraryPathString;
11077            }
11078            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11079                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
11080                if (secureContainerId != null) {
11081                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11082                }
11083            }
11084        }
11085        String publicSrcDir = null;
11086        if(!dataOnly) {
11087            final ApplicationInfo applicationInfo = p.applicationInfo;
11088            if (applicationInfo == null) {
11089                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11090                return false;
11091            }
11092            if (isForwardLocked(p)) {
11093                publicSrcDir = applicationInfo.publicSourceDir;
11094            }
11095        }
11096        int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath,
11097                publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps),
11098                pStats);
11099        if (res < 0) {
11100            return false;
11101        }
11102
11103        // Fix-up for forward-locked applications in ASEC containers.
11104        if (!isExternal(p)) {
11105            pStats.codeSize += pStats.externalCodeSize;
11106            pStats.externalCodeSize = 0L;
11107        }
11108
11109        return true;
11110    }
11111
11112
11113    @Override
11114    public void addPackageToPreferred(String packageName) {
11115        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11116    }
11117
11118    @Override
11119    public void removePackageFromPreferred(String packageName) {
11120        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11121    }
11122
11123    @Override
11124    public List<PackageInfo> getPreferredPackages(int flags) {
11125        return new ArrayList<PackageInfo>();
11126    }
11127
11128    private int getUidTargetSdkVersionLockedLPr(int uid) {
11129        Object obj = mSettings.getUserIdLPr(uid);
11130        if (obj instanceof SharedUserSetting) {
11131            final SharedUserSetting sus = (SharedUserSetting) obj;
11132            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11133            final Iterator<PackageSetting> it = sus.packages.iterator();
11134            while (it.hasNext()) {
11135                final PackageSetting ps = it.next();
11136                if (ps.pkg != null) {
11137                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11138                    if (v < vers) vers = v;
11139                }
11140            }
11141            return vers;
11142        } else if (obj instanceof PackageSetting) {
11143            final PackageSetting ps = (PackageSetting) obj;
11144            if (ps.pkg != null) {
11145                return ps.pkg.applicationInfo.targetSdkVersion;
11146            }
11147        }
11148        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11149    }
11150
11151    @Override
11152    public void addPreferredActivity(IntentFilter filter, int match,
11153            ComponentName[] set, ComponentName activity, int userId) {
11154        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11155    }
11156
11157    private void addPreferredActivityInternal(IntentFilter filter, int match,
11158            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11159        // writer
11160        int callingUid = Binder.getCallingUid();
11161        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11162        if (filter.countActions() == 0) {
11163            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11164            return;
11165        }
11166        synchronized (mPackages) {
11167            if (mContext.checkCallingOrSelfPermission(
11168                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11169                    != PackageManager.PERMISSION_GRANTED) {
11170                if (getUidTargetSdkVersionLockedLPr(callingUid)
11171                        < Build.VERSION_CODES.FROYO) {
11172                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11173                            + callingUid);
11174                    return;
11175                }
11176                mContext.enforceCallingOrSelfPermission(
11177                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11178            }
11179
11180            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11181            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11182            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11183                    new PreferredActivity(filter, match, set, activity, always));
11184            mSettings.writePackageRestrictionsLPr(userId);
11185        }
11186    }
11187
11188    @Override
11189    public void replacePreferredActivity(IntentFilter filter, int match,
11190            ComponentName[] set, ComponentName activity) {
11191        if (filter.countActions() != 1) {
11192            throw new IllegalArgumentException(
11193                    "replacePreferredActivity expects filter to have only 1 action.");
11194        }
11195        if (filter.countDataAuthorities() != 0
11196                || filter.countDataPaths() != 0
11197                || filter.countDataSchemes() > 1
11198                || filter.countDataTypes() != 0) {
11199            throw new IllegalArgumentException(
11200                    "replacePreferredActivity expects filter to have no data authorities, " +
11201                    "paths, or types; and at most one scheme.");
11202        }
11203        synchronized (mPackages) {
11204            if (mContext.checkCallingOrSelfPermission(
11205                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11206                    != PackageManager.PERMISSION_GRANTED) {
11207                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11208                        < Build.VERSION_CODES.FROYO) {
11209                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11210                            + Binder.getCallingUid());
11211                    return;
11212                }
11213                mContext.enforceCallingOrSelfPermission(
11214                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11215            }
11216
11217            final int callingUserId = UserHandle.getCallingUserId();
11218            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11219            if (pir != null) {
11220                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11221                if (filter.countDataSchemes() == 1) {
11222                    Uri.Builder builder = new Uri.Builder();
11223                    builder.scheme(filter.getDataScheme(0));
11224                    intent.setData(builder.build());
11225                }
11226                List<PreferredActivity> matches = pir.queryIntent(
11227                        intent, null, true, callingUserId);
11228                if (DEBUG_PREFERRED) {
11229                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11230                }
11231                for (int i = 0; i < matches.size(); i++) {
11232                    PreferredActivity pa = matches.get(i);
11233                    if (DEBUG_PREFERRED) {
11234                        Slog.i(TAG, "Removing preferred activity "
11235                                + pa.mPref.mComponent + ":");
11236                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11237                    }
11238                    pir.removeFilter(pa);
11239                }
11240            }
11241            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11242        }
11243    }
11244
11245    @Override
11246    public void clearPackagePreferredActivities(String packageName) {
11247        final int uid = Binder.getCallingUid();
11248        // writer
11249        synchronized (mPackages) {
11250            PackageParser.Package pkg = mPackages.get(packageName);
11251            if (pkg == null || pkg.applicationInfo.uid != uid) {
11252                if (mContext.checkCallingOrSelfPermission(
11253                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11254                        != PackageManager.PERMISSION_GRANTED) {
11255                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11256                            < Build.VERSION_CODES.FROYO) {
11257                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11258                                + Binder.getCallingUid());
11259                        return;
11260                    }
11261                    mContext.enforceCallingOrSelfPermission(
11262                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11263                }
11264            }
11265
11266            int user = UserHandle.getCallingUserId();
11267            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11268                mSettings.writePackageRestrictionsLPr(user);
11269                scheduleWriteSettingsLocked();
11270            }
11271        }
11272    }
11273
11274    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11275    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11276        ArrayList<PreferredActivity> removed = null;
11277        boolean changed = false;
11278        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11279            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11280            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11281            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11282                continue;
11283            }
11284            Iterator<PreferredActivity> it = pir.filterIterator();
11285            while (it.hasNext()) {
11286                PreferredActivity pa = it.next();
11287                // Mark entry for removal only if it matches the package name
11288                // and the entry is of type "always".
11289                if (packageName == null ||
11290                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11291                                && pa.mPref.mAlways)) {
11292                    if (removed == null) {
11293                        removed = new ArrayList<PreferredActivity>();
11294                    }
11295                    removed.add(pa);
11296                }
11297            }
11298            if (removed != null) {
11299                for (int j=0; j<removed.size(); j++) {
11300                    PreferredActivity pa = removed.get(j);
11301                    pir.removeFilter(pa);
11302                }
11303                changed = true;
11304            }
11305        }
11306        return changed;
11307    }
11308
11309    @Override
11310    public void resetPreferredActivities(int userId) {
11311        mContext.enforceCallingOrSelfPermission(
11312                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11313        // writer
11314        synchronized (mPackages) {
11315            int user = UserHandle.getCallingUserId();
11316            clearPackagePreferredActivitiesLPw(null, user);
11317            mSettings.readDefaultPreferredAppsLPw(this, user);
11318            mSettings.writePackageRestrictionsLPr(user);
11319            scheduleWriteSettingsLocked();
11320        }
11321    }
11322
11323    @Override
11324    public int getPreferredActivities(List<IntentFilter> outFilters,
11325            List<ComponentName> outActivities, String packageName) {
11326
11327        int num = 0;
11328        final int userId = UserHandle.getCallingUserId();
11329        // reader
11330        synchronized (mPackages) {
11331            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11332            if (pir != null) {
11333                final Iterator<PreferredActivity> it = pir.filterIterator();
11334                while (it.hasNext()) {
11335                    final PreferredActivity pa = it.next();
11336                    if (packageName == null
11337                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11338                                    && pa.mPref.mAlways)) {
11339                        if (outFilters != null) {
11340                            outFilters.add(new IntentFilter(pa));
11341                        }
11342                        if (outActivities != null) {
11343                            outActivities.add(pa.mPref.mComponent);
11344                        }
11345                    }
11346                }
11347            }
11348        }
11349
11350        return num;
11351    }
11352
11353    @Override
11354    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11355            int userId) {
11356        int callingUid = Binder.getCallingUid();
11357        if (callingUid != Process.SYSTEM_UID) {
11358            throw new SecurityException(
11359                    "addPersistentPreferredActivity can only be run by the system");
11360        }
11361        if (filter.countActions() == 0) {
11362            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11363            return;
11364        }
11365        synchronized (mPackages) {
11366            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11367                    " :");
11368            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11369            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11370                    new PersistentPreferredActivity(filter, activity));
11371            mSettings.writePackageRestrictionsLPr(userId);
11372        }
11373    }
11374
11375    @Override
11376    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11377        int callingUid = Binder.getCallingUid();
11378        if (callingUid != Process.SYSTEM_UID) {
11379            throw new SecurityException(
11380                    "clearPackagePersistentPreferredActivities can only be run by the system");
11381        }
11382        ArrayList<PersistentPreferredActivity> removed = null;
11383        boolean changed = false;
11384        synchronized (mPackages) {
11385            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11386                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11387                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11388                        .valueAt(i);
11389                if (userId != thisUserId) {
11390                    continue;
11391                }
11392                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11393                while (it.hasNext()) {
11394                    PersistentPreferredActivity ppa = it.next();
11395                    // Mark entry for removal only if it matches the package name.
11396                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11397                        if (removed == null) {
11398                            removed = new ArrayList<PersistentPreferredActivity>();
11399                        }
11400                        removed.add(ppa);
11401                    }
11402                }
11403                if (removed != null) {
11404                    for (int j=0; j<removed.size(); j++) {
11405                        PersistentPreferredActivity ppa = removed.get(j);
11406                        ppir.removeFilter(ppa);
11407                    }
11408                    changed = true;
11409                }
11410            }
11411
11412            if (changed) {
11413                mSettings.writePackageRestrictionsLPr(userId);
11414            }
11415        }
11416    }
11417
11418    @Override
11419    public void addForwardingIntentFilter(IntentFilter filter, boolean removable, int userIdOrig,
11420            int userIdDest) {
11421        mContext.enforceCallingOrSelfPermission(
11422                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11423        if (filter.countActions() == 0) {
11424            Slog.w(TAG, "Cannot set a forwarding intent filter with no filter actions");
11425            return;
11426        }
11427        synchronized (mPackages) {
11428            mSettings.editForwardingIntentResolverLPw(userIdOrig).addFilter(
11429                    new ForwardingIntentFilter(filter, removable, userIdDest));
11430            mSettings.writePackageRestrictionsLPr(userIdOrig);
11431        }
11432    }
11433
11434    @Override
11435    public void clearForwardingIntentFilters(int userIdOrig) {
11436        mContext.enforceCallingOrSelfPermission(
11437                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11438        synchronized (mPackages) {
11439            ForwardingIntentResolver fir = mSettings.editForwardingIntentResolverLPw(userIdOrig);
11440            HashSet<ForwardingIntentFilter> set =
11441                    new HashSet<ForwardingIntentFilter>(fir.filterSet());
11442            for (ForwardingIntentFilter fif : set) {
11443                if (fif.isRemovable()) fir.removeFilter(fif);
11444            }
11445            mSettings.writePackageRestrictionsLPr(userIdOrig);
11446        }
11447    }
11448
11449    @Override
11450    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11451        Intent intent = new Intent(Intent.ACTION_MAIN);
11452        intent.addCategory(Intent.CATEGORY_HOME);
11453
11454        final int callingUserId = UserHandle.getCallingUserId();
11455        List<ResolveInfo> list = queryIntentActivities(intent, null,
11456                PackageManager.GET_META_DATA, callingUserId);
11457        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11458                true, false, false, callingUserId);
11459
11460        allHomeCandidates.clear();
11461        if (list != null) {
11462            for (ResolveInfo ri : list) {
11463                allHomeCandidates.add(ri);
11464            }
11465        }
11466        return (preferred == null || preferred.activityInfo == null)
11467                ? null
11468                : new ComponentName(preferred.activityInfo.packageName,
11469                        preferred.activityInfo.name);
11470    }
11471
11472    @Override
11473    public void setApplicationEnabledSetting(String appPackageName,
11474            int newState, int flags, int userId, String callingPackage) {
11475        if (!sUserManager.exists(userId)) return;
11476        if (callingPackage == null) {
11477            callingPackage = Integer.toString(Binder.getCallingUid());
11478        }
11479        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11480    }
11481
11482    @Override
11483    public void setComponentEnabledSetting(ComponentName componentName,
11484            int newState, int flags, int userId) {
11485        if (!sUserManager.exists(userId)) return;
11486        setEnabledSetting(componentName.getPackageName(),
11487                componentName.getClassName(), newState, flags, userId, null);
11488    }
11489
11490    private void setEnabledSetting(final String packageName, String className, int newState,
11491            final int flags, int userId, String callingPackage) {
11492        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11493              || newState == COMPONENT_ENABLED_STATE_ENABLED
11494              || newState == COMPONENT_ENABLED_STATE_DISABLED
11495              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11496              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11497            throw new IllegalArgumentException("Invalid new component state: "
11498                    + newState);
11499        }
11500        PackageSetting pkgSetting;
11501        final int uid = Binder.getCallingUid();
11502        final int permission = mContext.checkCallingOrSelfPermission(
11503                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11504        enforceCrossUserPermission(uid, userId, false, "set enabled");
11505        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11506        boolean sendNow = false;
11507        boolean isApp = (className == null);
11508        String componentName = isApp ? packageName : className;
11509        int packageUid = -1;
11510        ArrayList<String> components;
11511
11512        // writer
11513        synchronized (mPackages) {
11514            pkgSetting = mSettings.mPackages.get(packageName);
11515            if (pkgSetting == null) {
11516                if (className == null) {
11517                    throw new IllegalArgumentException(
11518                            "Unknown package: " + packageName);
11519                }
11520                throw new IllegalArgumentException(
11521                        "Unknown component: " + packageName
11522                        + "/" + className);
11523            }
11524            // Allow root and verify that userId is not being specified by a different user
11525            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11526                throw new SecurityException(
11527                        "Permission Denial: attempt to change component state from pid="
11528                        + Binder.getCallingPid()
11529                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11530            }
11531            if (className == null) {
11532                // We're dealing with an application/package level state change
11533                if (pkgSetting.getEnabled(userId) == newState) {
11534                    // Nothing to do
11535                    return;
11536                }
11537                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11538                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11539                    // Don't care about who enables an app.
11540                    callingPackage = null;
11541                }
11542                pkgSetting.setEnabled(newState, userId, callingPackage);
11543                // pkgSetting.pkg.mSetEnabled = newState;
11544            } else {
11545                // We're dealing with a component level state change
11546                // First, verify that this is a valid class name.
11547                PackageParser.Package pkg = pkgSetting.pkg;
11548                if (pkg == null || !pkg.hasComponentClassName(className)) {
11549                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11550                        throw new IllegalArgumentException("Component class " + className
11551                                + " does not exist in " + packageName);
11552                    } else {
11553                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11554                                + className + " does not exist in " + packageName);
11555                    }
11556                }
11557                switch (newState) {
11558                case COMPONENT_ENABLED_STATE_ENABLED:
11559                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11560                        return;
11561                    }
11562                    break;
11563                case COMPONENT_ENABLED_STATE_DISABLED:
11564                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11565                        return;
11566                    }
11567                    break;
11568                case COMPONENT_ENABLED_STATE_DEFAULT:
11569                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11570                        return;
11571                    }
11572                    break;
11573                default:
11574                    Slog.e(TAG, "Invalid new component state: " + newState);
11575                    return;
11576                }
11577            }
11578            mSettings.writePackageRestrictionsLPr(userId);
11579            components = mPendingBroadcasts.get(userId, packageName);
11580            final boolean newPackage = components == null;
11581            if (newPackage) {
11582                components = new ArrayList<String>();
11583            }
11584            if (!components.contains(componentName)) {
11585                components.add(componentName);
11586            }
11587            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11588                sendNow = true;
11589                // Purge entry from pending broadcast list if another one exists already
11590                // since we are sending one right away.
11591                mPendingBroadcasts.remove(userId, packageName);
11592            } else {
11593                if (newPackage) {
11594                    mPendingBroadcasts.put(userId, packageName, components);
11595                }
11596                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11597                    // Schedule a message
11598                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11599                }
11600            }
11601        }
11602
11603        long callingId = Binder.clearCallingIdentity();
11604        try {
11605            if (sendNow) {
11606                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11607                sendPackageChangedBroadcast(packageName,
11608                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11609            }
11610        } finally {
11611            Binder.restoreCallingIdentity(callingId);
11612        }
11613    }
11614
11615    private void sendPackageChangedBroadcast(String packageName,
11616            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11617        if (DEBUG_INSTALL)
11618            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11619                    + componentNames);
11620        Bundle extras = new Bundle(4);
11621        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11622        String nameList[] = new String[componentNames.size()];
11623        componentNames.toArray(nameList);
11624        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11625        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11626        extras.putInt(Intent.EXTRA_UID, packageUid);
11627        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11628                new int[] {UserHandle.getUserId(packageUid)});
11629    }
11630
11631    @Override
11632    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11633        if (!sUserManager.exists(userId)) return;
11634        final int uid = Binder.getCallingUid();
11635        final int permission = mContext.checkCallingOrSelfPermission(
11636                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11637        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11638        enforceCrossUserPermission(uid, userId, true, "stop package");
11639        // writer
11640        synchronized (mPackages) {
11641            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11642                    uid, userId)) {
11643                scheduleWritePackageRestrictionsLocked(userId);
11644            }
11645        }
11646    }
11647
11648    @Override
11649    public String getInstallerPackageName(String packageName) {
11650        // reader
11651        synchronized (mPackages) {
11652            return mSettings.getInstallerPackageNameLPr(packageName);
11653        }
11654    }
11655
11656    @Override
11657    public int getApplicationEnabledSetting(String packageName, int userId) {
11658        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11659        int uid = Binder.getCallingUid();
11660        enforceCrossUserPermission(uid, userId, false, "get enabled");
11661        // reader
11662        synchronized (mPackages) {
11663            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11664        }
11665    }
11666
11667    @Override
11668    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11669        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11670        int uid = Binder.getCallingUid();
11671        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11672        // reader
11673        synchronized (mPackages) {
11674            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11675        }
11676    }
11677
11678    @Override
11679    public void enterSafeMode() {
11680        enforceSystemOrRoot("Only the system can request entering safe mode");
11681
11682        if (!mSystemReady) {
11683            mSafeMode = true;
11684        }
11685    }
11686
11687    @Override
11688    public void systemReady() {
11689        mSystemReady = true;
11690
11691        // Read the compatibilty setting when the system is ready.
11692        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11693                mContext.getContentResolver(),
11694                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11695        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11696        if (DEBUG_SETTINGS) {
11697            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11698        }
11699
11700        synchronized (mPackages) {
11701            // Verify that all of the preferred activity components actually
11702            // exist.  It is possible for applications to be updated and at
11703            // that point remove a previously declared activity component that
11704            // had been set as a preferred activity.  We try to clean this up
11705            // the next time we encounter that preferred activity, but it is
11706            // possible for the user flow to never be able to return to that
11707            // situation so here we do a sanity check to make sure we haven't
11708            // left any junk around.
11709            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11710            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11711                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11712                removed.clear();
11713                for (PreferredActivity pa : pir.filterSet()) {
11714                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11715                        removed.add(pa);
11716                    }
11717                }
11718                if (removed.size() > 0) {
11719                    for (int j=0; j<removed.size(); j++) {
11720                        PreferredActivity pa = removed.get(i);
11721                        Slog.w(TAG, "Removing dangling preferred activity: "
11722                                + pa.mPref.mComponent);
11723                        pir.removeFilter(pa);
11724                    }
11725                    mSettings.writePackageRestrictionsLPr(
11726                            mSettings.mPreferredActivities.keyAt(i));
11727                }
11728            }
11729        }
11730        sUserManager.systemReady();
11731    }
11732
11733    @Override
11734    public boolean isSafeMode() {
11735        return mSafeMode;
11736    }
11737
11738    @Override
11739    public boolean hasSystemUidErrors() {
11740        return mHasSystemUidErrors;
11741    }
11742
11743    static String arrayToString(int[] array) {
11744        StringBuffer buf = new StringBuffer(128);
11745        buf.append('[');
11746        if (array != null) {
11747            for (int i=0; i<array.length; i++) {
11748                if (i > 0) buf.append(", ");
11749                buf.append(array[i]);
11750            }
11751        }
11752        buf.append(']');
11753        return buf.toString();
11754    }
11755
11756    static class DumpState {
11757        public static final int DUMP_LIBS = 1 << 0;
11758
11759        public static final int DUMP_FEATURES = 1 << 1;
11760
11761        public static final int DUMP_RESOLVERS = 1 << 2;
11762
11763        public static final int DUMP_PERMISSIONS = 1 << 3;
11764
11765        public static final int DUMP_PACKAGES = 1 << 4;
11766
11767        public static final int DUMP_SHARED_USERS = 1 << 5;
11768
11769        public static final int DUMP_MESSAGES = 1 << 6;
11770
11771        public static final int DUMP_PROVIDERS = 1 << 7;
11772
11773        public static final int DUMP_VERIFIERS = 1 << 8;
11774
11775        public static final int DUMP_PREFERRED = 1 << 9;
11776
11777        public static final int DUMP_PREFERRED_XML = 1 << 10;
11778
11779        public static final int DUMP_KEYSETS = 1 << 11;
11780
11781        public static final int DUMP_VERSION = 1 << 12;
11782
11783        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11784
11785        private int mTypes;
11786
11787        private int mOptions;
11788
11789        private boolean mTitlePrinted;
11790
11791        private SharedUserSetting mSharedUser;
11792
11793        public boolean isDumping(int type) {
11794            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11795                return true;
11796            }
11797
11798            return (mTypes & type) != 0;
11799        }
11800
11801        public void setDump(int type) {
11802            mTypes |= type;
11803        }
11804
11805        public boolean isOptionEnabled(int option) {
11806            return (mOptions & option) != 0;
11807        }
11808
11809        public void setOptionEnabled(int option) {
11810            mOptions |= option;
11811        }
11812
11813        public boolean onTitlePrinted() {
11814            final boolean printed = mTitlePrinted;
11815            mTitlePrinted = true;
11816            return printed;
11817        }
11818
11819        public boolean getTitlePrinted() {
11820            return mTitlePrinted;
11821        }
11822
11823        public void setTitlePrinted(boolean enabled) {
11824            mTitlePrinted = enabled;
11825        }
11826
11827        public SharedUserSetting getSharedUser() {
11828            return mSharedUser;
11829        }
11830
11831        public void setSharedUser(SharedUserSetting user) {
11832            mSharedUser = user;
11833        }
11834    }
11835
11836    @Override
11837    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11838        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
11839                != PackageManager.PERMISSION_GRANTED) {
11840            pw.println("Permission Denial: can't dump ActivityManager from from pid="
11841                    + Binder.getCallingPid()
11842                    + ", uid=" + Binder.getCallingUid()
11843                    + " without permission "
11844                    + android.Manifest.permission.DUMP);
11845            return;
11846        }
11847
11848        DumpState dumpState = new DumpState();
11849        boolean fullPreferred = false;
11850        boolean checkin = false;
11851
11852        String packageName = null;
11853
11854        int opti = 0;
11855        while (opti < args.length) {
11856            String opt = args[opti];
11857            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11858                break;
11859            }
11860            opti++;
11861            if ("-a".equals(opt)) {
11862                // Right now we only know how to print all.
11863            } else if ("-h".equals(opt)) {
11864                pw.println("Package manager dump options:");
11865                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
11866                pw.println("    --checkin: dump for a checkin");
11867                pw.println("    -f: print details of intent filters");
11868                pw.println("    -h: print this help");
11869                pw.println("  cmd may be one of:");
11870                pw.println("    l[ibraries]: list known shared libraries");
11871                pw.println("    f[ibraries]: list device features");
11872                pw.println("    r[esolvers]: dump intent resolvers");
11873                pw.println("    perm[issions]: dump permissions");
11874                pw.println("    pref[erred]: print preferred package settings");
11875                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
11876                pw.println("    prov[iders]: dump content providers");
11877                pw.println("    p[ackages]: dump installed packages");
11878                pw.println("    s[hared-users]: dump shared user IDs");
11879                pw.println("    m[essages]: print collected runtime messages");
11880                pw.println("    v[erifiers]: print package verifier info");
11881                pw.println("    version: print database version info");
11882                pw.println("    <package.name>: info about given package");
11883                pw.println("    k[eysets]: print known keysets");
11884                return;
11885            } else if ("--checkin".equals(opt)) {
11886                checkin = true;
11887            } else if ("-f".equals(opt)) {
11888                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11889            } else {
11890                pw.println("Unknown argument: " + opt + "; use -h for help");
11891            }
11892        }
11893
11894        // Is the caller requesting to dump a particular piece of data?
11895        if (opti < args.length) {
11896            String cmd = args[opti];
11897            opti++;
11898            // Is this a package name?
11899            if ("android".equals(cmd) || cmd.contains(".")) {
11900                packageName = cmd;
11901                // When dumping a single package, we always dump all of its
11902                // filter information since the amount of data will be reasonable.
11903                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11904            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
11905                dumpState.setDump(DumpState.DUMP_LIBS);
11906            } else if ("f".equals(cmd) || "features".equals(cmd)) {
11907                dumpState.setDump(DumpState.DUMP_FEATURES);
11908            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
11909                dumpState.setDump(DumpState.DUMP_RESOLVERS);
11910            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
11911                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
11912            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
11913                dumpState.setDump(DumpState.DUMP_PREFERRED);
11914            } else if ("preferred-xml".equals(cmd)) {
11915                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
11916                if (opti < args.length && "--full".equals(args[opti])) {
11917                    fullPreferred = true;
11918                    opti++;
11919                }
11920            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
11921                dumpState.setDump(DumpState.DUMP_PACKAGES);
11922            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
11923                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
11924            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
11925                dumpState.setDump(DumpState.DUMP_PROVIDERS);
11926            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
11927                dumpState.setDump(DumpState.DUMP_MESSAGES);
11928            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
11929                dumpState.setDump(DumpState.DUMP_VERIFIERS);
11930            } else if ("version".equals(cmd)) {
11931                dumpState.setDump(DumpState.DUMP_VERSION);
11932            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
11933                dumpState.setDump(DumpState.DUMP_KEYSETS);
11934            }
11935        }
11936
11937        if (checkin) {
11938            pw.println("vers,1");
11939        }
11940
11941        // reader
11942        synchronized (mPackages) {
11943            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
11944                if (!checkin) {
11945                    if (dumpState.onTitlePrinted())
11946                        pw.println();
11947                    pw.println("Database versions:");
11948                    pw.print("  SDK Version:");
11949                    pw.print(" internal=");
11950                    pw.print(mSettings.mInternalSdkPlatform);
11951                    pw.print(" external=");
11952                    pw.println(mSettings.mExternalSdkPlatform);
11953                    pw.print("  DB Version:");
11954                    pw.print(" internal=");
11955                    pw.print(mSettings.mInternalDatabaseVersion);
11956                    pw.print(" external=");
11957                    pw.println(mSettings.mExternalDatabaseVersion);
11958                }
11959            }
11960
11961            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
11962                if (!checkin) {
11963                    if (dumpState.onTitlePrinted())
11964                        pw.println();
11965                    pw.println("Verifiers:");
11966                    pw.print("  Required: ");
11967                    pw.print(mRequiredVerifierPackage);
11968                    pw.print(" (uid=");
11969                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
11970                    pw.println(")");
11971                } else if (mRequiredVerifierPackage != null) {
11972                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
11973                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
11974                }
11975            }
11976
11977            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
11978                boolean printedHeader = false;
11979                final Iterator<String> it = mSharedLibraries.keySet().iterator();
11980                while (it.hasNext()) {
11981                    String name = it.next();
11982                    SharedLibraryEntry ent = mSharedLibraries.get(name);
11983                    if (!checkin) {
11984                        if (!printedHeader) {
11985                            if (dumpState.onTitlePrinted())
11986                                pw.println();
11987                            pw.println("Libraries:");
11988                            printedHeader = true;
11989                        }
11990                        pw.print("  ");
11991                    } else {
11992                        pw.print("lib,");
11993                    }
11994                    pw.print(name);
11995                    if (!checkin) {
11996                        pw.print(" -> ");
11997                    }
11998                    if (ent.path != null) {
11999                        if (!checkin) {
12000                            pw.print("(jar) ");
12001                            pw.print(ent.path);
12002                        } else {
12003                            pw.print(",jar,");
12004                            pw.print(ent.path);
12005                        }
12006                    } else {
12007                        if (!checkin) {
12008                            pw.print("(apk) ");
12009                            pw.print(ent.apk);
12010                        } else {
12011                            pw.print(",apk,");
12012                            pw.print(ent.apk);
12013                        }
12014                    }
12015                    pw.println();
12016                }
12017            }
12018
12019            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12020                if (dumpState.onTitlePrinted())
12021                    pw.println();
12022                if (!checkin) {
12023                    pw.println("Features:");
12024                }
12025                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12026                while (it.hasNext()) {
12027                    String name = it.next();
12028                    if (!checkin) {
12029                        pw.print("  ");
12030                    } else {
12031                        pw.print("feat,");
12032                    }
12033                    pw.println(name);
12034                }
12035            }
12036
12037            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12038                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12039                        : "Activity Resolver Table:", "  ", packageName,
12040                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12041                    dumpState.setTitlePrinted(true);
12042                }
12043                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12044                        : "Receiver Resolver Table:", "  ", packageName,
12045                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12046                    dumpState.setTitlePrinted(true);
12047                }
12048                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12049                        : "Service Resolver Table:", "  ", packageName,
12050                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12051                    dumpState.setTitlePrinted(true);
12052                }
12053                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12054                        : "Provider Resolver Table:", "  ", packageName,
12055                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12056                    dumpState.setTitlePrinted(true);
12057                }
12058            }
12059
12060            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12061                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12062                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12063                    int user = mSettings.mPreferredActivities.keyAt(i);
12064                    if (pir.dump(pw,
12065                            dumpState.getTitlePrinted()
12066                                ? "\nPreferred Activities User " + user + ":"
12067                                : "Preferred Activities User " + user + ":", "  ",
12068                            packageName, true)) {
12069                        dumpState.setTitlePrinted(true);
12070                    }
12071                }
12072            }
12073
12074            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12075                pw.flush();
12076                FileOutputStream fout = new FileOutputStream(fd);
12077                BufferedOutputStream str = new BufferedOutputStream(fout);
12078                XmlSerializer serializer = new FastXmlSerializer();
12079                try {
12080                    serializer.setOutput(str, "utf-8");
12081                    serializer.startDocument(null, true);
12082                    serializer.setFeature(
12083                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12084                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12085                    serializer.endDocument();
12086                    serializer.flush();
12087                } catch (IllegalArgumentException e) {
12088                    pw.println("Failed writing: " + e);
12089                } catch (IllegalStateException e) {
12090                    pw.println("Failed writing: " + e);
12091                } catch (IOException e) {
12092                    pw.println("Failed writing: " + e);
12093                }
12094            }
12095
12096            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12097                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12098            }
12099
12100            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12101                boolean printedSomething = false;
12102                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12103                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12104                        continue;
12105                    }
12106                    if (!printedSomething) {
12107                        if (dumpState.onTitlePrinted())
12108                            pw.println();
12109                        pw.println("Registered ContentProviders:");
12110                        printedSomething = true;
12111                    }
12112                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12113                    pw.print("    "); pw.println(p.toString());
12114                }
12115                printedSomething = false;
12116                for (Map.Entry<String, PackageParser.Provider> entry :
12117                        mProvidersByAuthority.entrySet()) {
12118                    PackageParser.Provider p = entry.getValue();
12119                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12120                        continue;
12121                    }
12122                    if (!printedSomething) {
12123                        if (dumpState.onTitlePrinted())
12124                            pw.println();
12125                        pw.println("ContentProvider Authorities:");
12126                        printedSomething = true;
12127                    }
12128                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12129                    pw.print("    "); pw.println(p.toString());
12130                    if (p.info != null && p.info.applicationInfo != null) {
12131                        final String appInfo = p.info.applicationInfo.toString();
12132                        pw.print("      applicationInfo="); pw.println(appInfo);
12133                    }
12134                }
12135            }
12136
12137            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12138                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
12139            }
12140
12141            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12142                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12143            }
12144
12145            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12146                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12147            }
12148
12149            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12150                if (dumpState.onTitlePrinted())
12151                    pw.println();
12152                mSettings.dumpReadMessagesLPr(pw, dumpState);
12153
12154                pw.println();
12155                pw.println("Package warning messages:");
12156                final File fname = getSettingsProblemFile();
12157                FileInputStream in = null;
12158                try {
12159                    in = new FileInputStream(fname);
12160                    final int avail = in.available();
12161                    final byte[] data = new byte[avail];
12162                    in.read(data);
12163                    pw.print(new String(data));
12164                } catch (FileNotFoundException e) {
12165                } catch (IOException e) {
12166                } finally {
12167                    if (in != null) {
12168                        try {
12169                            in.close();
12170                        } catch (IOException e) {
12171                        }
12172                    }
12173                }
12174            }
12175        }
12176    }
12177
12178    // ------- apps on sdcard specific code -------
12179    static final boolean DEBUG_SD_INSTALL = false;
12180
12181    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12182
12183    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12184
12185    private boolean mMediaMounted = false;
12186
12187    private String getEncryptKey() {
12188        try {
12189            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12190                    SD_ENCRYPTION_KEYSTORE_NAME);
12191            if (sdEncKey == null) {
12192                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12193                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12194                if (sdEncKey == null) {
12195                    Slog.e(TAG, "Failed to create encryption keys");
12196                    return null;
12197                }
12198            }
12199            return sdEncKey;
12200        } catch (NoSuchAlgorithmException nsae) {
12201            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12202            return null;
12203        } catch (IOException ioe) {
12204            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12205            return null;
12206        }
12207
12208    }
12209
12210    /* package */static String getTempContainerId() {
12211        int tmpIdx = 1;
12212        String list[] = PackageHelper.getSecureContainerList();
12213        if (list != null) {
12214            for (final String name : list) {
12215                // Ignore null and non-temporary container entries
12216                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12217                    continue;
12218                }
12219
12220                String subStr = name.substring(mTempContainerPrefix.length());
12221                try {
12222                    int cid = Integer.parseInt(subStr);
12223                    if (cid >= tmpIdx) {
12224                        tmpIdx = cid + 1;
12225                    }
12226                } catch (NumberFormatException e) {
12227                }
12228            }
12229        }
12230        return mTempContainerPrefix + tmpIdx;
12231    }
12232
12233    /*
12234     * Update media status on PackageManager.
12235     */
12236    @Override
12237    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12238        int callingUid = Binder.getCallingUid();
12239        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12240            throw new SecurityException("Media status can only be updated by the system");
12241        }
12242        // reader; this apparently protects mMediaMounted, but should probably
12243        // be a different lock in that case.
12244        synchronized (mPackages) {
12245            Log.i(TAG, "Updating external media status from "
12246                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12247                    + (mediaStatus ? "mounted" : "unmounted"));
12248            if (DEBUG_SD_INSTALL)
12249                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12250                        + ", mMediaMounted=" + mMediaMounted);
12251            if (mediaStatus == mMediaMounted) {
12252                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12253                        : 0, -1);
12254                mHandler.sendMessage(msg);
12255                return;
12256            }
12257            mMediaMounted = mediaStatus;
12258        }
12259        // Queue up an async operation since the package installation may take a
12260        // little while.
12261        mHandler.post(new Runnable() {
12262            public void run() {
12263                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12264            }
12265        });
12266    }
12267
12268    /**
12269     * Called by MountService when the initial ASECs to scan are available.
12270     * Should block until all the ASEC containers are finished being scanned.
12271     */
12272    public void scanAvailableAsecs() {
12273        updateExternalMediaStatusInner(true, false, false);
12274        if (mShouldRestoreconData) {
12275            SELinuxMMAC.setRestoreconDone();
12276            mShouldRestoreconData = false;
12277        }
12278    }
12279
12280    /*
12281     * Collect information of applications on external media, map them against
12282     * existing containers and update information based on current mount status.
12283     * Please note that we always have to report status if reportStatus has been
12284     * set to true especially when unloading packages.
12285     */
12286    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12287            boolean externalStorage) {
12288        // Collection of uids
12289        int uidArr[] = null;
12290        // Collection of stale containers
12291        HashSet<String> removeCids = new HashSet<String>();
12292        // Collection of packages on external media with valid containers.
12293        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12294        // Get list of secure containers.
12295        final String list[] = PackageHelper.getSecureContainerList();
12296        if (list == null || list.length == 0) {
12297            Log.i(TAG, "No secure containers on sdcard");
12298        } else {
12299            // Process list of secure containers and categorize them
12300            // as active or stale based on their package internal state.
12301            int uidList[] = new int[list.length];
12302            int num = 0;
12303            // reader
12304            synchronized (mPackages) {
12305                for (String cid : list) {
12306                    if (DEBUG_SD_INSTALL)
12307                        Log.i(TAG, "Processing container " + cid);
12308                    String pkgName = getAsecPackageName(cid);
12309                    if (pkgName == null) {
12310                        if (DEBUG_SD_INSTALL)
12311                            Log.i(TAG, "Container : " + cid + " stale");
12312                        removeCids.add(cid);
12313                        continue;
12314                    }
12315                    if (DEBUG_SD_INSTALL)
12316                        Log.i(TAG, "Looking for pkg : " + pkgName);
12317
12318                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12319                    if (ps == null) {
12320                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12321                        removeCids.add(cid);
12322                        continue;
12323                    }
12324
12325                    /*
12326                     * Skip packages that are not external if we're unmounting
12327                     * external storage.
12328                     */
12329                    if (externalStorage && !isMounted && !isExternal(ps)) {
12330                        continue;
12331                    }
12332
12333                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12334                            getAppInstructionSetFromSettings(ps),
12335                            isForwardLocked(ps));
12336                    // The package status is changed only if the code path
12337                    // matches between settings and the container id.
12338                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12339                        if (DEBUG_SD_INSTALL) {
12340                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12341                                    + " at code path: " + ps.codePathString);
12342                        }
12343
12344                        // We do have a valid package installed on sdcard
12345                        processCids.put(args, ps.codePathString);
12346                        final int uid = ps.appId;
12347                        if (uid != -1) {
12348                            uidList[num++] = uid;
12349                        }
12350                    } else {
12351                        Log.i(TAG, "Deleting stale container for " + cid);
12352                        removeCids.add(cid);
12353                    }
12354                }
12355            }
12356
12357            if (num > 0) {
12358                // Sort uid list
12359                Arrays.sort(uidList, 0, num);
12360                // Throw away duplicates
12361                uidArr = new int[num];
12362                uidArr[0] = uidList[0];
12363                int di = 0;
12364                for (int i = 1; i < num; i++) {
12365                    if (uidList[i - 1] != uidList[i]) {
12366                        uidArr[di++] = uidList[i];
12367                    }
12368                }
12369            }
12370        }
12371        // Process packages with valid entries.
12372        if (isMounted) {
12373            if (DEBUG_SD_INSTALL)
12374                Log.i(TAG, "Loading packages");
12375            loadMediaPackages(processCids, uidArr, removeCids);
12376            startCleaningPackages();
12377        } else {
12378            if (DEBUG_SD_INSTALL)
12379                Log.i(TAG, "Unloading packages");
12380            unloadMediaPackages(processCids, uidArr, reportStatus);
12381        }
12382    }
12383
12384   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12385           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12386        int size = pkgList.size();
12387        if (size > 0) {
12388            // Send broadcasts here
12389            Bundle extras = new Bundle();
12390            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12391                    .toArray(new String[size]));
12392            if (uidArr != null) {
12393                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12394            }
12395            if (replacing) {
12396                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12397            }
12398            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12399                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12400            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12401        }
12402    }
12403
12404   /*
12405     * Look at potentially valid container ids from processCids If package
12406     * information doesn't match the one on record or package scanning fails,
12407     * the cid is added to list of removeCids. We currently don't delete stale
12408     * containers.
12409     */
12410   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12411            HashSet<String> removeCids) {
12412        ArrayList<String> pkgList = new ArrayList<String>();
12413        Set<AsecInstallArgs> keys = processCids.keySet();
12414        boolean doGc = false;
12415        for (AsecInstallArgs args : keys) {
12416            String codePath = processCids.get(args);
12417            if (DEBUG_SD_INSTALL)
12418                Log.i(TAG, "Loading container : " + args.cid);
12419            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12420            try {
12421                // Make sure there are no container errors first.
12422                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12423                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12424                            + " when installing from sdcard");
12425                    continue;
12426                }
12427                // Check code path here.
12428                if (codePath == null || !codePath.equals(args.getCodePath())) {
12429                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12430                            + " does not match one in settings " + codePath);
12431                    continue;
12432                }
12433                // Parse package
12434                int parseFlags = mDefParseFlags;
12435                if (args.isExternal()) {
12436                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12437                }
12438                if (args.isFwdLocked()) {
12439                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12440                }
12441
12442                doGc = true;
12443                synchronized (mInstallLock) {
12444                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
12445                            0, 0, null);
12446                    // Scan the package
12447                    if (pkg != null) {
12448                        /*
12449                         * TODO why is the lock being held? doPostInstall is
12450                         * called in other places without the lock. This needs
12451                         * to be straightened out.
12452                         */
12453                        // writer
12454                        synchronized (mPackages) {
12455                            retCode = PackageManager.INSTALL_SUCCEEDED;
12456                            pkgList.add(pkg.packageName);
12457                            // Post process args
12458                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12459                                    pkg.applicationInfo.uid);
12460                        }
12461                    } else {
12462                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12463                    }
12464                }
12465
12466            } finally {
12467                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12468                    // Don't destroy container here. Wait till gc clears things
12469                    // up.
12470                    removeCids.add(args.cid);
12471                }
12472            }
12473        }
12474        // writer
12475        synchronized (mPackages) {
12476            // If the platform SDK has changed since the last time we booted,
12477            // we need to re-grant app permission to catch any new ones that
12478            // appear. This is really a hack, and means that apps can in some
12479            // cases get permissions that the user didn't initially explicitly
12480            // allow... it would be nice to have some better way to handle
12481            // this situation.
12482            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12483            if (regrantPermissions)
12484                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12485                        + mSdkVersion + "; regranting permissions for external storage");
12486            mSettings.mExternalSdkPlatform = mSdkVersion;
12487
12488            // Make sure group IDs have been assigned, and any permission
12489            // changes in other apps are accounted for
12490            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12491                    | (regrantPermissions
12492                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12493                            : 0));
12494
12495            mSettings.updateExternalDatabaseVersion();
12496
12497            // can downgrade to reader
12498            // Persist settings
12499            mSettings.writeLPr();
12500        }
12501        // Send a broadcast to let everyone know we are done processing
12502        if (pkgList.size() > 0) {
12503            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12504        }
12505        // Force gc to avoid any stale parser references that we might have.
12506        if (doGc) {
12507            Runtime.getRuntime().gc();
12508        }
12509        // List stale containers and destroy stale temporary containers.
12510        if (removeCids != null) {
12511            for (String cid : removeCids) {
12512                if (cid.startsWith(mTempContainerPrefix)) {
12513                    Log.i(TAG, "Destroying stale temporary container " + cid);
12514                    PackageHelper.destroySdDir(cid);
12515                } else {
12516                    Log.w(TAG, "Container " + cid + " is stale");
12517               }
12518           }
12519        }
12520    }
12521
12522   /*
12523     * Utility method to unload a list of specified containers
12524     */
12525    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12526        // Just unmount all valid containers.
12527        for (AsecInstallArgs arg : cidArgs) {
12528            synchronized (mInstallLock) {
12529                arg.doPostDeleteLI(false);
12530           }
12531       }
12532   }
12533
12534    /*
12535     * Unload packages mounted on external media. This involves deleting package
12536     * data from internal structures, sending broadcasts about diabled packages,
12537     * gc'ing to free up references, unmounting all secure containers
12538     * corresponding to packages on external media, and posting a
12539     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12540     * that we always have to post this message if status has been requested no
12541     * matter what.
12542     */
12543    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12544            final boolean reportStatus) {
12545        if (DEBUG_SD_INSTALL)
12546            Log.i(TAG, "unloading media packages");
12547        ArrayList<String> pkgList = new ArrayList<String>();
12548        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12549        final Set<AsecInstallArgs> keys = processCids.keySet();
12550        for (AsecInstallArgs args : keys) {
12551            String pkgName = args.getPackageName();
12552            if (DEBUG_SD_INSTALL)
12553                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12554            // Delete package internally
12555            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12556            synchronized (mInstallLock) {
12557                boolean res = deletePackageLI(pkgName, null, false, null, null,
12558                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12559                if (res) {
12560                    pkgList.add(pkgName);
12561                } else {
12562                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12563                    failedList.add(args);
12564                }
12565            }
12566        }
12567
12568        // reader
12569        synchronized (mPackages) {
12570            // We didn't update the settings after removing each package;
12571            // write them now for all packages.
12572            mSettings.writeLPr();
12573        }
12574
12575        // We have to absolutely send UPDATED_MEDIA_STATUS only
12576        // after confirming that all the receivers processed the ordered
12577        // broadcast when packages get disabled, force a gc to clean things up.
12578        // and unload all the containers.
12579        if (pkgList.size() > 0) {
12580            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12581                    new IIntentReceiver.Stub() {
12582                public void performReceive(Intent intent, int resultCode, String data,
12583                        Bundle extras, boolean ordered, boolean sticky,
12584                        int sendingUser) throws RemoteException {
12585                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12586                            reportStatus ? 1 : 0, 1, keys);
12587                    mHandler.sendMessage(msg);
12588                }
12589            });
12590        } else {
12591            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12592                    keys);
12593            mHandler.sendMessage(msg);
12594        }
12595    }
12596
12597    /** Binder call */
12598    @Override
12599    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12600            final int flags) {
12601        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12602        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12603        int returnCode = PackageManager.MOVE_SUCCEEDED;
12604        int currFlags = 0;
12605        int newFlags = 0;
12606        // reader
12607        synchronized (mPackages) {
12608            PackageParser.Package pkg = mPackages.get(packageName);
12609            if (pkg == null) {
12610                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12611            } else {
12612                // Disable moving fwd locked apps and system packages
12613                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12614                    Slog.w(TAG, "Cannot move system application");
12615                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12616                } else if (pkg.mOperationPending) {
12617                    Slog.w(TAG, "Attempt to move package which has pending operations");
12618                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12619                } else {
12620                    // Find install location first
12621                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12622                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12623                        Slog.w(TAG, "Ambigous flags specified for move location.");
12624                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12625                    } else {
12626                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12627                                : PackageManager.INSTALL_INTERNAL;
12628                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12629                                : PackageManager.INSTALL_INTERNAL;
12630
12631                        if (newFlags == currFlags) {
12632                            Slog.w(TAG, "No move required. Trying to move to same location");
12633                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12634                        } else {
12635                            if (isForwardLocked(pkg)) {
12636                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12637                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12638                            }
12639                        }
12640                    }
12641                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12642                        pkg.mOperationPending = true;
12643                    }
12644                }
12645            }
12646
12647            /*
12648             * TODO this next block probably shouldn't be inside the lock. We
12649             * can't guarantee these won't change after this is fired off
12650             * anyway.
12651             */
12652            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12653                processPendingMove(new MoveParams(null, observer, 0, packageName, null,
12654                        null, -1, user),
12655                        returnCode);
12656            } else {
12657                Message msg = mHandler.obtainMessage(INIT_COPY);
12658                final String instructionSet = getAppInstructionSet(pkg.applicationInfo);
12659                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
12660                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir,
12661                        instructionSet);
12662                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12663                        pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user);
12664                msg.obj = mp;
12665                mHandler.sendMessage(msg);
12666            }
12667        }
12668    }
12669
12670    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12671        // Queue up an async operation since the package deletion may take a
12672        // little while.
12673        mHandler.post(new Runnable() {
12674            public void run() {
12675                // TODO fix this; this does nothing.
12676                mHandler.removeCallbacks(this);
12677                int returnCode = currentStatus;
12678                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12679                    int uidArr[] = null;
12680                    ArrayList<String> pkgList = null;
12681                    synchronized (mPackages) {
12682                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12683                        if (pkg == null) {
12684                            Slog.w(TAG, " Package " + mp.packageName
12685                                    + " doesn't exist. Aborting move");
12686                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12687                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
12688                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12689                                    + mp.srcArgs.getCodePath() + " to "
12690                                    + pkg.applicationInfo.sourceDir
12691                                    + " Aborting move and returning error");
12692                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12693                        } else {
12694                            uidArr = new int[] {
12695                                pkg.applicationInfo.uid
12696                            };
12697                            pkgList = new ArrayList<String>();
12698                            pkgList.add(mp.packageName);
12699                        }
12700                    }
12701                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12702                        // Send resources unavailable broadcast
12703                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12704                        // Update package code and resource paths
12705                        synchronized (mInstallLock) {
12706                            synchronized (mPackages) {
12707                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12708                                // Recheck for package again.
12709                                if (pkg == null) {
12710                                    Slog.w(TAG, " Package " + mp.packageName
12711                                            + " doesn't exist. Aborting move");
12712                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12713                                } else if (!mp.srcArgs.getCodePath().equals(
12714                                        pkg.applicationInfo.sourceDir)) {
12715                                    Slog.w(TAG, "Package " + mp.packageName
12716                                            + " code path changed from " + mp.srcArgs.getCodePath()
12717                                            + " to " + pkg.applicationInfo.sourceDir
12718                                            + " Aborting move and returning error");
12719                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12720                                } else {
12721                                    final String oldCodePath = pkg.mPath;
12722                                    final String newCodePath = mp.targetArgs.getCodePath();
12723                                    final String newResPath = mp.targetArgs.getResourcePath();
12724                                    final String newNativePath = mp.targetArgs
12725                                            .getNativeLibraryPath();
12726
12727                                    final File newNativeDir = new File(newNativePath);
12728
12729                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12730                                        // NOTE: We do not report any errors from the APK scan and library
12731                                        // copy at this point.
12732                                        NativeLibraryHelper.ApkHandle handle =
12733                                                new NativeLibraryHelper.ApkHandle(newCodePath);
12734                                        final int abi = NativeLibraryHelper.findSupportedAbi(
12735                                                handle, Build.SUPPORTED_ABIS);
12736                                        if (abi >= 0) {
12737                                            NativeLibraryHelper.copyNativeBinariesIfNeededLI(
12738                                                    handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
12739                                        }
12740                                        handle.close();
12741                                    }
12742                                    final int[] users = sUserManager.getUserIds();
12743                                    for (int user : users) {
12744                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
12745                                                newNativePath, user) < 0) {
12746                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12747                                        }
12748                                    }
12749
12750                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12751                                        pkg.mPath = newCodePath;
12752                                        // Move dex files around
12753                                        if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
12754                                            // Moving of dex files failed. Set
12755                                            // error code and abort move.
12756                                            pkg.mPath = pkg.mScanPath;
12757                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12758                                        }
12759                                    }
12760
12761                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12762                                        pkg.mScanPath = newCodePath;
12763                                        pkg.applicationInfo.sourceDir = newCodePath;
12764                                        pkg.applicationInfo.publicSourceDir = newResPath;
12765                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
12766                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
12767                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
12768                                        ps.codePathString = ps.codePath.getPath();
12769                                        ps.resourcePath = new File(
12770                                                pkg.applicationInfo.publicSourceDir);
12771                                        ps.resourcePathString = ps.resourcePath.getPath();
12772                                        ps.nativeLibraryPathString = newNativePath;
12773                                        // Set the application info flag
12774                                        // correctly.
12775                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
12776                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12777                                        } else {
12778                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12779                                        }
12780                                        ps.setFlags(pkg.applicationInfo.flags);
12781                                        mAppDirs.remove(oldCodePath);
12782                                        mAppDirs.put(newCodePath, pkg);
12783                                        // Persist settings
12784                                        mSettings.writeLPr();
12785                                    }
12786                                }
12787                            }
12788                        }
12789                        // Send resources available broadcast
12790                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12791                    }
12792                }
12793                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12794                    // Clean up failed installation
12795                    if (mp.targetArgs != null) {
12796                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
12797                                -1);
12798                    }
12799                } else {
12800                    // Force a gc to clear things up.
12801                    Runtime.getRuntime().gc();
12802                    // Delete older code
12803                    synchronized (mInstallLock) {
12804                        mp.srcArgs.doPostDeleteLI(true);
12805                    }
12806                }
12807
12808                // Allow more operations on this file if we didn't fail because
12809                // an operation was already pending for this package.
12810                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
12811                    synchronized (mPackages) {
12812                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12813                        if (pkg != null) {
12814                            pkg.mOperationPending = false;
12815                       }
12816                   }
12817                }
12818
12819                IPackageMoveObserver observer = mp.observer;
12820                if (observer != null) {
12821                    try {
12822                        observer.packageMoved(mp.packageName, returnCode);
12823                    } catch (RemoteException e) {
12824                        Log.i(TAG, "Observer no longer exists.");
12825                    }
12826                }
12827            }
12828        });
12829    }
12830
12831    @Override
12832    public boolean setInstallLocation(int loc) {
12833        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12834                null);
12835        if (getInstallLocation() == loc) {
12836            return true;
12837        }
12838        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12839                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12840            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12841                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12842            return true;
12843        }
12844        return false;
12845   }
12846
12847    @Override
12848    public int getInstallLocation() {
12849        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12850                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12851                PackageHelper.APP_INSTALL_AUTO);
12852    }
12853
12854    /** Called by UserManagerService */
12855    void cleanUpUserLILPw(int userHandle) {
12856        mDirtyUsers.remove(userHandle);
12857        mSettings.removeUserLPr(userHandle);
12858        mPendingBroadcasts.remove(userHandle);
12859        if (mInstaller != null) {
12860            // Technically, we shouldn't be doing this with the package lock
12861            // held.  However, this is very rare, and there is already so much
12862            // other disk I/O going on, that we'll let it slide for now.
12863            mInstaller.removeUserDataDirs(userHandle);
12864        }
12865    }
12866
12867    /** Called by UserManagerService */
12868    void createNewUserLILPw(int userHandle, File path) {
12869        if (mInstaller != null) {
12870            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12871        }
12872    }
12873
12874    @Override
12875    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
12876        mContext.enforceCallingOrSelfPermission(
12877                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12878                "Only package verification agents can read the verifier device identity");
12879
12880        synchronized (mPackages) {
12881            return mSettings.getVerifierDeviceIdentityLPw();
12882        }
12883    }
12884
12885    @Override
12886    public void setPermissionEnforced(String permission, boolean enforced) {
12887        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
12888        if (READ_EXTERNAL_STORAGE.equals(permission)) {
12889            synchronized (mPackages) {
12890                if (mSettings.mReadExternalStorageEnforced == null
12891                        || mSettings.mReadExternalStorageEnforced != enforced) {
12892                    mSettings.mReadExternalStorageEnforced = enforced;
12893                    mSettings.writeLPr();
12894                }
12895            }
12896            // kill any non-foreground processes so we restart them and
12897            // grant/revoke the GID.
12898            final IActivityManager am = ActivityManagerNative.getDefault();
12899            if (am != null) {
12900                final long token = Binder.clearCallingIdentity();
12901                try {
12902                    am.killProcessesBelowForeground("setPermissionEnforcement");
12903                } catch (RemoteException e) {
12904                } finally {
12905                    Binder.restoreCallingIdentity(token);
12906                }
12907            }
12908        } else {
12909            throw new IllegalArgumentException("No selective enforcement for " + permission);
12910        }
12911    }
12912
12913    @Override
12914    @Deprecated
12915    public boolean isPermissionEnforced(String permission) {
12916        return true;
12917    }
12918
12919    @Override
12920    public boolean isStorageLow() {
12921        final long token = Binder.clearCallingIdentity();
12922        try {
12923            final DeviceStorageMonitorInternal
12924                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12925            if (dsm != null) {
12926                return dsm.isMemoryLow();
12927            } else {
12928                return false;
12929            }
12930        } finally {
12931            Binder.restoreCallingIdentity(token);
12932        }
12933    }
12934
12935    @Override
12936    public IPackageInstaller getPackageInstaller() {
12937        return mInstallerService;
12938    }
12939}
12940