PackageManagerService.java revision 3a951e52d93697b7e232501b78f9ffb0ec605516
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.system.OsConstants.S_IRWXU;
27import static android.system.OsConstants.S_IRGRP;
28import static android.system.OsConstants.S_IXGRP;
29import static android.system.OsConstants.S_IROTH;
30import static android.system.OsConstants.S_IXOTH;
31import static com.android.internal.util.ArrayUtils.appendInt;
32import static com.android.internal.util.ArrayUtils.removeInt;
33
34import android.content.pm.PackageParser.*;
35import com.android.internal.app.IMediaContainerService;
36import com.android.internal.app.ResolverActivity;
37import com.android.internal.content.NativeLibraryHelper;
38import com.android.internal.content.PackageHelper;
39import com.android.internal.util.FastPrintWriter;
40import com.android.internal.util.FastXmlSerializer;
41import com.android.internal.util.XmlUtils;
42import com.android.server.EventLogTags;
43import com.android.server.IntentResolver;
44import com.android.server.ServiceThread;
45
46import com.android.server.LocalServices;
47import com.android.server.Watchdog;
48import org.xmlpull.v1.XmlPullParser;
49import org.xmlpull.v1.XmlPullParserException;
50import org.xmlpull.v1.XmlSerializer;
51
52import android.app.ActivityManager;
53import android.app.ActivityManagerNative;
54import android.app.IActivityManager;
55import android.app.admin.IDevicePolicyManager;
56import android.app.backup.IBackupManager;
57import android.content.BroadcastReceiver;
58import android.content.ComponentName;
59import android.content.Context;
60import android.content.IIntentReceiver;
61import android.content.Intent;
62import android.content.IntentFilter;
63import android.content.IntentSender;
64import android.content.IntentSender.SendIntentException;
65import android.content.ServiceConnection;
66import android.content.pm.ActivityInfo;
67import android.content.pm.ApplicationInfo;
68import android.content.pm.ContainerEncryptionParams;
69import android.content.pm.FeatureInfo;
70import android.content.pm.IPackageDataObserver;
71import android.content.pm.IPackageDeleteObserver;
72import android.content.pm.IPackageInstallObserver;
73import android.content.pm.IPackageManager;
74import android.content.pm.IPackageMoveObserver;
75import android.content.pm.IPackageStatsObserver;
76import android.content.pm.InstrumentationInfo;
77import android.content.pm.ManifestDigest;
78import android.content.pm.PackageCleanItem;
79import android.content.pm.PackageInfo;
80import android.content.pm.PackageInfoLite;
81import android.content.pm.PackageManager;
82import android.content.pm.PackageParser;
83import android.content.pm.PackageStats;
84import android.content.pm.PackageUserState;
85import android.content.pm.ParceledListSlice;
86import android.content.pm.PermissionGroupInfo;
87import android.content.pm.PermissionInfo;
88import android.content.pm.ProviderInfo;
89import android.content.pm.ResolveInfo;
90import android.content.pm.ServiceInfo;
91import android.content.pm.Signature;
92import android.content.pm.VerificationParams;
93import android.content.pm.VerifierDeviceIdentity;
94import android.content.pm.VerifierInfo;
95import android.content.res.Resources;
96import android.hardware.display.DisplayManager;
97import android.net.Uri;
98import android.os.Binder;
99import android.os.Build;
100import android.os.Bundle;
101import android.os.Environment;
102import android.os.Environment.UserEnvironment;
103import android.os.FileObserver;
104import android.os.FileUtils;
105import android.os.Handler;
106import android.os.HandlerThread;
107import android.os.IBinder;
108import android.os.Looper;
109import android.os.Message;
110import android.os.Parcel;
111import android.os.ParcelFileDescriptor;
112import android.os.Process;
113import android.os.RemoteException;
114import android.os.SELinux;
115import android.os.ServiceManager;
116import android.os.SystemClock;
117import android.os.SystemProperties;
118import android.os.UserHandle;
119import android.os.UserManager;
120import android.security.KeyStore;
121import android.security.SystemKeyStore;
122import android.system.ErrnoException;
123import android.system.Os;
124import android.system.StructStat;
125import android.text.TextUtils;
126import android.util.DisplayMetrics;
127import android.util.EventLog;
128import android.util.Log;
129import android.util.LogPrinter;
130import android.util.PrintStreamPrinter;
131import android.util.Slog;
132import android.util.SparseArray;
133import android.util.Xml;
134import android.view.Display;
135
136import java.io.BufferedOutputStream;
137import java.io.File;
138import java.io.FileDescriptor;
139import java.io.FileInputStream;
140import java.io.FileNotFoundException;
141import java.io.FileOutputStream;
142import java.io.FileReader;
143import java.io.FilenameFilter;
144import java.io.IOException;
145import java.io.PrintWriter;
146import java.security.NoSuchAlgorithmException;
147import java.security.PublicKey;
148import java.security.cert.CertificateException;
149import java.text.SimpleDateFormat;
150import java.util.ArrayList;
151import java.util.Arrays;
152import java.util.Collection;
153import java.util.Collections;
154import java.util.Comparator;
155import java.util.Date;
156import java.util.HashMap;
157import java.util.HashSet;
158import java.util.Iterator;
159import java.util.List;
160import java.util.Map;
161import java.util.Set;
162
163import dalvik.system.VMRuntime;
164import libcore.io.IoUtils;
165
166import com.android.internal.R;
167import com.android.server.storage.DeviceStorageMonitorInternal;
168
169/**
170 * Keep track of all those .apks everywhere.
171 *
172 * This is very central to the platform's security; please run the unit
173 * tests whenever making modifications here:
174 *
175mmm frameworks/base/tests/AndroidTests
176adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
177adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
178 *
179 * {@hide}
180 */
181public class PackageManagerService extends IPackageManager.Stub {
182    static final String TAG = "PackageManager";
183    static final boolean DEBUG_SETTINGS = false;
184    static final boolean DEBUG_PREFERRED = false;
185    static final boolean DEBUG_UPGRADE = false;
186    private static final boolean DEBUG_INSTALL = false;
187    private static final boolean DEBUG_REMOVE = false;
188    private static final boolean DEBUG_BROADCASTS = false;
189    private static final boolean DEBUG_SHOW_INFO = false;
190    private static final boolean DEBUG_PACKAGE_INFO = false;
191    private static final boolean DEBUG_INTENT_MATCHING = false;
192    private static final boolean DEBUG_PACKAGE_SCANNING = false;
193    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
194    private static final boolean DEBUG_VERIFY = false;
195
196    private static final int RADIO_UID = Process.PHONE_UID;
197    private static final int LOG_UID = Process.LOG_UID;
198    private static final int NFC_UID = Process.NFC_UID;
199    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
200    private static final int SHELL_UID = Process.SHELL_UID;
201
202    private static final boolean GET_CERTIFICATES = true;
203
204    private static final int REMOVE_EVENTS =
205        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
206    private static final int ADD_EVENTS =
207        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
208
209    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
210    // Suffix used during package installation when copying/moving
211    // package apks to install directory.
212    private static final String INSTALL_PACKAGE_SUFFIX = "-";
213
214    static final int SCAN_MONITOR = 1<<0;
215    static final int SCAN_NO_DEX = 1<<1;
216    static final int SCAN_FORCE_DEX = 1<<2;
217    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
218    static final int SCAN_NEW_INSTALL = 1<<4;
219    static final int SCAN_NO_PATHS = 1<<5;
220    static final int SCAN_UPDATE_TIME = 1<<6;
221    static final int SCAN_DEFER_DEX = 1<<7;
222    static final int SCAN_BOOTING = 1<<8;
223    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
224    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
225
226    static final int REMOVE_CHATTY = 1<<16;
227
228    /**
229     * Timeout (in milliseconds) after which the watchdog should declare that
230     * our handler thread is wedged.  The usual default for such things is one
231     * minute but we sometimes do very lengthy I/O operations on this thread,
232     * such as installing multi-gigabyte applications, so ours needs to be longer.
233     */
234    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
235
236    /**
237     * Whether verification is enabled by default.
238     */
239    private static final boolean DEFAULT_VERIFY_ENABLE = true;
240
241    /**
242     * The default maximum time to wait for the verification agent to return in
243     * milliseconds.
244     */
245    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
246
247    /**
248     * The default response for package verification timeout.
249     *
250     * This can be either PackageManager.VERIFICATION_ALLOW or
251     * PackageManager.VERIFICATION_REJECT.
252     */
253    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
254
255    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
256
257    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
258            DEFAULT_CONTAINER_PACKAGE,
259            "com.android.defcontainer.DefaultContainerService");
260
261    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
262
263    private static final String LIB_DIR_NAME = "lib";
264    private static final String LIB64_DIR_NAME = "lib64";
265
266    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
267
268    static final String mTempContainerPrefix = "smdl2tmp";
269
270    final ServiceThread mHandlerThread;
271
272    private static String sPreferredInstructionSet;
273
274    private static final String IDMAP_PREFIX = "/data/resource-cache/";
275    private static final String IDMAP_SUFFIX = "@idmap";
276
277    final PackageHandler mHandler;
278
279    final int mSdkVersion = Build.VERSION.SDK_INT;
280    final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
281            ? null : Build.VERSION.CODENAME;
282
283    final Context mContext;
284    final boolean mFactoryTest;
285    final boolean mOnlyCore;
286    final boolean mNoDexOpt;
287    final DisplayMetrics mMetrics;
288    final int mDefParseFlags;
289    final String[] mSeparateProcesses;
290
291    // This is where all application persistent data goes.
292    final File mAppDataDir;
293
294    // This is where all application persistent data goes for secondary users.
295    final File mUserAppDataDir;
296
297    /** The location for ASEC container files on internal storage. */
298    final String mAsecInternalPath;
299
300    // This is the object monitoring the framework dir.
301    final FileObserver mFrameworkInstallObserver;
302
303    // This is the object monitoring the system app dir.
304    final FileObserver mSystemInstallObserver;
305
306    // This is the object monitoring the privileged system app dir.
307    final FileObserver mPrivilegedInstallObserver;
308
309    // This is the object monitoring the system app dir.
310    final FileObserver mVendorInstallObserver;
311
312    // This is the object monitoring the vendor overlay package dir.
313    final FileObserver mVendorOverlayInstallObserver;
314
315    // This is the object monitoring mAppInstallDir.
316    final FileObserver mAppInstallObserver;
317
318    // This is the object monitoring mDrmAppPrivateInstallDir.
319    final FileObserver mDrmAppInstallObserver;
320
321    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
322    // LOCK HELD.  Can be called with mInstallLock held.
323    final Installer mInstaller;
324
325    final File mAppInstallDir;
326
327    /**
328     * Directory to which applications installed internally have native
329     * libraries copied.
330     */
331    private File mAppLibInstallDir;
332
333    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
334    // apps.
335    final File mDrmAppPrivateInstallDir;
336
337    // ----------------------------------------------------------------
338
339    // Lock for state used when installing and doing other long running
340    // operations.  Methods that must be called with this lock held have
341    // the prefix "LI".
342    final Object mInstallLock = new Object();
343
344    // These are the directories in the 3rd party applications installed dir
345    // that we have currently loaded packages from.  Keys are the application's
346    // installed zip file (absolute codePath), and values are Package.
347    final HashMap<String, PackageParser.Package> mAppDirs =
348            new HashMap<String, PackageParser.Package>();
349
350    // Information for the parser to write more useful error messages.
351    int mLastScanError;
352
353    // ----------------------------------------------------------------
354
355    // Keys are String (package name), values are Package.  This also serves
356    // as the lock for the global state.  Methods that must be called with
357    // this lock held have the prefix "LP".
358    final HashMap<String, PackageParser.Package> mPackages =
359            new HashMap<String, PackageParser.Package>();
360
361    // Tracks available target package names -> overlay package paths.
362    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
363        new HashMap<String, HashMap<String, PackageParser.Package>>();
364
365    final Settings mSettings;
366    boolean mRestoredSettings;
367
368    // Group-ids that are given to all packages as read from etc/permissions/*.xml.
369    int[] mGlobalGids;
370
371    // These are the built-in uid -> permission mappings that were read from the
372    // etc/permissions.xml file.
373    final SparseArray<HashSet<String>> mSystemPermissions =
374            new SparseArray<HashSet<String>>();
375
376    static final class SharedLibraryEntry {
377        final String path;
378        final String apk;
379
380        SharedLibraryEntry(String _path, String _apk) {
381            path = _path;
382            apk = _apk;
383        }
384    }
385
386    // These are the built-in shared libraries that were read from the
387    // etc/permissions.xml file.
388    final HashMap<String, SharedLibraryEntry> mSharedLibraries
389            = new HashMap<String, SharedLibraryEntry>();
390
391    // Temporary for building the final shared libraries for an .apk.
392    String[] mTmpSharedLibraries = null;
393
394    // These are the features this devices supports that were read from the
395    // etc/permissions.xml file.
396    final HashMap<String, FeatureInfo> mAvailableFeatures =
397            new HashMap<String, FeatureInfo>();
398
399    // If mac_permissions.xml was found for seinfo labeling.
400    boolean mFoundPolicyFile;
401
402    // If a recursive restorecon of /data/data/<pkg> is needed.
403    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
404
405    // All available activities, for your resolving pleasure.
406    final ActivityIntentResolver mActivities =
407            new ActivityIntentResolver();
408
409    // All available receivers, for your resolving pleasure.
410    final ActivityIntentResolver mReceivers =
411            new ActivityIntentResolver();
412
413    // All available services, for your resolving pleasure.
414    final ServiceIntentResolver mServices = new ServiceIntentResolver();
415
416    // All available providers, for your resolving pleasure.
417    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
418
419    // Mapping from provider base names (first directory in content URI codePath)
420    // to the provider information.
421    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
422            new HashMap<String, PackageParser.Provider>();
423
424    // Mapping from instrumentation class names to info about them.
425    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
426            new HashMap<ComponentName, PackageParser.Instrumentation>();
427
428    // Mapping from permission names to info about them.
429    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
430            new HashMap<String, PackageParser.PermissionGroup>();
431
432    // Packages whose data we have transfered into another package, thus
433    // should no longer exist.
434    final HashSet<String> mTransferedPackages = new HashSet<String>();
435
436    // Broadcast actions that are only available to the system.
437    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
438
439    /** List of packages waiting for verification. */
440    final SparseArray<PackageVerificationState> mPendingVerification
441            = new SparseArray<PackageVerificationState>();
442
443    HashSet<PackageParser.Package> mDeferredDexOpt = null;
444
445    /** Token for keys in mPendingVerification. */
446    private int mPendingVerificationToken = 0;
447
448    boolean mSystemReady;
449    boolean mSafeMode;
450    boolean mHasSystemUidErrors;
451
452    ApplicationInfo mAndroidApplication;
453    final ActivityInfo mResolveActivity = new ActivityInfo();
454    final ResolveInfo mResolveInfo = new ResolveInfo();
455    ComponentName mResolveComponentName;
456    PackageParser.Package mPlatformPackage;
457    ComponentName mCustomResolverComponentName;
458
459    boolean mResolverReplaced = false;
460
461    // Set of pending broadcasts for aggregating enable/disable of components.
462    static class PendingPackageBroadcasts {
463        // for each user id, a map of <package name -> components within that package>
464        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
465
466        public PendingPackageBroadcasts() {
467            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
468        }
469
470        public ArrayList<String> get(int userId, String packageName) {
471            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
472            return packages.get(packageName);
473        }
474
475        public void put(int userId, String packageName, ArrayList<String> components) {
476            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
477            packages.put(packageName, components);
478        }
479
480        public void remove(int userId, String packageName) {
481            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
482            if (packages != null) {
483                packages.remove(packageName);
484            }
485        }
486
487        public void remove(int userId) {
488            mUidMap.remove(userId);
489        }
490
491        public int userIdCount() {
492            return mUidMap.size();
493        }
494
495        public int userIdAt(int n) {
496            return mUidMap.keyAt(n);
497        }
498
499        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
500            return mUidMap.get(userId);
501        }
502
503        public int size() {
504            // total number of pending broadcast entries across all userIds
505            int num = 0;
506            for (int i = 0; i< mUidMap.size(); i++) {
507                num += mUidMap.valueAt(i).size();
508            }
509            return num;
510        }
511
512        public void clear() {
513            mUidMap.clear();
514        }
515
516        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
517            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
518            if (map == null) {
519                map = new HashMap<String, ArrayList<String>>();
520                mUidMap.put(userId, map);
521            }
522            return map;
523        }
524    }
525    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
526
527    // Service Connection to remote media container service to copy
528    // package uri's from external media onto secure containers
529    // or internal storage.
530    private IMediaContainerService mContainerService = null;
531
532    static final int SEND_PENDING_BROADCAST = 1;
533    static final int MCS_BOUND = 3;
534    static final int END_COPY = 4;
535    static final int INIT_COPY = 5;
536    static final int MCS_UNBIND = 6;
537    static final int START_CLEANING_PACKAGE = 7;
538    static final int FIND_INSTALL_LOC = 8;
539    static final int POST_INSTALL = 9;
540    static final int MCS_RECONNECT = 10;
541    static final int MCS_GIVE_UP = 11;
542    static final int UPDATED_MEDIA_STATUS = 12;
543    static final int WRITE_SETTINGS = 13;
544    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
545    static final int PACKAGE_VERIFIED = 15;
546    static final int CHECK_PENDING_VERIFICATION = 16;
547
548    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
549
550    // Delay time in millisecs
551    static final int BROADCAST_DELAY = 10 * 1000;
552
553    static UserManagerService sUserManager;
554
555    // Stores a list of users whose package restrictions file needs to be updated
556    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
557
558    final private DefaultContainerConnection mDefContainerConn =
559            new DefaultContainerConnection();
560    class DefaultContainerConnection implements ServiceConnection {
561        public void onServiceConnected(ComponentName name, IBinder service) {
562            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
563            IMediaContainerService imcs =
564                IMediaContainerService.Stub.asInterface(service);
565            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
566        }
567
568        public void onServiceDisconnected(ComponentName name) {
569            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
570        }
571    };
572
573    // Recordkeeping of restore-after-install operations that are currently in flight
574    // between the Package Manager and the Backup Manager
575    class PostInstallData {
576        public InstallArgs args;
577        public PackageInstalledInfo res;
578
579        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
580            args = _a;
581            res = _r;
582        }
583    };
584    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
585    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
586
587    private final String mRequiredVerifierPackage;
588
589    class PackageHandler extends Handler {
590        private boolean mBound = false;
591        final ArrayList<HandlerParams> mPendingInstalls =
592            new ArrayList<HandlerParams>();
593
594        private boolean connectToService() {
595            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
596                    " DefaultContainerService");
597            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
598            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
599            if (mContext.bindServiceAsUser(service, mDefContainerConn,
600                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
601                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
602                mBound = true;
603                return true;
604            }
605            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
606            return false;
607        }
608
609        private void disconnectService() {
610            mContainerService = null;
611            mBound = false;
612            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
613            mContext.unbindService(mDefContainerConn);
614            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
615        }
616
617        PackageHandler(Looper looper) {
618            super(looper);
619        }
620
621        public void handleMessage(Message msg) {
622            try {
623                doHandleMessage(msg);
624            } finally {
625                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
626            }
627        }
628
629        void doHandleMessage(Message msg) {
630            switch (msg.what) {
631                case INIT_COPY: {
632                    HandlerParams params = (HandlerParams) msg.obj;
633                    int idx = mPendingInstalls.size();
634                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
635                    // If a bind was already initiated we dont really
636                    // need to do anything. The pending install
637                    // will be processed later on.
638                    if (!mBound) {
639                        // If this is the only one pending we might
640                        // have to bind to the service again.
641                        if (!connectToService()) {
642                            Slog.e(TAG, "Failed to bind to media container service");
643                            params.serviceError();
644                            return;
645                        } else {
646                            // Once we bind to the service, the first
647                            // pending request will be processed.
648                            mPendingInstalls.add(idx, params);
649                        }
650                    } else {
651                        mPendingInstalls.add(idx, params);
652                        // Already bound to the service. Just make
653                        // sure we trigger off processing the first request.
654                        if (idx == 0) {
655                            mHandler.sendEmptyMessage(MCS_BOUND);
656                        }
657                    }
658                    break;
659                }
660                case MCS_BOUND: {
661                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
662                    if (msg.obj != null) {
663                        mContainerService = (IMediaContainerService) msg.obj;
664                    }
665                    if (mContainerService == null) {
666                        // Something seriously wrong. Bail out
667                        Slog.e(TAG, "Cannot bind to media container service");
668                        for (HandlerParams params : mPendingInstalls) {
669                            // Indicate service bind error
670                            params.serviceError();
671                        }
672                        mPendingInstalls.clear();
673                    } else if (mPendingInstalls.size() > 0) {
674                        HandlerParams params = mPendingInstalls.get(0);
675                        if (params != null) {
676                            if (params.startCopy()) {
677                                // We are done...  look for more work or to
678                                // go idle.
679                                if (DEBUG_SD_INSTALL) Log.i(TAG,
680                                        "Checking for more work or unbind...");
681                                // Delete pending install
682                                if (mPendingInstalls.size() > 0) {
683                                    mPendingInstalls.remove(0);
684                                }
685                                if (mPendingInstalls.size() == 0) {
686                                    if (mBound) {
687                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
688                                                "Posting delayed MCS_UNBIND");
689                                        removeMessages(MCS_UNBIND);
690                                        Message ubmsg = obtainMessage(MCS_UNBIND);
691                                        // Unbind after a little delay, to avoid
692                                        // continual thrashing.
693                                        sendMessageDelayed(ubmsg, 10000);
694                                    }
695                                } else {
696                                    // There are more pending requests in queue.
697                                    // Just post MCS_BOUND message to trigger processing
698                                    // of next pending install.
699                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
700                                            "Posting MCS_BOUND for next woek");
701                                    mHandler.sendEmptyMessage(MCS_BOUND);
702                                }
703                            }
704                        }
705                    } else {
706                        // Should never happen ideally.
707                        Slog.w(TAG, "Empty queue");
708                    }
709                    break;
710                }
711                case MCS_RECONNECT: {
712                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
713                    if (mPendingInstalls.size() > 0) {
714                        if (mBound) {
715                            disconnectService();
716                        }
717                        if (!connectToService()) {
718                            Slog.e(TAG, "Failed to bind to media container service");
719                            for (HandlerParams params : mPendingInstalls) {
720                                // Indicate service bind error
721                                params.serviceError();
722                            }
723                            mPendingInstalls.clear();
724                        }
725                    }
726                    break;
727                }
728                case MCS_UNBIND: {
729                    // If there is no actual work left, then time to unbind.
730                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
731
732                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
733                        if (mBound) {
734                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
735
736                            disconnectService();
737                        }
738                    } else if (mPendingInstalls.size() > 0) {
739                        // There are more pending requests in queue.
740                        // Just post MCS_BOUND message to trigger processing
741                        // of next pending install.
742                        mHandler.sendEmptyMessage(MCS_BOUND);
743                    }
744
745                    break;
746                }
747                case MCS_GIVE_UP: {
748                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
749                    mPendingInstalls.remove(0);
750                    break;
751                }
752                case SEND_PENDING_BROADCAST: {
753                    String packages[];
754                    ArrayList<String> components[];
755                    int size = 0;
756                    int uids[];
757                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
758                    synchronized (mPackages) {
759                        if (mPendingBroadcasts == null) {
760                            return;
761                        }
762                        size = mPendingBroadcasts.size();
763                        if (size <= 0) {
764                            // Nothing to be done. Just return
765                            return;
766                        }
767                        packages = new String[size];
768                        components = new ArrayList[size];
769                        uids = new int[size];
770                        int i = 0;  // filling out the above arrays
771
772                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
773                            int packageUserId = mPendingBroadcasts.userIdAt(n);
774                            Iterator<Map.Entry<String, ArrayList<String>>> it
775                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
776                                            .entrySet().iterator();
777                            while (it.hasNext() && i < size) {
778                                Map.Entry<String, ArrayList<String>> ent = it.next();
779                                packages[i] = ent.getKey();
780                                components[i] = ent.getValue();
781                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
782                                uids[i] = (ps != null)
783                                        ? UserHandle.getUid(packageUserId, ps.appId)
784                                        : -1;
785                                i++;
786                            }
787                        }
788                        size = i;
789                        mPendingBroadcasts.clear();
790                    }
791                    // Send broadcasts
792                    for (int i = 0; i < size; i++) {
793                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
794                    }
795                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
796                    break;
797                }
798                case START_CLEANING_PACKAGE: {
799                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
800                    final String packageName = (String)msg.obj;
801                    final int userId = msg.arg1;
802                    final boolean andCode = msg.arg2 != 0;
803                    synchronized (mPackages) {
804                        if (userId == UserHandle.USER_ALL) {
805                            int[] users = sUserManager.getUserIds();
806                            for (int user : users) {
807                                mSettings.addPackageToCleanLPw(
808                                        new PackageCleanItem(user, packageName, andCode));
809                            }
810                        } else {
811                            mSettings.addPackageToCleanLPw(
812                                    new PackageCleanItem(userId, packageName, andCode));
813                        }
814                    }
815                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
816                    startCleaningPackages();
817                } break;
818                case POST_INSTALL: {
819                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
820                    PostInstallData data = mRunningInstalls.get(msg.arg1);
821                    mRunningInstalls.delete(msg.arg1);
822                    boolean deleteOld = false;
823
824                    if (data != null) {
825                        InstallArgs args = data.args;
826                        PackageInstalledInfo res = data.res;
827
828                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
829                            res.removedInfo.sendBroadcast(false, true, false);
830                            Bundle extras = new Bundle(1);
831                            extras.putInt(Intent.EXTRA_UID, res.uid);
832                            // Determine the set of users who are adding this
833                            // package for the first time vs. those who are seeing
834                            // an update.
835                            int[] firstUsers;
836                            int[] updateUsers = new int[0];
837                            if (res.origUsers == null || res.origUsers.length == 0) {
838                                firstUsers = res.newUsers;
839                            } else {
840                                firstUsers = new int[0];
841                                for (int i=0; i<res.newUsers.length; i++) {
842                                    int user = res.newUsers[i];
843                                    boolean isNew = true;
844                                    for (int j=0; j<res.origUsers.length; j++) {
845                                        if (res.origUsers[j] == user) {
846                                            isNew = false;
847                                            break;
848                                        }
849                                    }
850                                    if (isNew) {
851                                        int[] newFirst = new int[firstUsers.length+1];
852                                        System.arraycopy(firstUsers, 0, newFirst, 0,
853                                                firstUsers.length);
854                                        newFirst[firstUsers.length] = user;
855                                        firstUsers = newFirst;
856                                    } else {
857                                        int[] newUpdate = new int[updateUsers.length+1];
858                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
859                                                updateUsers.length);
860                                        newUpdate[updateUsers.length] = user;
861                                        updateUsers = newUpdate;
862                                    }
863                                }
864                            }
865                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
866                                    res.pkg.applicationInfo.packageName,
867                                    extras, null, null, firstUsers);
868                            final boolean update = res.removedInfo.removedPackage != null;
869                            if (update) {
870                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
871                            }
872                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
873                                    res.pkg.applicationInfo.packageName,
874                                    extras, null, null, updateUsers);
875                            if (update) {
876                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
877                                        res.pkg.applicationInfo.packageName,
878                                        extras, null, null, updateUsers);
879                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
880                                        null, null,
881                                        res.pkg.applicationInfo.packageName, null, updateUsers);
882
883                                // treat asec-hosted packages like removable media on upgrade
884                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
885                                    if (DEBUG_INSTALL) {
886                                        Slog.i(TAG, "upgrading pkg " + res.pkg
887                                                + " is ASEC-hosted -> AVAILABLE");
888                                    }
889                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
890                                    ArrayList<String> pkgList = new ArrayList<String>(1);
891                                    pkgList.add(res.pkg.applicationInfo.packageName);
892                                    sendResourcesChangedBroadcast(true, true,
893                                            pkgList,uidArray, null);
894                                }
895                            }
896                            if (res.removedInfo.args != null) {
897                                // Remove the replaced package's older resources safely now
898                                deleteOld = true;
899                            }
900
901                            // Log current value of "unknown sources" setting
902                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
903                                getUnknownSourcesSettings());
904                        }
905                        // Force a gc to clear up things
906                        Runtime.getRuntime().gc();
907                        // We delete after a gc for applications  on sdcard.
908                        if (deleteOld) {
909                            synchronized (mInstallLock) {
910                                res.removedInfo.args.doPostDeleteLI(true);
911                            }
912                        }
913                        if (args.observer != null) {
914                            try {
915                                args.observer.packageInstalled(res.name, res.returnCode);
916                            } catch (RemoteException e) {
917                                Slog.i(TAG, "Observer no longer exists.");
918                            }
919                        }
920                    } else {
921                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
922                    }
923                } break;
924                case UPDATED_MEDIA_STATUS: {
925                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
926                    boolean reportStatus = msg.arg1 == 1;
927                    boolean doGc = msg.arg2 == 1;
928                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
929                    if (doGc) {
930                        // Force a gc to clear up stale containers.
931                        Runtime.getRuntime().gc();
932                    }
933                    if (msg.obj != null) {
934                        @SuppressWarnings("unchecked")
935                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
936                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
937                        // Unload containers
938                        unloadAllContainers(args);
939                    }
940                    if (reportStatus) {
941                        try {
942                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
943                            PackageHelper.getMountService().finishMediaUpdate();
944                        } catch (RemoteException e) {
945                            Log.e(TAG, "MountService not running?");
946                        }
947                    }
948                } break;
949                case WRITE_SETTINGS: {
950                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
951                    synchronized (mPackages) {
952                        removeMessages(WRITE_SETTINGS);
953                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
954                        mSettings.writeLPr();
955                        mDirtyUsers.clear();
956                    }
957                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
958                } break;
959                case WRITE_PACKAGE_RESTRICTIONS: {
960                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
961                    synchronized (mPackages) {
962                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
963                        for (int userId : mDirtyUsers) {
964                            mSettings.writePackageRestrictionsLPr(userId);
965                        }
966                        mDirtyUsers.clear();
967                    }
968                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
969                } break;
970                case CHECK_PENDING_VERIFICATION: {
971                    final int verificationId = msg.arg1;
972                    final PackageVerificationState state = mPendingVerification.get(verificationId);
973
974                    if ((state != null) && !state.timeoutExtended()) {
975                        final InstallArgs args = state.getInstallArgs();
976                        Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
977                        mPendingVerification.remove(verificationId);
978
979                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
980
981                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
982                            Slog.i(TAG, "Continuing with installation of "
983                                    + args.packageURI.toString());
984                            state.setVerifierResponse(Binder.getCallingUid(),
985                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
986                            broadcastPackageVerified(verificationId, args.packageURI,
987                                    PackageManager.VERIFICATION_ALLOW,
988                                    state.getInstallArgs().getUser());
989                            try {
990                                ret = args.copyApk(mContainerService, true);
991                            } catch (RemoteException e) {
992                                Slog.e(TAG, "Could not contact the ContainerService");
993                            }
994                        } else {
995                            broadcastPackageVerified(verificationId, args.packageURI,
996                                    PackageManager.VERIFICATION_REJECT,
997                                    state.getInstallArgs().getUser());
998                        }
999
1000                        processPendingInstall(args, ret);
1001                        mHandler.sendEmptyMessage(MCS_UNBIND);
1002                    }
1003                    break;
1004                }
1005                case PACKAGE_VERIFIED: {
1006                    final int verificationId = msg.arg1;
1007
1008                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1009                    if (state == null) {
1010                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1011                        break;
1012                    }
1013
1014                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1015
1016                    state.setVerifierResponse(response.callerUid, response.code);
1017
1018                    if (state.isVerificationComplete()) {
1019                        mPendingVerification.remove(verificationId);
1020
1021                        final InstallArgs args = state.getInstallArgs();
1022
1023                        int ret;
1024                        if (state.isInstallAllowed()) {
1025                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1026                            broadcastPackageVerified(verificationId, args.packageURI,
1027                                    response.code, state.getInstallArgs().getUser());
1028                            try {
1029                                ret = args.copyApk(mContainerService, true);
1030                            } catch (RemoteException e) {
1031                                Slog.e(TAG, "Could not contact the ContainerService");
1032                            }
1033                        } else {
1034                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1035                        }
1036
1037                        processPendingInstall(args, ret);
1038
1039                        mHandler.sendEmptyMessage(MCS_UNBIND);
1040                    }
1041
1042                    break;
1043                }
1044            }
1045        }
1046    }
1047
1048    void scheduleWriteSettingsLocked() {
1049        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1050            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1051        }
1052    }
1053
1054    void scheduleWritePackageRestrictionsLocked(int userId) {
1055        if (!sUserManager.exists(userId)) return;
1056        mDirtyUsers.add(userId);
1057        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1058            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1059        }
1060    }
1061
1062    public static final IPackageManager main(Context context, Installer installer,
1063            boolean factoryTest, boolean onlyCore) {
1064        PackageManagerService m = new PackageManagerService(context, installer,
1065                factoryTest, onlyCore);
1066        ServiceManager.addService("package", m);
1067        return m;
1068    }
1069
1070    static String[] splitString(String str, char sep) {
1071        int count = 1;
1072        int i = 0;
1073        while ((i=str.indexOf(sep, i)) >= 0) {
1074            count++;
1075            i++;
1076        }
1077
1078        String[] res = new String[count];
1079        i=0;
1080        count = 0;
1081        int lastI=0;
1082        while ((i=str.indexOf(sep, i)) >= 0) {
1083            res[count] = str.substring(lastI, i);
1084            count++;
1085            i++;
1086            lastI = i;
1087        }
1088        res[count] = str.substring(lastI, str.length());
1089        return res;
1090    }
1091
1092    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1093        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1094                Context.DISPLAY_SERVICE);
1095        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1096    }
1097
1098    public PackageManagerService(Context context, Installer installer,
1099            boolean factoryTest, boolean onlyCore) {
1100        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1101                SystemClock.uptimeMillis());
1102
1103        if (mSdkVersion <= 0) {
1104            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1105        }
1106
1107        mContext = context;
1108        mFactoryTest = factoryTest;
1109        mOnlyCore = onlyCore;
1110        mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1111        mMetrics = new DisplayMetrics();
1112        mSettings = new Settings(context);
1113        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1114                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1115        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1116                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1117        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1118                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1119        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1120                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1121        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1122                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1123        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1124                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1125
1126        String separateProcesses = SystemProperties.get("debug.separate_processes");
1127        if (separateProcesses != null && separateProcesses.length() > 0) {
1128            if ("*".equals(separateProcesses)) {
1129                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1130                mSeparateProcesses = null;
1131                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1132            } else {
1133                mDefParseFlags = 0;
1134                mSeparateProcesses = separateProcesses.split(",");
1135                Slog.w(TAG, "Running with debug.separate_processes: "
1136                        + separateProcesses);
1137            }
1138        } else {
1139            mDefParseFlags = 0;
1140            mSeparateProcesses = null;
1141        }
1142
1143        mInstaller = installer;
1144
1145        getDefaultDisplayMetrics(context, mMetrics);
1146
1147        synchronized (mInstallLock) {
1148        // writer
1149        synchronized (mPackages) {
1150            mHandlerThread = new ServiceThread(TAG,
1151                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1152            mHandlerThread.start();
1153            mHandler = new PackageHandler(mHandlerThread.getLooper());
1154            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1155
1156            File dataDir = Environment.getDataDirectory();
1157            mAppDataDir = new File(dataDir, "data");
1158            mAppInstallDir = new File(dataDir, "app");
1159            mAppLibInstallDir = new File(dataDir, "app-lib");
1160            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1161            mUserAppDataDir = new File(dataDir, "user");
1162            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1163
1164            sUserManager = new UserManagerService(context, this,
1165                    mInstallLock, mPackages);
1166
1167            readPermissions();
1168
1169            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1170
1171            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1172                    mSdkVersion, mOnlyCore);
1173
1174            String customResolverActivity = Resources.getSystem().getString(
1175                    R.string.config_customResolverActivity);
1176            if (TextUtils.isEmpty(customResolverActivity)) {
1177                customResolverActivity = null;
1178            } else {
1179                mCustomResolverComponentName = ComponentName.unflattenFromString(
1180                        customResolverActivity);
1181            }
1182
1183            long startTime = SystemClock.uptimeMillis();
1184
1185            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1186                    startTime);
1187
1188            // Set flag to monitor and not change apk file paths when
1189            // scanning install directories.
1190            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1191            if (mNoDexOpt) {
1192                Slog.w(TAG, "Running ENG build: no pre-dexopt!");
1193                scanMode |= SCAN_NO_DEX;
1194            }
1195
1196            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1197
1198            /**
1199             * Add everything in the in the boot class path to the
1200             * list of process files because dexopt will have been run
1201             * if necessary during zygote startup.
1202             */
1203            String bootClassPath = System.getProperty("java.boot.class.path");
1204            if (bootClassPath != null) {
1205                String[] paths = splitString(bootClassPath, ':');
1206                for (int i=0; i<paths.length; i++) {
1207                    alreadyDexOpted.add(paths[i]);
1208                }
1209            } else {
1210                Slog.w(TAG, "No BOOTCLASSPATH found!");
1211            }
1212
1213            boolean didDexOpt = false;
1214
1215            final List<String> instructionSets = getAllInstructionSets();
1216
1217            /**
1218             * Ensure all external libraries have had dexopt run on them.
1219             */
1220            if (mSharedLibraries.size() > 0) {
1221                // NOTE: For now, we're compiling these system "shared libraries"
1222                // (and framework jars) into all available architectures. It's possible
1223                // to compile them only when we come across an app that uses them (there's
1224                // already logic for that in scanPackageLI) but that adds some complexity.
1225                for (String instructionSet : instructionSets) {
1226                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1227                        final String lib = libEntry.path;
1228                        if (lib == null) {
1229                            continue;
1230                        }
1231
1232                        try {
1233                            if (dalvik.system.DexFile.isDexOptNeededInternal(
1234                                    lib, null, instructionSet, false)) {
1235                                alreadyDexOpted.add(lib);
1236
1237                                // The list of "shared libraries" we have at this point is
1238                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1239                                didDexOpt = true;
1240                            }
1241                        } catch (FileNotFoundException e) {
1242                            Slog.w(TAG, "Library not found: " + lib);
1243                        } catch (IOException e) {
1244                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1245                                    + e.getMessage());
1246                        }
1247                    }
1248                }
1249            }
1250
1251            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1252
1253            // Gross hack for now: we know this file doesn't contain any
1254            // code, so don't dexopt it to avoid the resulting log spew.
1255            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1256
1257            // Gross hack for now: we know this file is only part of
1258            // the boot class path for art, so don't dexopt it to
1259            // avoid the resulting log spew.
1260            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1261
1262            /**
1263             * And there are a number of commands implemented in Java, which
1264             * we currently need to do the dexopt on so that they can be
1265             * run from a non-root shell.
1266             */
1267            String[] frameworkFiles = frameworkDir.list();
1268            if (frameworkFiles != null) {
1269                // TODO: We could compile these only for the most preferred ABI. We should
1270                // first double check that the dex files for these commands are not referenced
1271                // by other system apps.
1272                for (String instructionSet : instructionSets) {
1273                    for (int i=0; i<frameworkFiles.length; i++) {
1274                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1275                        String path = libPath.getPath();
1276                        // Skip the file if we already did it.
1277                        if (alreadyDexOpted.contains(path)) {
1278                            continue;
1279                        }
1280                        // Skip the file if it is not a type we want to dexopt.
1281                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1282                            continue;
1283                        }
1284                        try {
1285                            if (dalvik.system.DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1286                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1287                                didDexOpt = true;
1288                            }
1289                        } catch (FileNotFoundException e) {
1290                            Slog.w(TAG, "Jar not found: " + path);
1291                        } catch (IOException e) {
1292                            Slog.w(TAG, "Exception reading jar: " + path, e);
1293                        }
1294                    }
1295                }
1296            }
1297
1298            if (didDexOpt) {
1299                File dalvikCacheDir = new File(dataDir, "dalvik-cache");
1300
1301                // If we had to do a dexopt of one of the previous
1302                // things, then something on the system has changed.
1303                // Consider this significant, and wipe away all other
1304                // existing dexopt files to ensure we don't leave any
1305                // dangling around.
1306                String[] files = dalvikCacheDir.list();
1307                if (files != null) {
1308                    for (int i=0; i<files.length; i++) {
1309                        String fn = files[i];
1310                        if (fn.startsWith("data@app@")
1311                                || fn.startsWith("data@app-private@")) {
1312                            Slog.i(TAG, "Pruning dalvik file: " + fn);
1313                            (new File(dalvikCacheDir, fn)).delete();
1314                        }
1315                    }
1316                }
1317            }
1318
1319            // Collect vendor overlay packages.
1320            // (Do this before scanning any apps.)
1321            // For security and version matching reason, only consider
1322            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1323            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1324            mVendorOverlayInstallObserver = new AppDirObserver(
1325                vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1326            mVendorOverlayInstallObserver.startWatching();
1327            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1328                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1329
1330            // Find base frameworks (resource packages without code).
1331            mFrameworkInstallObserver = new AppDirObserver(
1332                frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1333            mFrameworkInstallObserver.startWatching();
1334            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1335                    | PackageParser.PARSE_IS_SYSTEM_DIR
1336                    | PackageParser.PARSE_IS_PRIVILEGED,
1337                    scanMode | SCAN_NO_DEX, 0);
1338
1339            // Collected privileged system packages.
1340            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1341            mPrivilegedInstallObserver = new AppDirObserver(
1342                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1343            mPrivilegedInstallObserver.startWatching();
1344                scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1345                        | PackageParser.PARSE_IS_SYSTEM_DIR
1346                        | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1347
1348            // Collect ordinary system packages.
1349            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1350            mSystemInstallObserver = new AppDirObserver(
1351                systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1352            mSystemInstallObserver.startWatching();
1353            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1354                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1355
1356            // Collect all vendor packages.
1357            File vendorAppDir = new File("/vendor/app");
1358            try {
1359                vendorAppDir = vendorAppDir.getCanonicalFile();
1360            } catch (IOException e) {
1361                // failed to look up canonical path, continue with original one
1362            }
1363            mVendorInstallObserver = new AppDirObserver(
1364                vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1365            mVendorInstallObserver.startWatching();
1366            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1367                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1368
1369            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1370            mInstaller.moveFiles();
1371
1372            // Prune any system packages that no longer exist.
1373            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1374            if (!mOnlyCore) {
1375                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1376                while (psit.hasNext()) {
1377                    PackageSetting ps = psit.next();
1378
1379                    /*
1380                     * If this is not a system app, it can't be a
1381                     * disable system app.
1382                     */
1383                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1384                        continue;
1385                    }
1386
1387                    /*
1388                     * If the package is scanned, it's not erased.
1389                     */
1390                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1391                    if (scannedPkg != null) {
1392                        /*
1393                         * If the system app is both scanned and in the
1394                         * disabled packages list, then it must have been
1395                         * added via OTA. Remove it from the currently
1396                         * scanned package so the previously user-installed
1397                         * application can be scanned.
1398                         */
1399                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1400                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1401                                    + "; removing system app");
1402                            removePackageLI(ps, true);
1403                        }
1404
1405                        continue;
1406                    }
1407
1408                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1409                        psit.remove();
1410                        String msg = "System package " + ps.name
1411                                + " no longer exists; wiping its data";
1412                        reportSettingsProblem(Log.WARN, msg);
1413                        removeDataDirsLI(ps.name);
1414                    } else {
1415                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1416                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1417                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1418                        }
1419                    }
1420                }
1421            }
1422
1423            //look for any incomplete package installations
1424            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1425            //clean up list
1426            for(int i = 0; i < deletePkgsList.size(); i++) {
1427                //clean up here
1428                cleanupInstallFailedPackage(deletePkgsList.get(i));
1429            }
1430            //delete tmp files
1431            deleteTempPackageFiles();
1432
1433            // Remove any shared userIDs that have no associated packages
1434            mSettings.pruneSharedUsersLPw();
1435
1436            if (!mOnlyCore) {
1437                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1438                        SystemClock.uptimeMillis());
1439                mAppInstallObserver = new AppDirObserver(
1440                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1441                mAppInstallObserver.startWatching();
1442                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1443
1444                mDrmAppInstallObserver = new AppDirObserver(
1445                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1446                mDrmAppInstallObserver.startWatching();
1447                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1448                        scanMode, 0);
1449
1450                /**
1451                 * Remove disable package settings for any updated system
1452                 * apps that were removed via an OTA. If they're not a
1453                 * previously-updated app, remove them completely.
1454                 * Otherwise, just revoke their system-level permissions.
1455                 */
1456                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1457                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1458                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1459
1460                    String msg;
1461                    if (deletedPkg == null) {
1462                        msg = "Updated system package " + deletedAppName
1463                                + " no longer exists; wiping its data";
1464                        removeDataDirsLI(deletedAppName);
1465                    } else {
1466                        msg = "Updated system app + " + deletedAppName
1467                                + " no longer present; removing system privileges for "
1468                                + deletedAppName;
1469
1470                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1471
1472                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1473                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1474                    }
1475                    reportSettingsProblem(Log.WARN, msg);
1476                }
1477            } else {
1478                mAppInstallObserver = null;
1479                mDrmAppInstallObserver = null;
1480            }
1481
1482            // Now that we know all of the shared libraries, update all clients to have
1483            // the correct library paths.
1484            updateAllSharedLibrariesLPw();
1485
1486            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1487                    SystemClock.uptimeMillis());
1488            Slog.i(TAG, "Time to scan packages: "
1489                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1490                    + " seconds");
1491
1492            // If the platform SDK has changed since the last time we booted,
1493            // we need to re-grant app permission to catch any new ones that
1494            // appear.  This is really a hack, and means that apps can in some
1495            // cases get permissions that the user didn't initially explicitly
1496            // allow...  it would be nice to have some better way to handle
1497            // this situation.
1498            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1499                    != mSdkVersion;
1500            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1501                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1502                    + "; regranting permissions for internal storage");
1503            mSettings.mInternalSdkPlatform = mSdkVersion;
1504
1505            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1506                    | (regrantPermissions
1507                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1508                            : 0));
1509
1510            // If this is the first boot, and it is a normal boot, then
1511            // we need to initialize the default preferred apps.
1512            if (!mRestoredSettings && !onlyCore) {
1513                mSettings.readDefaultPreferredAppsLPw(this, 0);
1514            }
1515
1516            // can downgrade to reader
1517            mSettings.writeLPr();
1518
1519            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1520                    SystemClock.uptimeMillis());
1521
1522            // Now after opening every single application zip, make sure they
1523            // are all flushed.  Not really needed, but keeps things nice and
1524            // tidy.
1525            Runtime.getRuntime().gc();
1526
1527            mRequiredVerifierPackage = getRequiredVerifierLPr();
1528        } // synchronized (mPackages)
1529        } // synchronized (mInstallLock)
1530    }
1531
1532    public boolean isFirstBoot() {
1533        return !mRestoredSettings;
1534    }
1535
1536    public boolean isOnlyCoreApps() {
1537        return mOnlyCore;
1538    }
1539
1540    private String getRequiredVerifierLPr() {
1541        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1542        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1543                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1544
1545        String requiredVerifier = null;
1546
1547        final int N = receivers.size();
1548        for (int i = 0; i < N; i++) {
1549            final ResolveInfo info = receivers.get(i);
1550
1551            if (info.activityInfo == null) {
1552                continue;
1553            }
1554
1555            final String packageName = info.activityInfo.packageName;
1556
1557            final PackageSetting ps = mSettings.mPackages.get(packageName);
1558            if (ps == null) {
1559                continue;
1560            }
1561
1562            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1563            if (!gp.grantedPermissions
1564                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1565                continue;
1566            }
1567
1568            if (requiredVerifier != null) {
1569                throw new RuntimeException("There can be only one required verifier");
1570            }
1571
1572            requiredVerifier = packageName;
1573        }
1574
1575        return requiredVerifier;
1576    }
1577
1578    @Override
1579    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1580            throws RemoteException {
1581        try {
1582            return super.onTransact(code, data, reply, flags);
1583        } catch (RuntimeException e) {
1584            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1585                Slog.wtf(TAG, "Package Manager Crash", e);
1586            }
1587            throw e;
1588        }
1589    }
1590
1591    void cleanupInstallFailedPackage(PackageSetting ps) {
1592        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1593        removeDataDirsLI(ps.name);
1594        if (ps.codePath != null) {
1595            if (!ps.codePath.delete()) {
1596                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1597            }
1598        }
1599        if (ps.resourcePath != null) {
1600            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1601                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1602            }
1603        }
1604        mSettings.removePackageLPw(ps.name);
1605    }
1606
1607    void readPermissions() {
1608        // Read permissions from .../etc/permission directory.
1609        File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1610        if (!libraryDir.exists() || !libraryDir.isDirectory()) {
1611            Slog.w(TAG, "No directory " + libraryDir + ", skipping");
1612            return;
1613        }
1614        if (!libraryDir.canRead()) {
1615            Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
1616            return;
1617        }
1618
1619        // Iterate over the files in the directory and scan .xml files
1620        for (File f : libraryDir.listFiles()) {
1621            // We'll read platform.xml last
1622            if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1623                continue;
1624            }
1625
1626            if (!f.getPath().endsWith(".xml")) {
1627                Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
1628                continue;
1629            }
1630            if (!f.canRead()) {
1631                Slog.w(TAG, "Permissions library file " + f + " cannot be read");
1632                continue;
1633            }
1634
1635            readPermissionsFromXml(f);
1636        }
1637
1638        // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1639        final File permFile = new File(Environment.getRootDirectory(),
1640                "etc/permissions/platform.xml");
1641        readPermissionsFromXml(permFile);
1642    }
1643
1644    private void readPermissionsFromXml(File permFile) {
1645        FileReader permReader = null;
1646        try {
1647            permReader = new FileReader(permFile);
1648        } catch (FileNotFoundException e) {
1649            Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
1650            return;
1651        }
1652
1653        try {
1654            XmlPullParser parser = Xml.newPullParser();
1655            parser.setInput(permReader);
1656
1657            XmlUtils.beginDocument(parser, "permissions");
1658
1659            while (true) {
1660                XmlUtils.nextElement(parser);
1661                if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1662                    break;
1663                }
1664
1665                String name = parser.getName();
1666                if ("group".equals(name)) {
1667                    String gidStr = parser.getAttributeValue(null, "gid");
1668                    if (gidStr != null) {
1669                        int gid = Process.getGidForName(gidStr);
1670                        mGlobalGids = appendInt(mGlobalGids, gid);
1671                    } else {
1672                        Slog.w(TAG, "<group> without gid at "
1673                                + parser.getPositionDescription());
1674                    }
1675
1676                    XmlUtils.skipCurrentTag(parser);
1677                    continue;
1678                } else if ("permission".equals(name)) {
1679                    String perm = parser.getAttributeValue(null, "name");
1680                    if (perm == null) {
1681                        Slog.w(TAG, "<permission> without name at "
1682                                + parser.getPositionDescription());
1683                        XmlUtils.skipCurrentTag(parser);
1684                        continue;
1685                    }
1686                    perm = perm.intern();
1687                    readPermission(parser, perm);
1688
1689                } else if ("assign-permission".equals(name)) {
1690                    String perm = parser.getAttributeValue(null, "name");
1691                    if (perm == null) {
1692                        Slog.w(TAG, "<assign-permission> without name at "
1693                                + parser.getPositionDescription());
1694                        XmlUtils.skipCurrentTag(parser);
1695                        continue;
1696                    }
1697                    String uidStr = parser.getAttributeValue(null, "uid");
1698                    if (uidStr == null) {
1699                        Slog.w(TAG, "<assign-permission> without uid at "
1700                                + parser.getPositionDescription());
1701                        XmlUtils.skipCurrentTag(parser);
1702                        continue;
1703                    }
1704                    int uid = Process.getUidForName(uidStr);
1705                    if (uid < 0) {
1706                        Slog.w(TAG, "<assign-permission> with unknown uid \""
1707                                + uidStr + "\" at "
1708                                + parser.getPositionDescription());
1709                        XmlUtils.skipCurrentTag(parser);
1710                        continue;
1711                    }
1712                    perm = perm.intern();
1713                    HashSet<String> perms = mSystemPermissions.get(uid);
1714                    if (perms == null) {
1715                        perms = new HashSet<String>();
1716                        mSystemPermissions.put(uid, perms);
1717                    }
1718                    perms.add(perm);
1719                    XmlUtils.skipCurrentTag(parser);
1720
1721                } else if ("library".equals(name)) {
1722                    String lname = parser.getAttributeValue(null, "name");
1723                    String lfile = parser.getAttributeValue(null, "file");
1724                    if (lname == null) {
1725                        Slog.w(TAG, "<library> without name at "
1726                                + parser.getPositionDescription());
1727                    } else if (lfile == null) {
1728                        Slog.w(TAG, "<library> without file at "
1729                                + parser.getPositionDescription());
1730                    } else {
1731                        //Log.i(TAG, "Got library " + lname + " in " + lfile);
1732                        mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null));
1733                    }
1734                    XmlUtils.skipCurrentTag(parser);
1735                    continue;
1736
1737                } else if ("feature".equals(name)) {
1738                    String fname = parser.getAttributeValue(null, "name");
1739                    if (fname == null) {
1740                        Slog.w(TAG, "<feature> without name at "
1741                                + parser.getPositionDescription());
1742                    } else {
1743                        //Log.i(TAG, "Got feature " + fname);
1744                        FeatureInfo fi = new FeatureInfo();
1745                        fi.name = fname;
1746                        mAvailableFeatures.put(fname, fi);
1747                    }
1748                    XmlUtils.skipCurrentTag(parser);
1749                    continue;
1750
1751                } else {
1752                    XmlUtils.skipCurrentTag(parser);
1753                    continue;
1754                }
1755
1756            }
1757            permReader.close();
1758        } catch (XmlPullParserException e) {
1759            Slog.w(TAG, "Got execption parsing permissions.", e);
1760        } catch (IOException e) {
1761            Slog.w(TAG, "Got execption parsing permissions.", e);
1762        }
1763    }
1764
1765    void readPermission(XmlPullParser parser, String name)
1766            throws IOException, XmlPullParserException {
1767
1768        name = name.intern();
1769
1770        BasePermission bp = mSettings.mPermissions.get(name);
1771        if (bp == null) {
1772            bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1773            mSettings.mPermissions.put(name, bp);
1774        }
1775        int outerDepth = parser.getDepth();
1776        int type;
1777        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1778               && (type != XmlPullParser.END_TAG
1779                       || parser.getDepth() > outerDepth)) {
1780            if (type == XmlPullParser.END_TAG
1781                    || type == XmlPullParser.TEXT) {
1782                continue;
1783            }
1784
1785            String tagName = parser.getName();
1786            if ("group".equals(tagName)) {
1787                String gidStr = parser.getAttributeValue(null, "gid");
1788                if (gidStr != null) {
1789                    int gid = Process.getGidForName(gidStr);
1790                    bp.gids = appendInt(bp.gids, gid);
1791                } else {
1792                    Slog.w(TAG, "<group> without gid at "
1793                            + parser.getPositionDescription());
1794                }
1795            }
1796            XmlUtils.skipCurrentTag(parser);
1797        }
1798    }
1799
1800    static int[] appendInts(int[] cur, int[] add) {
1801        if (add == null) return cur;
1802        if (cur == null) return add;
1803        final int N = add.length;
1804        for (int i=0; i<N; i++) {
1805            cur = appendInt(cur, add[i]);
1806        }
1807        return cur;
1808    }
1809
1810    static int[] removeInts(int[] cur, int[] rem) {
1811        if (rem == null) return cur;
1812        if (cur == null) return cur;
1813        final int N = rem.length;
1814        for (int i=0; i<N; i++) {
1815            cur = removeInt(cur, rem[i]);
1816        }
1817        return cur;
1818    }
1819
1820    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1821        if (!sUserManager.exists(userId)) return null;
1822        final PackageSetting ps = (PackageSetting) p.mExtras;
1823        if (ps == null) {
1824            return null;
1825        }
1826        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1827        final PackageUserState state = ps.readUserState(userId);
1828        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1829                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1830                state, userId);
1831    }
1832
1833    public boolean isPackageAvailable(String packageName, int userId) {
1834        if (!sUserManager.exists(userId)) return false;
1835        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1836        synchronized (mPackages) {
1837            PackageParser.Package p = mPackages.get(packageName);
1838            if (p != null) {
1839                final PackageSetting ps = (PackageSetting) p.mExtras;
1840                if (ps != null) {
1841                    final PackageUserState state = ps.readUserState(userId);
1842                    if (state != null) {
1843                        return PackageParser.isAvailable(state);
1844                    }
1845                }
1846            }
1847        }
1848        return false;
1849    }
1850
1851    @Override
1852    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1853        if (!sUserManager.exists(userId)) return null;
1854        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1855        // reader
1856        synchronized (mPackages) {
1857            PackageParser.Package p = mPackages.get(packageName);
1858            if (DEBUG_PACKAGE_INFO)
1859                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1860            if (p != null) {
1861                return generatePackageInfo(p, flags, userId);
1862            }
1863            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1864                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1865            }
1866        }
1867        return null;
1868    }
1869
1870    public String[] currentToCanonicalPackageNames(String[] names) {
1871        String[] out = new String[names.length];
1872        // reader
1873        synchronized (mPackages) {
1874            for (int i=names.length-1; i>=0; i--) {
1875                PackageSetting ps = mSettings.mPackages.get(names[i]);
1876                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1877            }
1878        }
1879        return out;
1880    }
1881
1882    public String[] canonicalToCurrentPackageNames(String[] names) {
1883        String[] out = new String[names.length];
1884        // reader
1885        synchronized (mPackages) {
1886            for (int i=names.length-1; i>=0; i--) {
1887                String cur = mSettings.mRenamedPackages.get(names[i]);
1888                out[i] = cur != null ? cur : names[i];
1889            }
1890        }
1891        return out;
1892    }
1893
1894    @Override
1895    public int getPackageUid(String packageName, int userId) {
1896        if (!sUserManager.exists(userId)) return -1;
1897        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1898        // reader
1899        synchronized (mPackages) {
1900            PackageParser.Package p = mPackages.get(packageName);
1901            if(p != null) {
1902                return UserHandle.getUid(userId, p.applicationInfo.uid);
1903            }
1904            PackageSetting ps = mSettings.mPackages.get(packageName);
1905            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1906                return -1;
1907            }
1908            p = ps.pkg;
1909            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1910        }
1911    }
1912
1913    @Override
1914    public int[] getPackageGids(String packageName) {
1915        // reader
1916        synchronized (mPackages) {
1917            PackageParser.Package p = mPackages.get(packageName);
1918            if (DEBUG_PACKAGE_INFO)
1919                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1920            if (p != null) {
1921                final PackageSetting ps = (PackageSetting)p.mExtras;
1922                return ps.getGids();
1923            }
1924        }
1925        // stupid thing to indicate an error.
1926        return new int[0];
1927    }
1928
1929    static final PermissionInfo generatePermissionInfo(
1930            BasePermission bp, int flags) {
1931        if (bp.perm != null) {
1932            return PackageParser.generatePermissionInfo(bp.perm, flags);
1933        }
1934        PermissionInfo pi = new PermissionInfo();
1935        pi.name = bp.name;
1936        pi.packageName = bp.sourcePackage;
1937        pi.nonLocalizedLabel = bp.name;
1938        pi.protectionLevel = bp.protectionLevel;
1939        return pi;
1940    }
1941
1942    public PermissionInfo getPermissionInfo(String name, int flags) {
1943        // reader
1944        synchronized (mPackages) {
1945            final BasePermission p = mSettings.mPermissions.get(name);
1946            if (p != null) {
1947                return generatePermissionInfo(p, flags);
1948            }
1949            return null;
1950        }
1951    }
1952
1953    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1954        // reader
1955        synchronized (mPackages) {
1956            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1957            for (BasePermission p : mSettings.mPermissions.values()) {
1958                if (group == null) {
1959                    if (p.perm == null || p.perm.info.group == null) {
1960                        out.add(generatePermissionInfo(p, flags));
1961                    }
1962                } else {
1963                    if (p.perm != null && group.equals(p.perm.info.group)) {
1964                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1965                    }
1966                }
1967            }
1968
1969            if (out.size() > 0) {
1970                return out;
1971            }
1972            return mPermissionGroups.containsKey(group) ? out : null;
1973        }
1974    }
1975
1976    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1977        // reader
1978        synchronized (mPackages) {
1979            return PackageParser.generatePermissionGroupInfo(
1980                    mPermissionGroups.get(name), flags);
1981        }
1982    }
1983
1984    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1985        // reader
1986        synchronized (mPackages) {
1987            final int N = mPermissionGroups.size();
1988            ArrayList<PermissionGroupInfo> out
1989                    = new ArrayList<PermissionGroupInfo>(N);
1990            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1991                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1992            }
1993            return out;
1994        }
1995    }
1996
1997    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
1998            int userId) {
1999        if (!sUserManager.exists(userId)) return null;
2000        PackageSetting ps = mSettings.mPackages.get(packageName);
2001        if (ps != null) {
2002            if (ps.pkg == null) {
2003                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2004                        flags, userId);
2005                if (pInfo != null) {
2006                    return pInfo.applicationInfo;
2007                }
2008                return null;
2009            }
2010            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2011                    ps.readUserState(userId), userId);
2012        }
2013        return null;
2014    }
2015
2016    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2017            int userId) {
2018        if (!sUserManager.exists(userId)) return null;
2019        PackageSetting ps = mSettings.mPackages.get(packageName);
2020        if (ps != null) {
2021            PackageParser.Package pkg = ps.pkg;
2022            if (pkg == null) {
2023                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2024                    return null;
2025                }
2026                pkg = new PackageParser.Package(packageName);
2027                pkg.applicationInfo.packageName = packageName;
2028                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2029                pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
2030                pkg.applicationInfo.sourceDir = ps.codePathString;
2031                pkg.applicationInfo.dataDir =
2032                        getDataPathForPackage(packageName, 0).getPath();
2033                pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
2034                pkg.applicationInfo.requiredCpuAbi = ps.requiredCpuAbiString;
2035            }
2036            return generatePackageInfo(pkg, flags, userId);
2037        }
2038        return null;
2039    }
2040
2041    @Override
2042    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2043        if (!sUserManager.exists(userId)) return null;
2044        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2045        // writer
2046        synchronized (mPackages) {
2047            PackageParser.Package p = mPackages.get(packageName);
2048            if (DEBUG_PACKAGE_INFO) Log.v(
2049                    TAG, "getApplicationInfo " + packageName
2050                    + ": " + p);
2051            if (p != null) {
2052                PackageSetting ps = mSettings.mPackages.get(packageName);
2053                if (ps == null) return null;
2054                // Note: isEnabledLP() does not apply here - always return info
2055                return PackageParser.generateApplicationInfo(
2056                        p, flags, ps.readUserState(userId), userId);
2057            }
2058            if ("android".equals(packageName)||"system".equals(packageName)) {
2059                return mAndroidApplication;
2060            }
2061            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2062                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2063            }
2064        }
2065        return null;
2066    }
2067
2068
2069    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2070        mContext.enforceCallingOrSelfPermission(
2071                android.Manifest.permission.CLEAR_APP_CACHE, null);
2072        // Queue up an async operation since clearing cache may take a little while.
2073        mHandler.post(new Runnable() {
2074            public void run() {
2075                mHandler.removeCallbacks(this);
2076                int retCode = -1;
2077                synchronized (mInstallLock) {
2078                    retCode = mInstaller.freeCache(freeStorageSize);
2079                    if (retCode < 0) {
2080                        Slog.w(TAG, "Couldn't clear application caches");
2081                    }
2082                }
2083                if (observer != null) {
2084                    try {
2085                        observer.onRemoveCompleted(null, (retCode >= 0));
2086                    } catch (RemoteException e) {
2087                        Slog.w(TAG, "RemoveException when invoking call back");
2088                    }
2089                }
2090            }
2091        });
2092    }
2093
2094    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2095        mContext.enforceCallingOrSelfPermission(
2096                android.Manifest.permission.CLEAR_APP_CACHE, null);
2097        // Queue up an async operation since clearing cache may take a little while.
2098        mHandler.post(new Runnable() {
2099            public void run() {
2100                mHandler.removeCallbacks(this);
2101                int retCode = -1;
2102                synchronized (mInstallLock) {
2103                    retCode = mInstaller.freeCache(freeStorageSize);
2104                    if (retCode < 0) {
2105                        Slog.w(TAG, "Couldn't clear application caches");
2106                    }
2107                }
2108                if(pi != null) {
2109                    try {
2110                        // Callback via pending intent
2111                        int code = (retCode >= 0) ? 1 : 0;
2112                        pi.sendIntent(null, code, null,
2113                                null, null);
2114                    } catch (SendIntentException e1) {
2115                        Slog.i(TAG, "Failed to send pending intent");
2116                    }
2117                }
2118            }
2119        });
2120    }
2121
2122    @Override
2123    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2124        if (!sUserManager.exists(userId)) return null;
2125        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2126        synchronized (mPackages) {
2127            PackageParser.Activity a = mActivities.mActivities.get(component);
2128
2129            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2130            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2131                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2132                if (ps == null) return null;
2133                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2134                        userId);
2135            }
2136            if (mResolveComponentName.equals(component)) {
2137                return mResolveActivity;
2138            }
2139        }
2140        return null;
2141    }
2142
2143    @Override
2144    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2145        if (!sUserManager.exists(userId)) return null;
2146        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2147        synchronized (mPackages) {
2148            PackageParser.Activity a = mReceivers.mActivities.get(component);
2149            if (DEBUG_PACKAGE_INFO) Log.v(
2150                TAG, "getReceiverInfo " + component + ": " + a);
2151            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2152                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2153                if (ps == null) return null;
2154                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2155                        userId);
2156            }
2157        }
2158        return null;
2159    }
2160
2161    @Override
2162    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2163        if (!sUserManager.exists(userId)) return null;
2164        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2165        synchronized (mPackages) {
2166            PackageParser.Service s = mServices.mServices.get(component);
2167            if (DEBUG_PACKAGE_INFO) Log.v(
2168                TAG, "getServiceInfo " + component + ": " + s);
2169            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2170                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2171                if (ps == null) return null;
2172                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2173                        userId);
2174            }
2175        }
2176        return null;
2177    }
2178
2179    @Override
2180    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2181        if (!sUserManager.exists(userId)) return null;
2182        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2183        synchronized (mPackages) {
2184            PackageParser.Provider p = mProviders.mProviders.get(component);
2185            if (DEBUG_PACKAGE_INFO) Log.v(
2186                TAG, "getProviderInfo " + component + ": " + p);
2187            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2188                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2189                if (ps == null) return null;
2190                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2191                        userId);
2192            }
2193        }
2194        return null;
2195    }
2196
2197    public String[] getSystemSharedLibraryNames() {
2198        Set<String> libSet;
2199        synchronized (mPackages) {
2200            libSet = mSharedLibraries.keySet();
2201            int size = libSet.size();
2202            if (size > 0) {
2203                String[] libs = new String[size];
2204                libSet.toArray(libs);
2205                return libs;
2206            }
2207        }
2208        return null;
2209    }
2210
2211    public FeatureInfo[] getSystemAvailableFeatures() {
2212        Collection<FeatureInfo> featSet;
2213        synchronized (mPackages) {
2214            featSet = mAvailableFeatures.values();
2215            int size = featSet.size();
2216            if (size > 0) {
2217                FeatureInfo[] features = new FeatureInfo[size+1];
2218                featSet.toArray(features);
2219                FeatureInfo fi = new FeatureInfo();
2220                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2221                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2222                features[size] = fi;
2223                return features;
2224            }
2225        }
2226        return null;
2227    }
2228
2229    public boolean hasSystemFeature(String name) {
2230        synchronized (mPackages) {
2231            return mAvailableFeatures.containsKey(name);
2232        }
2233    }
2234
2235    private void checkValidCaller(int uid, int userId) {
2236        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2237            return;
2238
2239        throw new SecurityException("Caller uid=" + uid
2240                + " is not privileged to communicate with user=" + userId);
2241    }
2242
2243    public int checkPermission(String permName, String pkgName) {
2244        synchronized (mPackages) {
2245            PackageParser.Package p = mPackages.get(pkgName);
2246            if (p != null && p.mExtras != null) {
2247                PackageSetting ps = (PackageSetting)p.mExtras;
2248                if (ps.sharedUser != null) {
2249                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2250                        return PackageManager.PERMISSION_GRANTED;
2251                    }
2252                } else if (ps.grantedPermissions.contains(permName)) {
2253                    return PackageManager.PERMISSION_GRANTED;
2254                }
2255            }
2256        }
2257        return PackageManager.PERMISSION_DENIED;
2258    }
2259
2260    public int checkUidPermission(String permName, int uid) {
2261        synchronized (mPackages) {
2262            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2263            if (obj != null) {
2264                GrantedPermissions gp = (GrantedPermissions)obj;
2265                if (gp.grantedPermissions.contains(permName)) {
2266                    return PackageManager.PERMISSION_GRANTED;
2267                }
2268            } else {
2269                HashSet<String> perms = mSystemPermissions.get(uid);
2270                if (perms != null && perms.contains(permName)) {
2271                    return PackageManager.PERMISSION_GRANTED;
2272                }
2273            }
2274        }
2275        return PackageManager.PERMISSION_DENIED;
2276    }
2277
2278    /**
2279     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2280     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2281     * @param message the message to log on security exception
2282     * @return
2283     */
2284    private void enforceCrossUserPermission(int callingUid, int userId,
2285            boolean requireFullPermission, String message) {
2286        if (userId < 0) {
2287            throw new IllegalArgumentException("Invalid userId " + userId);
2288        }
2289        if (userId == UserHandle.getUserId(callingUid)) return;
2290        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2291            if (requireFullPermission) {
2292                mContext.enforceCallingOrSelfPermission(
2293                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2294            } else {
2295                try {
2296                    mContext.enforceCallingOrSelfPermission(
2297                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2298                } catch (SecurityException se) {
2299                    mContext.enforceCallingOrSelfPermission(
2300                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2301                }
2302            }
2303        }
2304    }
2305
2306    private BasePermission findPermissionTreeLP(String permName) {
2307        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2308            if (permName.startsWith(bp.name) &&
2309                    permName.length() > bp.name.length() &&
2310                    permName.charAt(bp.name.length()) == '.') {
2311                return bp;
2312            }
2313        }
2314        return null;
2315    }
2316
2317    private BasePermission checkPermissionTreeLP(String permName) {
2318        if (permName != null) {
2319            BasePermission bp = findPermissionTreeLP(permName);
2320            if (bp != null) {
2321                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2322                    return bp;
2323                }
2324                throw new SecurityException("Calling uid "
2325                        + Binder.getCallingUid()
2326                        + " is not allowed to add to permission tree "
2327                        + bp.name + " owned by uid " + bp.uid);
2328            }
2329        }
2330        throw new SecurityException("No permission tree found for " + permName);
2331    }
2332
2333    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2334        if (s1 == null) {
2335            return s2 == null;
2336        }
2337        if (s2 == null) {
2338            return false;
2339        }
2340        if (s1.getClass() != s2.getClass()) {
2341            return false;
2342        }
2343        return s1.equals(s2);
2344    }
2345
2346    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2347        if (pi1.icon != pi2.icon) return false;
2348        if (pi1.logo != pi2.logo) return false;
2349        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2350        if (!compareStrings(pi1.name, pi2.name)) return false;
2351        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2352        // We'll take care of setting this one.
2353        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2354        // These are not currently stored in settings.
2355        //if (!compareStrings(pi1.group, pi2.group)) return false;
2356        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2357        //if (pi1.labelRes != pi2.labelRes) return false;
2358        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2359        return true;
2360    }
2361
2362    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2363        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2364            throw new SecurityException("Label must be specified in permission");
2365        }
2366        BasePermission tree = checkPermissionTreeLP(info.name);
2367        BasePermission bp = mSettings.mPermissions.get(info.name);
2368        boolean added = bp == null;
2369        boolean changed = true;
2370        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2371        if (added) {
2372            bp = new BasePermission(info.name, tree.sourcePackage,
2373                    BasePermission.TYPE_DYNAMIC);
2374        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2375            throw new SecurityException(
2376                    "Not allowed to modify non-dynamic permission "
2377                    + info.name);
2378        } else {
2379            if (bp.protectionLevel == fixedLevel
2380                    && bp.perm.owner.equals(tree.perm.owner)
2381                    && bp.uid == tree.uid
2382                    && comparePermissionInfos(bp.perm.info, info)) {
2383                changed = false;
2384            }
2385        }
2386        bp.protectionLevel = fixedLevel;
2387        info = new PermissionInfo(info);
2388        info.protectionLevel = fixedLevel;
2389        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2390        bp.perm.info.packageName = tree.perm.info.packageName;
2391        bp.uid = tree.uid;
2392        if (added) {
2393            mSettings.mPermissions.put(info.name, bp);
2394        }
2395        if (changed) {
2396            if (!async) {
2397                mSettings.writeLPr();
2398            } else {
2399                scheduleWriteSettingsLocked();
2400            }
2401        }
2402        return added;
2403    }
2404
2405    public boolean addPermission(PermissionInfo info) {
2406        synchronized (mPackages) {
2407            return addPermissionLocked(info, false);
2408        }
2409    }
2410
2411    public boolean addPermissionAsync(PermissionInfo info) {
2412        synchronized (mPackages) {
2413            return addPermissionLocked(info, true);
2414        }
2415    }
2416
2417    public void removePermission(String name) {
2418        synchronized (mPackages) {
2419            checkPermissionTreeLP(name);
2420            BasePermission bp = mSettings.mPermissions.get(name);
2421            if (bp != null) {
2422                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2423                    throw new SecurityException(
2424                            "Not allowed to modify non-dynamic permission "
2425                            + name);
2426                }
2427                mSettings.mPermissions.remove(name);
2428                mSettings.writeLPr();
2429            }
2430        }
2431    }
2432
2433    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2434        int index = pkg.requestedPermissions.indexOf(bp.name);
2435        if (index == -1) {
2436            throw new SecurityException("Package " + pkg.packageName
2437                    + " has not requested permission " + bp.name);
2438        }
2439        boolean isNormal =
2440                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2441                        == PermissionInfo.PROTECTION_NORMAL);
2442        boolean isDangerous =
2443                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2444                        == PermissionInfo.PROTECTION_DANGEROUS);
2445        boolean isDevelopment =
2446                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2447
2448        if (!isNormal && !isDangerous && !isDevelopment) {
2449            throw new SecurityException("Permission " + bp.name
2450                    + " is not a changeable permission type");
2451        }
2452
2453        if (isNormal || isDangerous) {
2454            if (pkg.requestedPermissionsRequired.get(index)) {
2455                throw new SecurityException("Can't change " + bp.name
2456                        + ". It is required by the application");
2457            }
2458        }
2459    }
2460
2461    public void grantPermission(String packageName, String permissionName) {
2462        mContext.enforceCallingOrSelfPermission(
2463                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2464        synchronized (mPackages) {
2465            final PackageParser.Package pkg = mPackages.get(packageName);
2466            if (pkg == null) {
2467                throw new IllegalArgumentException("Unknown package: " + packageName);
2468            }
2469            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2470            if (bp == null) {
2471                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2472            }
2473
2474            checkGrantRevokePermissions(pkg, bp);
2475
2476            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2477            if (ps == null) {
2478                return;
2479            }
2480            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2481            if (gp.grantedPermissions.add(permissionName)) {
2482                if (ps.haveGids) {
2483                    gp.gids = appendInts(gp.gids, bp.gids);
2484                }
2485                mSettings.writeLPr();
2486            }
2487        }
2488    }
2489
2490    public void revokePermission(String packageName, String permissionName) {
2491        int changedAppId = -1;
2492
2493        synchronized (mPackages) {
2494            final PackageParser.Package pkg = mPackages.get(packageName);
2495            if (pkg == null) {
2496                throw new IllegalArgumentException("Unknown package: " + packageName);
2497            }
2498            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2499                mContext.enforceCallingOrSelfPermission(
2500                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2501            }
2502            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2503            if (bp == null) {
2504                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2505            }
2506
2507            checkGrantRevokePermissions(pkg, bp);
2508
2509            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2510            if (ps == null) {
2511                return;
2512            }
2513            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2514            if (gp.grantedPermissions.remove(permissionName)) {
2515                gp.grantedPermissions.remove(permissionName);
2516                if (ps.haveGids) {
2517                    gp.gids = removeInts(gp.gids, bp.gids);
2518                }
2519                mSettings.writeLPr();
2520                changedAppId = ps.appId;
2521            }
2522        }
2523
2524        if (changedAppId >= 0) {
2525            // We changed the perm on someone, kill its processes.
2526            IActivityManager am = ActivityManagerNative.getDefault();
2527            if (am != null) {
2528                final int callingUserId = UserHandle.getCallingUserId();
2529                final long ident = Binder.clearCallingIdentity();
2530                try {
2531                    //XXX we should only revoke for the calling user's app permissions,
2532                    // but for now we impact all users.
2533                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2534                    //        "revoke " + permissionName);
2535                    int[] users = sUserManager.getUserIds();
2536                    for (int user : users) {
2537                        am.killUid(UserHandle.getUid(user, changedAppId),
2538                                "revoke " + permissionName);
2539                    }
2540                } catch (RemoteException e) {
2541                } finally {
2542                    Binder.restoreCallingIdentity(ident);
2543                }
2544            }
2545        }
2546    }
2547
2548    public boolean isProtectedBroadcast(String actionName) {
2549        synchronized (mPackages) {
2550            return mProtectedBroadcasts.contains(actionName);
2551        }
2552    }
2553
2554    public int checkSignatures(String pkg1, String pkg2) {
2555        synchronized (mPackages) {
2556            final PackageParser.Package p1 = mPackages.get(pkg1);
2557            final PackageParser.Package p2 = mPackages.get(pkg2);
2558            if (p1 == null || p1.mExtras == null
2559                    || p2 == null || p2.mExtras == null) {
2560                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2561            }
2562            return compareSignatures(p1.mSignatures, p2.mSignatures);
2563        }
2564    }
2565
2566    public int checkUidSignatures(int uid1, int uid2) {
2567        // Map to base uids.
2568        uid1 = UserHandle.getAppId(uid1);
2569        uid2 = UserHandle.getAppId(uid2);
2570        // reader
2571        synchronized (mPackages) {
2572            Signature[] s1;
2573            Signature[] s2;
2574            Object obj = mSettings.getUserIdLPr(uid1);
2575            if (obj != null) {
2576                if (obj instanceof SharedUserSetting) {
2577                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2578                } else if (obj instanceof PackageSetting) {
2579                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2580                } else {
2581                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2582                }
2583            } else {
2584                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2585            }
2586            obj = mSettings.getUserIdLPr(uid2);
2587            if (obj != null) {
2588                if (obj instanceof SharedUserSetting) {
2589                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2590                } else if (obj instanceof PackageSetting) {
2591                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2592                } else {
2593                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2594                }
2595            } else {
2596                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2597            }
2598            return compareSignatures(s1, s2);
2599        }
2600    }
2601
2602    /**
2603     * Compares two sets of signatures. Returns:
2604     * <br />
2605     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2606     * <br />
2607     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2608     * <br />
2609     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2610     * <br />
2611     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2612     * <br />
2613     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2614     */
2615    static int compareSignatures(Signature[] s1, Signature[] s2) {
2616        if (s1 == null) {
2617            return s2 == null
2618                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2619                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2620        }
2621
2622        if (s2 == null) {
2623            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2624        }
2625
2626        if (s1.length != s2.length) {
2627            return PackageManager.SIGNATURE_NO_MATCH;
2628        }
2629
2630        // Since both signature sets are of size 1, we can compare without HashSets.
2631        if (s1.length == 1) {
2632            return s1[0].equals(s2[0]) ?
2633                    PackageManager.SIGNATURE_MATCH :
2634                    PackageManager.SIGNATURE_NO_MATCH;
2635        }
2636
2637        HashSet<Signature> set1 = new HashSet<Signature>();
2638        for (Signature sig : s1) {
2639            set1.add(sig);
2640        }
2641        HashSet<Signature> set2 = new HashSet<Signature>();
2642        for (Signature sig : s2) {
2643            set2.add(sig);
2644        }
2645        // Make sure s2 contains all signatures in s1.
2646        if (set1.equals(set2)) {
2647            return PackageManager.SIGNATURE_MATCH;
2648        }
2649        return PackageManager.SIGNATURE_NO_MATCH;
2650    }
2651
2652    public String[] getPackagesForUid(int uid) {
2653        uid = UserHandle.getAppId(uid);
2654        // reader
2655        synchronized (mPackages) {
2656            Object obj = mSettings.getUserIdLPr(uid);
2657            if (obj instanceof SharedUserSetting) {
2658                final SharedUserSetting sus = (SharedUserSetting) obj;
2659                final int N = sus.packages.size();
2660                final String[] res = new String[N];
2661                final Iterator<PackageSetting> it = sus.packages.iterator();
2662                int i = 0;
2663                while (it.hasNext()) {
2664                    res[i++] = it.next().name;
2665                }
2666                return res;
2667            } else if (obj instanceof PackageSetting) {
2668                final PackageSetting ps = (PackageSetting) obj;
2669                return new String[] { ps.name };
2670            }
2671        }
2672        return null;
2673    }
2674
2675    public String getNameForUid(int uid) {
2676        // reader
2677        synchronized (mPackages) {
2678            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2679            if (obj instanceof SharedUserSetting) {
2680                final SharedUserSetting sus = (SharedUserSetting) obj;
2681                return sus.name + ":" + sus.userId;
2682            } else if (obj instanceof PackageSetting) {
2683                final PackageSetting ps = (PackageSetting) obj;
2684                return ps.name;
2685            }
2686        }
2687        return null;
2688    }
2689
2690    public int getUidForSharedUser(String sharedUserName) {
2691        if(sharedUserName == null) {
2692            return -1;
2693        }
2694        // reader
2695        synchronized (mPackages) {
2696            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2697            if (suid == null) {
2698                return -1;
2699            }
2700            return suid.userId;
2701        }
2702    }
2703
2704    public int getFlagsForUid(int uid) {
2705        synchronized (mPackages) {
2706            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2707            if (obj instanceof SharedUserSetting) {
2708                final SharedUserSetting sus = (SharedUserSetting) obj;
2709                return sus.pkgFlags;
2710            } else if (obj instanceof PackageSetting) {
2711                final PackageSetting ps = (PackageSetting) obj;
2712                return ps.pkgFlags;
2713            }
2714        }
2715        return 0;
2716    }
2717
2718    @Override
2719    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2720            int flags, int userId) {
2721        if (!sUserManager.exists(userId)) return null;
2722        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2723        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2724        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2725    }
2726
2727    @Override
2728    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2729            IntentFilter filter, int match, ComponentName activity) {
2730        final int userId = UserHandle.getCallingUserId();
2731        if (DEBUG_PREFERRED) {
2732            Log.v(TAG, "setLastChosenActivity intent=" + intent
2733                + " resolvedType=" + resolvedType
2734                + " flags=" + flags
2735                + " filter=" + filter
2736                + " match=" + match
2737                + " activity=" + activity);
2738            filter.dump(new PrintStreamPrinter(System.out), "    ");
2739        }
2740        intent.setComponent(null);
2741        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2742        // Find any earlier preferred or last chosen entries and nuke them
2743        findPreferredActivity(intent, resolvedType,
2744                flags, query, 0, false, true, false, userId);
2745        // Add the new activity as the last chosen for this filter
2746        addPreferredActivityInternal(filter, match, null, activity, false, userId);
2747    }
2748
2749    @Override
2750    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2751        final int userId = UserHandle.getCallingUserId();
2752        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2753        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2754        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2755                false, false, false, userId);
2756    }
2757
2758    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2759            int flags, List<ResolveInfo> query, int userId) {
2760        if (query != null) {
2761            final int N = query.size();
2762            if (N == 1) {
2763                return query.get(0);
2764            } else if (N > 1) {
2765                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2766                // If there is more than one activity with the same priority,
2767                // then let the user decide between them.
2768                ResolveInfo r0 = query.get(0);
2769                ResolveInfo r1 = query.get(1);
2770                if (DEBUG_INTENT_MATCHING || debug) {
2771                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2772                            + r1.activityInfo.name + "=" + r1.priority);
2773                }
2774                // If the first activity has a higher priority, or a different
2775                // default, then it is always desireable to pick it.
2776                if (r0.priority != r1.priority
2777                        || r0.preferredOrder != r1.preferredOrder
2778                        || r0.isDefault != r1.isDefault) {
2779                    return query.get(0);
2780                }
2781                // If we have saved a preference for a preferred activity for
2782                // this Intent, use that.
2783                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2784                        flags, query, r0.priority, true, false, debug, userId);
2785                if (ri != null) {
2786                    return ri;
2787                }
2788                if (userId != 0) {
2789                    ri = new ResolveInfo(mResolveInfo);
2790                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2791                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2792                            ri.activityInfo.applicationInfo);
2793                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2794                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2795                    return ri;
2796                }
2797                return mResolveInfo;
2798            }
2799        }
2800        return null;
2801    }
2802
2803    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
2804            List<ResolveInfo> query, int priority, boolean always,
2805            boolean removeMatches, boolean debug, int userId) {
2806        if (!sUserManager.exists(userId)) return null;
2807        // writer
2808        synchronized (mPackages) {
2809            if (intent.getSelector() != null) {
2810                intent = intent.getSelector();
2811            }
2812            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
2813            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
2814            // Get the list of preferred activities that handle the intent
2815            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
2816            List<PreferredActivity> prefs = pir != null
2817                    ? pir.queryIntent(intent, resolvedType,
2818                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2819                    : null;
2820            if (prefs != null && prefs.size() > 0) {
2821                // First figure out how good the original match set is.
2822                // We will only allow preferred activities that came
2823                // from the same match quality.
2824                int match = 0;
2825
2826                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
2827
2828                final int N = query.size();
2829                for (int j=0; j<N; j++) {
2830                    final ResolveInfo ri = query.get(j);
2831                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
2832                            + ": 0x" + Integer.toHexString(match));
2833                    if (ri.match > match) {
2834                        match = ri.match;
2835                    }
2836                }
2837
2838                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
2839                        + Integer.toHexString(match));
2840
2841                match &= IntentFilter.MATCH_CATEGORY_MASK;
2842                final int M = prefs.size();
2843                for (int i=0; i<M; i++) {
2844                    final PreferredActivity pa = prefs.get(i);
2845                    if (DEBUG_PREFERRED || debug) {
2846                        Slog.v(TAG, "Checking PreferredActivity ds="
2847                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
2848                                + "\n  component=" + pa.mPref.mComponent);
2849                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2850                    }
2851                    if (pa.mPref.mMatch != match) {
2852                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
2853                                + Integer.toHexString(pa.mPref.mMatch));
2854                        continue;
2855                    }
2856                    // If it's not an "always" type preferred activity and that's what we're
2857                    // looking for, skip it.
2858                    if (always && !pa.mPref.mAlways) {
2859                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
2860                        continue;
2861                    }
2862                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
2863                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
2864                    if (DEBUG_PREFERRED || debug) {
2865                        Slog.v(TAG, "Found preferred activity:");
2866                        if (ai != null) {
2867                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2868                        } else {
2869                            Slog.v(TAG, "  null");
2870                        }
2871                    }
2872                    if (ai == null) {
2873                        // This previously registered preferred activity
2874                        // component is no longer known.  Most likely an update
2875                        // to the app was installed and in the new version this
2876                        // component no longer exists.  Clean it up by removing
2877                        // it from the preferred activities list, and skip it.
2878                        Slog.w(TAG, "Removing dangling preferred activity: "
2879                                + pa.mPref.mComponent);
2880                        pir.removeFilter(pa);
2881                        continue;
2882                    }
2883                    for (int j=0; j<N; j++) {
2884                        final ResolveInfo ri = query.get(j);
2885                        if (!ri.activityInfo.applicationInfo.packageName
2886                                .equals(ai.applicationInfo.packageName)) {
2887                            continue;
2888                        }
2889                        if (!ri.activityInfo.name.equals(ai.name)) {
2890                            continue;
2891                        }
2892
2893                        if (removeMatches) {
2894                            pir.removeFilter(pa);
2895                            if (DEBUG_PREFERRED) {
2896                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
2897                            }
2898                            break;
2899                        }
2900
2901                        // Okay we found a previously set preferred or last chosen app.
2902                        // If the result set is different from when this
2903                        // was created, we need to clear it and re-ask the
2904                        // user their preference, if we're looking for an "always" type entry.
2905                        if (always && !pa.mPref.sameSet(query, priority)) {
2906                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
2907                                    + intent + " type " + resolvedType);
2908                            if (DEBUG_PREFERRED) {
2909                                Slog.v(TAG, "Removing preferred activity since set changed "
2910                                        + pa.mPref.mComponent);
2911                            }
2912                            pir.removeFilter(pa);
2913                            // Re-add the filter as a "last chosen" entry (!always)
2914                            PreferredActivity lastChosen = new PreferredActivity(
2915                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
2916                            pir.addFilter(lastChosen);
2917                            mSettings.writePackageRestrictionsLPr(userId);
2918                            return null;
2919                        }
2920
2921                        // Yay! Either the set matched or we're looking for the last chosen
2922                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
2923                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
2924                        mSettings.writePackageRestrictionsLPr(userId);
2925                        return ri;
2926                    }
2927                }
2928            }
2929            mSettings.writePackageRestrictionsLPr(userId);
2930        }
2931        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
2932        return null;
2933    }
2934
2935    @Override
2936    public List<ResolveInfo> queryIntentActivities(Intent intent,
2937            String resolvedType, int flags, int userId) {
2938        if (!sUserManager.exists(userId)) return Collections.emptyList();
2939        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
2940        ComponentName comp = intent.getComponent();
2941        if (comp == null) {
2942            if (intent.getSelector() != null) {
2943                intent = intent.getSelector();
2944                comp = intent.getComponent();
2945            }
2946        }
2947
2948        if (comp != null) {
2949            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2950            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
2951            if (ai != null) {
2952                final ResolveInfo ri = new ResolveInfo();
2953                ri.activityInfo = ai;
2954                list.add(ri);
2955            }
2956            return list;
2957        }
2958
2959        // reader
2960        synchronized (mPackages) {
2961            final String pkgName = intent.getPackage();
2962            if (pkgName == null) {
2963                return mActivities.queryIntent(intent, resolvedType, flags, userId);
2964            }
2965            final PackageParser.Package pkg = mPackages.get(pkgName);
2966            if (pkg != null) {
2967                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
2968                        pkg.activities, userId);
2969            }
2970            return new ArrayList<ResolveInfo>();
2971        }
2972    }
2973
2974    @Override
2975    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2976            Intent[] specifics, String[] specificTypes, Intent intent,
2977            String resolvedType, int flags, int userId) {
2978        if (!sUserManager.exists(userId)) return Collections.emptyList();
2979        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
2980                "query intent activity options");
2981        final String resultsAction = intent.getAction();
2982
2983        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
2984                | PackageManager.GET_RESOLVED_FILTER, userId);
2985
2986        if (DEBUG_INTENT_MATCHING) {
2987            Log.v(TAG, "Query " + intent + ": " + results);
2988        }
2989
2990        int specificsPos = 0;
2991        int N;
2992
2993        // todo: note that the algorithm used here is O(N^2).  This
2994        // isn't a problem in our current environment, but if we start running
2995        // into situations where we have more than 5 or 10 matches then this
2996        // should probably be changed to something smarter...
2997
2998        // First we go through and resolve each of the specific items
2999        // that were supplied, taking care of removing any corresponding
3000        // duplicate items in the generic resolve list.
3001        if (specifics != null) {
3002            for (int i=0; i<specifics.length; i++) {
3003                final Intent sintent = specifics[i];
3004                if (sintent == null) {
3005                    continue;
3006                }
3007
3008                if (DEBUG_INTENT_MATCHING) {
3009                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3010                }
3011
3012                String action = sintent.getAction();
3013                if (resultsAction != null && resultsAction.equals(action)) {
3014                    // If this action was explicitly requested, then don't
3015                    // remove things that have it.
3016                    action = null;
3017                }
3018
3019                ResolveInfo ri = null;
3020                ActivityInfo ai = null;
3021
3022                ComponentName comp = sintent.getComponent();
3023                if (comp == null) {
3024                    ri = resolveIntent(
3025                        sintent,
3026                        specificTypes != null ? specificTypes[i] : null,
3027                            flags, userId);
3028                    if (ri == null) {
3029                        continue;
3030                    }
3031                    if (ri == mResolveInfo) {
3032                        // ACK!  Must do something better with this.
3033                    }
3034                    ai = ri.activityInfo;
3035                    comp = new ComponentName(ai.applicationInfo.packageName,
3036                            ai.name);
3037                } else {
3038                    ai = getActivityInfo(comp, flags, userId);
3039                    if (ai == null) {
3040                        continue;
3041                    }
3042                }
3043
3044                // Look for any generic query activities that are duplicates
3045                // of this specific one, and remove them from the results.
3046                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3047                N = results.size();
3048                int j;
3049                for (j=specificsPos; j<N; j++) {
3050                    ResolveInfo sri = results.get(j);
3051                    if ((sri.activityInfo.name.equals(comp.getClassName())
3052                            && sri.activityInfo.applicationInfo.packageName.equals(
3053                                    comp.getPackageName()))
3054                        || (action != null && sri.filter.matchAction(action))) {
3055                        results.remove(j);
3056                        if (DEBUG_INTENT_MATCHING) Log.v(
3057                            TAG, "Removing duplicate item from " + j
3058                            + " due to specific " + specificsPos);
3059                        if (ri == null) {
3060                            ri = sri;
3061                        }
3062                        j--;
3063                        N--;
3064                    }
3065                }
3066
3067                // Add this specific item to its proper place.
3068                if (ri == null) {
3069                    ri = new ResolveInfo();
3070                    ri.activityInfo = ai;
3071                }
3072                results.add(specificsPos, ri);
3073                ri.specificIndex = i;
3074                specificsPos++;
3075            }
3076        }
3077
3078        // Now we go through the remaining generic results and remove any
3079        // duplicate actions that are found here.
3080        N = results.size();
3081        for (int i=specificsPos; i<N-1; i++) {
3082            final ResolveInfo rii = results.get(i);
3083            if (rii.filter == null) {
3084                continue;
3085            }
3086
3087            // Iterate over all of the actions of this result's intent
3088            // filter...  typically this should be just one.
3089            final Iterator<String> it = rii.filter.actionsIterator();
3090            if (it == null) {
3091                continue;
3092            }
3093            while (it.hasNext()) {
3094                final String action = it.next();
3095                if (resultsAction != null && resultsAction.equals(action)) {
3096                    // If this action was explicitly requested, then don't
3097                    // remove things that have it.
3098                    continue;
3099                }
3100                for (int j=i+1; j<N; j++) {
3101                    final ResolveInfo rij = results.get(j);
3102                    if (rij.filter != null && rij.filter.hasAction(action)) {
3103                        results.remove(j);
3104                        if (DEBUG_INTENT_MATCHING) Log.v(
3105                            TAG, "Removing duplicate item from " + j
3106                            + " due to action " + action + " at " + i);
3107                        j--;
3108                        N--;
3109                    }
3110                }
3111            }
3112
3113            // If the caller didn't request filter information, drop it now
3114            // so we don't have to marshall/unmarshall it.
3115            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3116                rii.filter = null;
3117            }
3118        }
3119
3120        // Filter out the caller activity if so requested.
3121        if (caller != null) {
3122            N = results.size();
3123            for (int i=0; i<N; i++) {
3124                ActivityInfo ainfo = results.get(i).activityInfo;
3125                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3126                        && caller.getClassName().equals(ainfo.name)) {
3127                    results.remove(i);
3128                    break;
3129                }
3130            }
3131        }
3132
3133        // If the caller didn't request filter information,
3134        // drop them now so we don't have to
3135        // marshall/unmarshall it.
3136        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3137            N = results.size();
3138            for (int i=0; i<N; i++) {
3139                results.get(i).filter = null;
3140            }
3141        }
3142
3143        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3144        return results;
3145    }
3146
3147    @Override
3148    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3149            int userId) {
3150        if (!sUserManager.exists(userId)) return Collections.emptyList();
3151        ComponentName comp = intent.getComponent();
3152        if (comp == null) {
3153            if (intent.getSelector() != null) {
3154                intent = intent.getSelector();
3155                comp = intent.getComponent();
3156            }
3157        }
3158        if (comp != null) {
3159            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3160            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3161            if (ai != null) {
3162                ResolveInfo ri = new ResolveInfo();
3163                ri.activityInfo = ai;
3164                list.add(ri);
3165            }
3166            return list;
3167        }
3168
3169        // reader
3170        synchronized (mPackages) {
3171            String pkgName = intent.getPackage();
3172            if (pkgName == null) {
3173                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3174            }
3175            final PackageParser.Package pkg = mPackages.get(pkgName);
3176            if (pkg != null) {
3177                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3178                        userId);
3179            }
3180            return null;
3181        }
3182    }
3183
3184    @Override
3185    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3186        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3187        if (!sUserManager.exists(userId)) return null;
3188        if (query != null) {
3189            if (query.size() >= 1) {
3190                // If there is more than one service with the same priority,
3191                // just arbitrarily pick the first one.
3192                return query.get(0);
3193            }
3194        }
3195        return null;
3196    }
3197
3198    @Override
3199    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3200            int userId) {
3201        if (!sUserManager.exists(userId)) return Collections.emptyList();
3202        ComponentName comp = intent.getComponent();
3203        if (comp == null) {
3204            if (intent.getSelector() != null) {
3205                intent = intent.getSelector();
3206                comp = intent.getComponent();
3207            }
3208        }
3209        if (comp != null) {
3210            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3211            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3212            if (si != null) {
3213                final ResolveInfo ri = new ResolveInfo();
3214                ri.serviceInfo = si;
3215                list.add(ri);
3216            }
3217            return list;
3218        }
3219
3220        // reader
3221        synchronized (mPackages) {
3222            String pkgName = intent.getPackage();
3223            if (pkgName == null) {
3224                return mServices.queryIntent(intent, resolvedType, flags, userId);
3225            }
3226            final PackageParser.Package pkg = mPackages.get(pkgName);
3227            if (pkg != null) {
3228                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3229                        userId);
3230            }
3231            return null;
3232        }
3233    }
3234
3235    @Override
3236    public List<ResolveInfo> queryIntentContentProviders(
3237            Intent intent, String resolvedType, int flags, int userId) {
3238        if (!sUserManager.exists(userId)) return Collections.emptyList();
3239        ComponentName comp = intent.getComponent();
3240        if (comp == null) {
3241            if (intent.getSelector() != null) {
3242                intent = intent.getSelector();
3243                comp = intent.getComponent();
3244            }
3245        }
3246        if (comp != null) {
3247            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3248            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3249            if (pi != null) {
3250                final ResolveInfo ri = new ResolveInfo();
3251                ri.providerInfo = pi;
3252                list.add(ri);
3253            }
3254            return list;
3255        }
3256
3257        // reader
3258        synchronized (mPackages) {
3259            String pkgName = intent.getPackage();
3260            if (pkgName == null) {
3261                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3262            }
3263            final PackageParser.Package pkg = mPackages.get(pkgName);
3264            if (pkg != null) {
3265                return mProviders.queryIntentForPackage(
3266                        intent, resolvedType, flags, pkg.providers, userId);
3267            }
3268            return null;
3269        }
3270    }
3271
3272    @Override
3273    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3274        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3275
3276        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3277
3278        // writer
3279        synchronized (mPackages) {
3280            ArrayList<PackageInfo> list;
3281            if (listUninstalled) {
3282                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3283                for (PackageSetting ps : mSettings.mPackages.values()) {
3284                    PackageInfo pi;
3285                    if (ps.pkg != null) {
3286                        pi = generatePackageInfo(ps.pkg, flags, userId);
3287                    } else {
3288                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3289                    }
3290                    if (pi != null) {
3291                        list.add(pi);
3292                    }
3293                }
3294            } else {
3295                list = new ArrayList<PackageInfo>(mPackages.size());
3296                for (PackageParser.Package p : mPackages.values()) {
3297                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3298                    if (pi != null) {
3299                        list.add(pi);
3300                    }
3301                }
3302            }
3303
3304            return new ParceledListSlice<PackageInfo>(list);
3305        }
3306    }
3307
3308    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3309            String[] permissions, boolean[] tmp, int flags, int userId) {
3310        int numMatch = 0;
3311        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3312        for (int i=0; i<permissions.length; i++) {
3313            if (gp.grantedPermissions.contains(permissions[i])) {
3314                tmp[i] = true;
3315                numMatch++;
3316            } else {
3317                tmp[i] = false;
3318            }
3319        }
3320        if (numMatch == 0) {
3321            return;
3322        }
3323        PackageInfo pi;
3324        if (ps.pkg != null) {
3325            pi = generatePackageInfo(ps.pkg, flags, userId);
3326        } else {
3327            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3328        }
3329        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3330            if (numMatch == permissions.length) {
3331                pi.requestedPermissions = permissions;
3332            } else {
3333                pi.requestedPermissions = new String[numMatch];
3334                numMatch = 0;
3335                for (int i=0; i<permissions.length; i++) {
3336                    if (tmp[i]) {
3337                        pi.requestedPermissions[numMatch] = permissions[i];
3338                        numMatch++;
3339                    }
3340                }
3341            }
3342        }
3343        list.add(pi);
3344    }
3345
3346    @Override
3347    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3348            String[] permissions, int flags, int userId) {
3349        if (!sUserManager.exists(userId)) return null;
3350        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3351
3352        // writer
3353        synchronized (mPackages) {
3354            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3355            boolean[] tmpBools = new boolean[permissions.length];
3356            if (listUninstalled) {
3357                for (PackageSetting ps : mSettings.mPackages.values()) {
3358                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3359                }
3360            } else {
3361                for (PackageParser.Package pkg : mPackages.values()) {
3362                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3363                    if (ps != null) {
3364                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3365                                userId);
3366                    }
3367                }
3368            }
3369
3370            return new ParceledListSlice<PackageInfo>(list);
3371        }
3372    }
3373
3374    @Override
3375    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3376        if (!sUserManager.exists(userId)) return null;
3377        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3378
3379        // writer
3380        synchronized (mPackages) {
3381            ArrayList<ApplicationInfo> list;
3382            if (listUninstalled) {
3383                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3384                for (PackageSetting ps : mSettings.mPackages.values()) {
3385                    ApplicationInfo ai;
3386                    if (ps.pkg != null) {
3387                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3388                                ps.readUserState(userId), userId);
3389                    } else {
3390                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3391                    }
3392                    if (ai != null) {
3393                        list.add(ai);
3394                    }
3395                }
3396            } else {
3397                list = new ArrayList<ApplicationInfo>(mPackages.size());
3398                for (PackageParser.Package p : mPackages.values()) {
3399                    if (p.mExtras != null) {
3400                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3401                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3402                        if (ai != null) {
3403                            list.add(ai);
3404                        }
3405                    }
3406                }
3407            }
3408
3409            return new ParceledListSlice<ApplicationInfo>(list);
3410        }
3411    }
3412
3413    public List<ApplicationInfo> getPersistentApplications(int flags) {
3414        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3415
3416        // reader
3417        synchronized (mPackages) {
3418            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3419            final int userId = UserHandle.getCallingUserId();
3420            while (i.hasNext()) {
3421                final PackageParser.Package p = i.next();
3422                if (p.applicationInfo != null
3423                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3424                        && (!mSafeMode || isSystemApp(p))) {
3425                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3426                    if (ps != null) {
3427                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3428                                ps.readUserState(userId), userId);
3429                        if (ai != null) {
3430                            finalList.add(ai);
3431                        }
3432                    }
3433                }
3434            }
3435        }
3436
3437        return finalList;
3438    }
3439
3440    @Override
3441    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3442        if (!sUserManager.exists(userId)) return null;
3443        // reader
3444        synchronized (mPackages) {
3445            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3446            PackageSetting ps = provider != null
3447                    ? mSettings.mPackages.get(provider.owner.packageName)
3448                    : null;
3449            return ps != null
3450                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3451                    && (!mSafeMode || (provider.info.applicationInfo.flags
3452                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3453                    ? PackageParser.generateProviderInfo(provider, flags,
3454                            ps.readUserState(userId), userId)
3455                    : null;
3456        }
3457    }
3458
3459    /**
3460     * @deprecated
3461     */
3462    @Deprecated
3463    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3464        // reader
3465        synchronized (mPackages) {
3466            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3467                    .entrySet().iterator();
3468            final int userId = UserHandle.getCallingUserId();
3469            while (i.hasNext()) {
3470                Map.Entry<String, PackageParser.Provider> entry = i.next();
3471                PackageParser.Provider p = entry.getValue();
3472                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3473
3474                if (ps != null && p.syncable
3475                        && (!mSafeMode || (p.info.applicationInfo.flags
3476                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3477                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3478                            ps.readUserState(userId), userId);
3479                    if (info != null) {
3480                        outNames.add(entry.getKey());
3481                        outInfo.add(info);
3482                    }
3483                }
3484            }
3485        }
3486    }
3487
3488    public List<ProviderInfo> queryContentProviders(String processName,
3489            int uid, int flags) {
3490        ArrayList<ProviderInfo> finalList = null;
3491        // reader
3492        synchronized (mPackages) {
3493            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3494            final int userId = processName != null ?
3495                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3496            while (i.hasNext()) {
3497                final PackageParser.Provider p = i.next();
3498                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3499                if (ps != null && p.info.authority != null
3500                        && (processName == null
3501                                || (p.info.processName.equals(processName)
3502                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3503                        && mSettings.isEnabledLPr(p.info, flags, userId)
3504                        && (!mSafeMode
3505                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3506                    if (finalList == null) {
3507                        finalList = new ArrayList<ProviderInfo>(3);
3508                    }
3509                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3510                            ps.readUserState(userId), userId);
3511                    if (info != null) {
3512                        finalList.add(info);
3513                    }
3514                }
3515            }
3516        }
3517
3518        if (finalList != null) {
3519            Collections.sort(finalList, mProviderInitOrderSorter);
3520        }
3521
3522        return finalList;
3523    }
3524
3525    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3526            int flags) {
3527        // reader
3528        synchronized (mPackages) {
3529            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3530            return PackageParser.generateInstrumentationInfo(i, flags);
3531        }
3532    }
3533
3534    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3535            int flags) {
3536        ArrayList<InstrumentationInfo> finalList =
3537            new ArrayList<InstrumentationInfo>();
3538
3539        // reader
3540        synchronized (mPackages) {
3541            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3542            while (i.hasNext()) {
3543                final PackageParser.Instrumentation p = i.next();
3544                if (targetPackage == null
3545                        || targetPackage.equals(p.info.targetPackage)) {
3546                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3547                            flags);
3548                    if (ii != null) {
3549                        finalList.add(ii);
3550                    }
3551                }
3552            }
3553        }
3554
3555        return finalList;
3556    }
3557
3558    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
3559        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
3560        if (overlays == null) {
3561            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
3562            return;
3563        }
3564        for (PackageParser.Package opkg : overlays.values()) {
3565            // Not much to do if idmap fails: we already logged the error
3566            // and we certainly don't want to abort installation of pkg simply
3567            // because an overlay didn't fit properly. For these reasons,
3568            // ignore the return value of createIdmapForPackagePairLI.
3569            createIdmapForPackagePairLI(pkg, opkg);
3570        }
3571    }
3572
3573    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
3574            PackageParser.Package opkg) {
3575        if (!opkg.mTrustedOverlay) {
3576            Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " +
3577                    opkg.mScanPath + ": overlay not trusted");
3578            return false;
3579        }
3580        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
3581        if (overlaySet == null) {
3582            Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " +
3583                    opkg.mScanPath + " but target package has no known overlays");
3584            return false;
3585        }
3586        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
3587        if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) {
3588            Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath);
3589            return false;
3590        }
3591        PackageParser.Package[] overlayArray =
3592            overlaySet.values().toArray(new PackageParser.Package[0]);
3593        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
3594            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
3595                return p1.mOverlayPriority - p2.mOverlayPriority;
3596            }
3597        };
3598        Arrays.sort(overlayArray, cmp);
3599
3600        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
3601        int i = 0;
3602        for (PackageParser.Package p : overlayArray) {
3603            pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir;
3604        }
3605        return true;
3606    }
3607
3608    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
3609        String[] files = dir.list();
3610        if (files == null) {
3611            Log.d(TAG, "No files in app dir " + dir);
3612            return;
3613        }
3614
3615        if (DEBUG_PACKAGE_SCANNING) {
3616            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
3617                    + " flags=0x" + Integer.toHexString(flags));
3618        }
3619
3620        int i;
3621        for (i=0; i<files.length; i++) {
3622            File file = new File(dir, files[i]);
3623            if (!isPackageFilename(files[i])) {
3624                // Ignore entries which are not apk's
3625                continue;
3626            }
3627            PackageParser.Package pkg = scanPackageLI(file,
3628                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
3629            // Don't mess around with apps in system partition.
3630            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
3631                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
3632                // Delete the apk
3633                Slog.w(TAG, "Cleaning up failed install of " + file);
3634                file.delete();
3635            }
3636        }
3637    }
3638
3639    private static File getSettingsProblemFile() {
3640        File dataDir = Environment.getDataDirectory();
3641        File systemDir = new File(dataDir, "system");
3642        File fname = new File(systemDir, "uiderrors.txt");
3643        return fname;
3644    }
3645
3646    static void reportSettingsProblem(int priority, String msg) {
3647        try {
3648            File fname = getSettingsProblemFile();
3649            FileOutputStream out = new FileOutputStream(fname, true);
3650            PrintWriter pw = new FastPrintWriter(out);
3651            SimpleDateFormat formatter = new SimpleDateFormat();
3652            String dateString = formatter.format(new Date(System.currentTimeMillis()));
3653            pw.println(dateString + ": " + msg);
3654            pw.close();
3655            FileUtils.setPermissions(
3656                    fname.toString(),
3657                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
3658                    -1, -1);
3659        } catch (java.io.IOException e) {
3660        }
3661        Slog.println(priority, TAG, msg);
3662    }
3663
3664    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
3665            PackageParser.Package pkg, File srcFile, int parseFlags) {
3666        if (GET_CERTIFICATES) {
3667            if (ps != null
3668                    && ps.codePath.equals(srcFile)
3669                    && ps.timeStamp == srcFile.lastModified()) {
3670                if (ps.signatures.mSignatures != null
3671                        && ps.signatures.mSignatures.length != 0) {
3672                    // Optimization: reuse the existing cached certificates
3673                    // if the package appears to be unchanged.
3674                    pkg.mSignatures = ps.signatures.mSignatures;
3675                    return true;
3676                }
3677
3678                Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
3679            } else {
3680                Log.i(TAG, srcFile.toString() + " changed; collecting certs");
3681            }
3682
3683            if (!pp.collectCertificates(pkg, parseFlags)) {
3684                mLastScanError = pp.getParseError();
3685                return false;
3686            }
3687        }
3688        return true;
3689    }
3690
3691    /*
3692     *  Scan a package and return the newly parsed package.
3693     *  Returns null in case of errors and the error code is stored in mLastScanError
3694     */
3695    private PackageParser.Package scanPackageLI(File scanFile,
3696            int parseFlags, int scanMode, long currentTime, UserHandle user) {
3697        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3698        String scanPath = scanFile.getPath();
3699        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
3700        parseFlags |= mDefParseFlags;
3701        PackageParser pp = new PackageParser(scanPath);
3702        pp.setSeparateProcesses(mSeparateProcesses);
3703        pp.setOnlyCoreApps(mOnlyCore);
3704        final PackageParser.Package pkg = pp.parsePackage(scanFile,
3705                scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0);
3706
3707        if (pkg == null) {
3708            mLastScanError = pp.getParseError();
3709            return null;
3710        }
3711
3712        PackageSetting ps = null;
3713        PackageSetting updatedPkg;
3714        // reader
3715        synchronized (mPackages) {
3716            // Look to see if we already know about this package.
3717            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
3718            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
3719                // This package has been renamed to its original name.  Let's
3720                // use that.
3721                ps = mSettings.peekPackageLPr(oldName);
3722            }
3723            // If there was no original package, see one for the real package name.
3724            if (ps == null) {
3725                ps = mSettings.peekPackageLPr(pkg.packageName);
3726            }
3727            // Check to see if this package could be hiding/updating a system
3728            // package.  Must look for it either under the original or real
3729            // package name depending on our state.
3730            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
3731            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
3732        }
3733        boolean updatedPkgBetter = false;
3734        // First check if this is a system package that may involve an update
3735        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3736            if (ps != null && !ps.codePath.equals(scanFile)) {
3737                // The path has changed from what was last scanned...  check the
3738                // version of the new path against what we have stored to determine
3739                // what to do.
3740                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
3741                if (pkg.mVersionCode < ps.versionCode) {
3742                    // The system package has been updated and the code path does not match
3743                    // Ignore entry. Skip it.
3744                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
3745                            + " ignored: updated version " + ps.versionCode
3746                            + " better than this " + pkg.mVersionCode);
3747                    if (!updatedPkg.codePath.equals(scanFile)) {
3748                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
3749                                + ps.name + " changing from " + updatedPkg.codePathString
3750                                + " to " + scanFile);
3751                        updatedPkg.codePath = scanFile;
3752                        updatedPkg.codePathString = scanFile.toString();
3753                        // This is the point at which we know that the system-disk APK
3754                        // for this package has moved during a reboot (e.g. due to an OTA),
3755                        // so we need to reevaluate it for privilege policy.
3756                        if (locationIsPrivileged(scanFile)) {
3757                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
3758                        }
3759                    }
3760                    updatedPkg.pkg = pkg;
3761                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3762                    return null;
3763                } else {
3764                    // The current app on the system partion is better than
3765                    // what we have updated to on the data partition; switch
3766                    // back to the system partition version.
3767                    // At this point, its safely assumed that package installation for
3768                    // apps in system partition will go through. If not there won't be a working
3769                    // version of the app
3770                    // writer
3771                    synchronized (mPackages) {
3772                        // Just remove the loaded entries from package lists.
3773                        mPackages.remove(ps.name);
3774                    }
3775                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
3776                            + "reverting from " + ps.codePathString
3777                            + ": new version " + pkg.mVersionCode
3778                            + " better than installed " + ps.versionCode);
3779
3780                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3781                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
3782                            getAppInstructionSetFromSettings(ps));
3783                    synchronized (mInstallLock) {
3784                        args.cleanUpResourcesLI();
3785                    }
3786                    synchronized (mPackages) {
3787                        mSettings.enableSystemPackageLPw(ps.name);
3788                    }
3789                    updatedPkgBetter = true;
3790                }
3791            }
3792        }
3793
3794        if (updatedPkg != null) {
3795            // An updated system app will not have the PARSE_IS_SYSTEM flag set
3796            // initially
3797            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
3798
3799            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
3800            // flag set initially
3801            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
3802                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
3803            }
3804        }
3805        // Verify certificates against what was last scanned
3806        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
3807            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
3808            return null;
3809        }
3810
3811        /*
3812         * A new system app appeared, but we already had a non-system one of the
3813         * same name installed earlier.
3814         */
3815        boolean shouldHideSystemApp = false;
3816        if (updatedPkg == null && ps != null
3817                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
3818            /*
3819             * Check to make sure the signatures match first. If they don't,
3820             * wipe the installed application and its data.
3821             */
3822            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
3823                    != PackageManager.SIGNATURE_MATCH) {
3824                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
3825                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
3826                ps = null;
3827            } else {
3828                /*
3829                 * If the newly-added system app is an older version than the
3830                 * already installed version, hide it. It will be scanned later
3831                 * and re-added like an update.
3832                 */
3833                if (pkg.mVersionCode < ps.versionCode) {
3834                    shouldHideSystemApp = true;
3835                } else {
3836                    /*
3837                     * The newly found system app is a newer version that the
3838                     * one previously installed. Simply remove the
3839                     * already-installed application and replace it with our own
3840                     * while keeping the application data.
3841                     */
3842                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
3843                            + ps.codePathString + ": new version " + pkg.mVersionCode
3844                            + " better than installed " + ps.versionCode);
3845                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3846                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
3847                            getAppInstructionSetFromSettings(ps));
3848                    synchronized (mInstallLock) {
3849                        args.cleanUpResourcesLI();
3850                    }
3851                }
3852            }
3853        }
3854
3855        // The apk is forward locked (not public) if its code and resources
3856        // are kept in different files. (except for app in either system or
3857        // vendor path).
3858        // TODO grab this value from PackageSettings
3859        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
3860            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
3861                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
3862            }
3863        }
3864
3865        String codePath = null;
3866        String resPath = null;
3867        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
3868            if (ps != null && ps.resourcePathString != null) {
3869                resPath = ps.resourcePathString;
3870            } else {
3871                // Should not happen at all. Just log an error.
3872                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
3873            }
3874        } else {
3875            resPath = pkg.mScanPath;
3876        }
3877
3878        codePath = pkg.mScanPath;
3879        // Set application objects path explicitly.
3880        setApplicationInfoPaths(pkg, codePath, resPath);
3881        // Note that we invoke the following method only if we are about to unpack an application
3882        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
3883                | SCAN_UPDATE_SIGNATURE, currentTime, user);
3884
3885        /*
3886         * If the system app should be overridden by a previously installed
3887         * data, hide the system app now and let the /data/app scan pick it up
3888         * again.
3889         */
3890        if (shouldHideSystemApp) {
3891            synchronized (mPackages) {
3892                /*
3893                 * We have to grant systems permissions before we hide, because
3894                 * grantPermissions will assume the package update is trying to
3895                 * expand its permissions.
3896                 */
3897                grantPermissionsLPw(pkg, true);
3898                mSettings.disableSystemPackageLPw(pkg.packageName);
3899            }
3900        }
3901
3902        return scannedPkg;
3903    }
3904
3905    private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
3906            String destResPath) {
3907        pkg.mPath = pkg.mScanPath = destCodePath;
3908        pkg.applicationInfo.sourceDir = destCodePath;
3909        pkg.applicationInfo.publicSourceDir = destResPath;
3910    }
3911
3912    private static String fixProcessName(String defProcessName,
3913            String processName, int uid) {
3914        if (processName == null) {
3915            return defProcessName;
3916        }
3917        return processName;
3918    }
3919
3920    private boolean verifySignaturesLP(PackageSetting pkgSetting,
3921            PackageParser.Package pkg) {
3922        if (pkgSetting.signatures.mSignatures != null) {
3923            // Already existing package. Make sure signatures match
3924            if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
3925                PackageManager.SIGNATURE_MATCH) {
3926                    Slog.e(TAG, "Package " + pkg.packageName
3927                            + " signatures do not match the previously installed version; ignoring!");
3928                    mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
3929                    return false;
3930                }
3931        }
3932        // Check for shared user signatures
3933        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
3934            if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
3935                    pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3936                Slog.e(TAG, "Package " + pkg.packageName
3937                        + " has no signatures that match those in shared user "
3938                        + pkgSetting.sharedUser.name + "; ignoring!");
3939                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
3940                return false;
3941            }
3942        }
3943        return true;
3944    }
3945
3946    /**
3947     * Enforces that only the system UID or root's UID can call a method exposed
3948     * via Binder.
3949     *
3950     * @param message used as message if SecurityException is thrown
3951     * @throws SecurityException if the caller is not system or root
3952     */
3953    private static final void enforceSystemOrRoot(String message) {
3954        final int uid = Binder.getCallingUid();
3955        if (uid != Process.SYSTEM_UID && uid != 0) {
3956            throw new SecurityException(message);
3957        }
3958    }
3959
3960    @Override
3961    public void performBootDexOpt() {
3962        enforceSystemOrRoot("Only the system can request dexopt be performed");
3963
3964        final HashSet<PackageParser.Package> pkgs;
3965        synchronized (mPackages) {
3966            pkgs = mDeferredDexOpt;
3967            mDeferredDexOpt = null;
3968        }
3969
3970        if (pkgs != null) {
3971            int i = 0;
3972            for (PackageParser.Package pkg : pkgs) {
3973                if (!isFirstBoot()) {
3974                    i++;
3975                    try {
3976                        ActivityManagerNative.getDefault().showBootMessage(
3977                                mContext.getResources().getString(
3978                                        com.android.internal.R.string.android_upgrading_apk,
3979                                        i, pkgs.size()), true);
3980                    } catch (RemoteException e) {
3981                    }
3982                }
3983                PackageParser.Package p = pkg;
3984                synchronized (mInstallLock) {
3985                    if (!p.mDidDexOpt) {
3986                        performDexOptLI(p, false /* force dex */, false /* defer */,
3987                                true /* include dependencies */);
3988                    }
3989                }
3990            }
3991        }
3992    }
3993
3994    @Override
3995    public boolean performDexOpt(String packageName) {
3996        enforceSystemOrRoot("Only the system can request dexopt be performed");
3997        if (!mNoDexOpt) {
3998            return false;
3999        }
4000
4001        PackageParser.Package p;
4002        synchronized (mPackages) {
4003            p = mPackages.get(packageName);
4004            if (p == null || p.mDidDexOpt) {
4005                return false;
4006            }
4007        }
4008        synchronized (mInstallLock) {
4009            return performDexOptLI(p, false /* force dex */, false /* defer */,
4010                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4011        }
4012    }
4013
4014    private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet, boolean forceDex,
4015            boolean defer, HashSet<String> done) {
4016        for (int i=0; i<libs.size(); i++) {
4017            PackageParser.Package libPkg;
4018            String libName;
4019            synchronized (mPackages) {
4020                libName = libs.get(i);
4021                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4022                if (lib != null && lib.apk != null) {
4023                    libPkg = mPackages.get(lib.apk);
4024                } else {
4025                    libPkg = null;
4026                }
4027            }
4028            if (libPkg != null && !done.contains(libName)) {
4029                performDexOptLI(libPkg, instructionSet, forceDex, defer, done);
4030            }
4031        }
4032    }
4033
4034    static final int DEX_OPT_SKIPPED = 0;
4035    static final int DEX_OPT_PERFORMED = 1;
4036    static final int DEX_OPT_DEFERRED = 2;
4037    static final int DEX_OPT_FAILED = -1;
4038
4039    private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride,
4040            boolean forceDex,
4041            boolean defer, HashSet<String> done) {
4042        final String instructionSet = instructionSetOverride != null ?
4043                instructionSetOverride : getAppInstructionSet(pkg.applicationInfo);
4044
4045        if (done != null) {
4046            done.add(pkg.packageName);
4047            if (pkg.usesLibraries != null) {
4048                performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done);
4049            }
4050            if (pkg.usesOptionalLibraries != null) {
4051                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done);
4052            }
4053        }
4054
4055        boolean performed = false;
4056        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4057            String path = pkg.mScanPath;
4058            int ret = 0;
4059            try {
4060                if (forceDex || dalvik.system.DexFile.isDexOptNeededInternal(path,
4061                        pkg.packageName, instructionSet, defer)) {
4062                    if (!forceDex && defer) {
4063                        if (mDeferredDexOpt == null) {
4064                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4065                        }
4066                        mDeferredDexOpt.add(pkg);
4067                        return DEX_OPT_DEFERRED;
4068                    } else {
4069                        Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName +
4070                                " (instructionSet=" + instructionSet + ")");
4071
4072                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4073                        ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4074                                                pkg.packageName, instructionSet);
4075                        pkg.mDidDexOpt = true;
4076                        performed = true;
4077                    }
4078                }
4079            } catch (FileNotFoundException e) {
4080                Slog.w(TAG, "Apk not found for dexopt: " + path);
4081                ret = -1;
4082            } catch (IOException e) {
4083                Slog.w(TAG, "IOException reading apk: " + path, e);
4084                ret = -1;
4085            } catch (dalvik.system.StaleDexCacheError e) {
4086                Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4087                ret = -1;
4088            } catch (Exception e) {
4089                Slog.w(TAG, "Exception when doing dexopt : ", e);
4090                ret = -1;
4091            }
4092            if (ret < 0) {
4093                //error from installer
4094                return DEX_OPT_FAILED;
4095            }
4096        }
4097
4098        return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4099    }
4100
4101    private String getAppInstructionSet(ApplicationInfo info) {
4102        String instructionSet = getPreferredInstructionSet();
4103
4104        if (info.requiredCpuAbi != null) {
4105            instructionSet = VMRuntime.getInstructionSet(info.requiredCpuAbi);
4106        }
4107
4108        return instructionSet;
4109    }
4110
4111    private String getAppInstructionSetFromSettings(PackageSetting ps) {
4112        String instructionSet = getPreferredInstructionSet();
4113
4114        if (ps.requiredCpuAbiString != null) {
4115            instructionSet = VMRuntime.getInstructionSet(ps.requiredCpuAbiString);
4116        }
4117
4118        return instructionSet;
4119    }
4120
4121    private static String getPreferredInstructionSet() {
4122        if (sPreferredInstructionSet == null) {
4123            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4124        }
4125
4126        return sPreferredInstructionSet;
4127    }
4128
4129    private static List<String> getAllInstructionSets() {
4130        final String[] allAbis = Build.SUPPORTED_ABIS;
4131        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4132
4133        for (String abi : allAbis) {
4134            final String instructionSet = VMRuntime.getInstructionSet(abi);
4135            if (!allInstructionSets.contains(instructionSet)) {
4136                allInstructionSets.add(instructionSet);
4137            }
4138        }
4139
4140        return allInstructionSets;
4141    }
4142
4143    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4144            boolean inclDependencies) {
4145        HashSet<String> done;
4146        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4147            done = new HashSet<String>();
4148            done.add(pkg.packageName);
4149        } else {
4150            done = null;
4151        }
4152        return performDexOptLI(pkg, null /* instruction set override */,  forceDex, defer, done);
4153    }
4154
4155    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4156        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4157            Slog.w(TAG, "Unable to update from " + oldPkg.name
4158                    + " to " + newPkg.packageName
4159                    + ": old package not in system partition");
4160            return false;
4161        } else if (mPackages.get(oldPkg.name) != null) {
4162            Slog.w(TAG, "Unable to update from " + oldPkg.name
4163                    + " to " + newPkg.packageName
4164                    + ": old package still exists");
4165            return false;
4166        }
4167        return true;
4168    }
4169
4170    File getDataPathForUser(int userId) {
4171        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4172    }
4173
4174    private File getDataPathForPackage(String packageName, int userId) {
4175        /*
4176         * Until we fully support multiple users, return the directory we
4177         * previously would have. The PackageManagerTests will need to be
4178         * revised when this is changed back..
4179         */
4180        if (userId == 0) {
4181            return new File(mAppDataDir, packageName);
4182        } else {
4183            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4184                + File.separator + packageName);
4185        }
4186    }
4187
4188    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4189        int[] users = sUserManager.getUserIds();
4190        int res = mInstaller.install(packageName, uid, uid, seinfo);
4191        if (res < 0) {
4192            return res;
4193        }
4194        for (int user : users) {
4195            if (user != 0) {
4196                res = mInstaller.createUserData(packageName,
4197                        UserHandle.getUid(user, uid), user, seinfo);
4198                if (res < 0) {
4199                    return res;
4200                }
4201            }
4202        }
4203        return res;
4204    }
4205
4206    private int removeDataDirsLI(String packageName) {
4207        int[] users = sUserManager.getUserIds();
4208        int res = 0;
4209        for (int user : users) {
4210            int resInner = mInstaller.remove(packageName, user);
4211            if (resInner < 0) {
4212                res = resInner;
4213            }
4214        }
4215
4216        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4217        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4218        if (!nativeLibraryFile.delete()) {
4219            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4220        }
4221
4222        return res;
4223    }
4224
4225    private int addSharedLibraryLPw(final SharedLibraryEntry file, int num,
4226            PackageParser.Package changingLib) {
4227        if (file.path != null) {
4228            mTmpSharedLibraries[num] = file.path;
4229            return num+1;
4230        }
4231        PackageParser.Package p = mPackages.get(file.apk);
4232        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4233            // If we are doing this while in the middle of updating a library apk,
4234            // then we need to make sure to use that new apk for determining the
4235            // dependencies here.  (We haven't yet finished committing the new apk
4236            // to the package manager state.)
4237            if (p == null || p.packageName.equals(changingLib.packageName)) {
4238                p = changingLib;
4239            }
4240        }
4241        if (p != null) {
4242            String path = p.mPath;
4243            for (int i=0; i<num; i++) {
4244                if (mTmpSharedLibraries[i].equals(path)) {
4245                    return num;
4246                }
4247            }
4248            mTmpSharedLibraries[num] = p.mPath;
4249            return num+1;
4250        }
4251        return num;
4252    }
4253
4254    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4255            PackageParser.Package changingLib) {
4256        // We might be upgrading from a version of the platform that did not
4257        // provide per-package native library directories for system apps.
4258        // Fix that up here.
4259        if (isSystemApp(pkg)) {
4260            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4261            setInternalAppNativeLibraryPath(pkg, ps);
4262        }
4263
4264        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4265            if (mTmpSharedLibraries == null ||
4266                    mTmpSharedLibraries.length < mSharedLibraries.size()) {
4267                mTmpSharedLibraries = new String[mSharedLibraries.size()];
4268            }
4269            int num = 0;
4270            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4271            for (int i=0; i<N; i++) {
4272                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4273                if (file == null) {
4274                    Slog.e(TAG, "Package " + pkg.packageName
4275                            + " requires unavailable shared library "
4276                            + pkg.usesLibraries.get(i) + "; failing!");
4277                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4278                    return false;
4279                }
4280                num = addSharedLibraryLPw(file, num, changingLib);
4281            }
4282            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4283            for (int i=0; i<N; i++) {
4284                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4285                if (file == null) {
4286                    Slog.w(TAG, "Package " + pkg.packageName
4287                            + " desires unavailable shared library "
4288                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4289                } else {
4290                    num = addSharedLibraryLPw(file, num, changingLib);
4291                }
4292            }
4293            if (num > 0) {
4294                pkg.usesLibraryFiles = new String[num];
4295                System.arraycopy(mTmpSharedLibraries, 0,
4296                        pkg.usesLibraryFiles, 0, num);
4297            } else {
4298                pkg.usesLibraryFiles = null;
4299            }
4300        }
4301        return true;
4302    }
4303
4304    private static boolean hasString(List<String> list, List<String> which) {
4305        if (list == null) {
4306            return false;
4307        }
4308        for (int i=list.size()-1; i>=0; i--) {
4309            for (int j=which.size()-1; j>=0; j--) {
4310                if (which.get(j).equals(list.get(i))) {
4311                    return true;
4312                }
4313            }
4314        }
4315        return false;
4316    }
4317
4318    private void updateAllSharedLibrariesLPw() {
4319        for (PackageParser.Package pkg : mPackages.values()) {
4320            updateSharedLibrariesLPw(pkg, null);
4321        }
4322    }
4323
4324    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4325            PackageParser.Package changingPkg) {
4326        ArrayList<PackageParser.Package> res = null;
4327        for (PackageParser.Package pkg : mPackages.values()) {
4328            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4329                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4330                if (res == null) {
4331                    res = new ArrayList<PackageParser.Package>();
4332                }
4333                res.add(pkg);
4334                updateSharedLibrariesLPw(pkg, changingPkg);
4335            }
4336        }
4337        return res;
4338    }
4339
4340    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4341            int parseFlags, int scanMode, long currentTime, UserHandle user) {
4342        File scanFile = new File(pkg.mScanPath);
4343        if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
4344                pkg.applicationInfo.publicSourceDir == null) {
4345            // Bail out. The resource and code paths haven't been set.
4346            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4347            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4348            return null;
4349        }
4350
4351        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4352            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4353        }
4354
4355        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4356            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4357        }
4358
4359        if (mCustomResolverComponentName != null &&
4360                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4361            setUpCustomResolverActivity(pkg);
4362        }
4363
4364        if (pkg.packageName.equals("android")) {
4365            synchronized (mPackages) {
4366                if (mAndroidApplication != null) {
4367                    Slog.w(TAG, "*************************************************");
4368                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4369                    Slog.w(TAG, " file=" + scanFile);
4370                    Slog.w(TAG, "*************************************************");
4371                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4372                    return null;
4373                }
4374
4375                // Set up information for our fall-back user intent resolution activity.
4376                mPlatformPackage = pkg;
4377                pkg.mVersionCode = mSdkVersion;
4378                mAndroidApplication = pkg.applicationInfo;
4379
4380                if (!mResolverReplaced) {
4381                    mResolveActivity.applicationInfo = mAndroidApplication;
4382                    mResolveActivity.name = ResolverActivity.class.getName();
4383                    mResolveActivity.packageName = mAndroidApplication.packageName;
4384                    mResolveActivity.processName = "system:ui";
4385                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4386                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4387                    mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
4388                    mResolveActivity.exported = true;
4389                    mResolveActivity.enabled = true;
4390                    mResolveInfo.activityInfo = mResolveActivity;
4391                    mResolveInfo.priority = 0;
4392                    mResolveInfo.preferredOrder = 0;
4393                    mResolveInfo.match = 0;
4394                    mResolveComponentName = new ComponentName(
4395                            mAndroidApplication.packageName, mResolveActivity.name);
4396                }
4397            }
4398        }
4399
4400        if (DEBUG_PACKAGE_SCANNING) {
4401            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4402                Log.d(TAG, "Scanning package " + pkg.packageName);
4403        }
4404
4405        if (mPackages.containsKey(pkg.packageName)
4406                || mSharedLibraries.containsKey(pkg.packageName)) {
4407            Slog.w(TAG, "Application package " + pkg.packageName
4408                    + " already installed.  Skipping duplicate.");
4409            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4410            return null;
4411        }
4412
4413        // Initialize package source and resource directories
4414        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
4415        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
4416
4417        SharedUserSetting suid = null;
4418        PackageSetting pkgSetting = null;
4419
4420        if (!isSystemApp(pkg)) {
4421            // Only system apps can use these features.
4422            pkg.mOriginalPackages = null;
4423            pkg.mRealPackage = null;
4424            pkg.mAdoptPermissions = null;
4425        }
4426
4427        // writer
4428        synchronized (mPackages) {
4429            if (pkg.mSharedUserId != null) {
4430                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
4431                if (suid == null) {
4432                    Slog.w(TAG, "Creating application package " + pkg.packageName
4433                            + " for shared user failed");
4434                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4435                    return null;
4436                }
4437                if (DEBUG_PACKAGE_SCANNING) {
4438                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4439                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
4440                                + "): packages=" + suid.packages);
4441                }
4442            }
4443
4444            // Check if we are renaming from an original package name.
4445            PackageSetting origPackage = null;
4446            String realName = null;
4447            if (pkg.mOriginalPackages != null) {
4448                // This package may need to be renamed to a previously
4449                // installed name.  Let's check on that...
4450                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
4451                if (pkg.mOriginalPackages.contains(renamed)) {
4452                    // This package had originally been installed as the
4453                    // original name, and we have already taken care of
4454                    // transitioning to the new one.  Just update the new
4455                    // one to continue using the old name.
4456                    realName = pkg.mRealPackage;
4457                    if (!pkg.packageName.equals(renamed)) {
4458                        // Callers into this function may have already taken
4459                        // care of renaming the package; only do it here if
4460                        // it is not already done.
4461                        pkg.setPackageName(renamed);
4462                    }
4463
4464                } else {
4465                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
4466                        if ((origPackage = mSettings.peekPackageLPr(
4467                                pkg.mOriginalPackages.get(i))) != null) {
4468                            // We do have the package already installed under its
4469                            // original name...  should we use it?
4470                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
4471                                // New package is not compatible with original.
4472                                origPackage = null;
4473                                continue;
4474                            } else if (origPackage.sharedUser != null) {
4475                                // Make sure uid is compatible between packages.
4476                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
4477                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
4478                                            + " to " + pkg.packageName + ": old uid "
4479                                            + origPackage.sharedUser.name
4480                                            + " differs from " + pkg.mSharedUserId);
4481                                    origPackage = null;
4482                                    continue;
4483                                }
4484                            } else {
4485                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
4486                                        + pkg.packageName + " to old name " + origPackage.name);
4487                            }
4488                            break;
4489                        }
4490                    }
4491                }
4492            }
4493
4494            if (mTransferedPackages.contains(pkg.packageName)) {
4495                Slog.w(TAG, "Package " + pkg.packageName
4496                        + " was transferred to another, but its .apk remains");
4497            }
4498
4499            // Just create the setting, don't add it yet. For already existing packages
4500            // the PkgSetting exists already and doesn't have to be created.
4501            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
4502                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
4503                    pkg.applicationInfo.requiredCpuAbi,
4504                    pkg.applicationInfo.flags, user, false);
4505            if (pkgSetting == null) {
4506                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
4507                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4508                return null;
4509            }
4510
4511            if (pkgSetting.origPackage != null) {
4512                // If we are first transitioning from an original package,
4513                // fix up the new package's name now.  We need to do this after
4514                // looking up the package under its new name, so getPackageLP
4515                // can take care of fiddling things correctly.
4516                pkg.setPackageName(origPackage.name);
4517
4518                // File a report about this.
4519                String msg = "New package " + pkgSetting.realName
4520                        + " renamed to replace old package " + pkgSetting.name;
4521                reportSettingsProblem(Log.WARN, msg);
4522
4523                // Make a note of it.
4524                mTransferedPackages.add(origPackage.name);
4525
4526                // No longer need to retain this.
4527                pkgSetting.origPackage = null;
4528            }
4529
4530            if (realName != null) {
4531                // Make a note of it.
4532                mTransferedPackages.add(pkg.packageName);
4533            }
4534
4535            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
4536                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
4537            }
4538
4539            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4540                // Check all shared libraries and map to their actual file path.
4541                // We only do this here for apps not on a system dir, because those
4542                // are the only ones that can fail an install due to this.  We
4543                // will take care of the system apps by updating all of their
4544                // library paths after the scan is done.
4545                if (!updateSharedLibrariesLPw(pkg, null)) {
4546                    return null;
4547                }
4548            }
4549
4550            if (mFoundPolicyFile) {
4551                SELinuxMMAC.assignSeinfoValue(pkg);
4552            }
4553
4554            pkg.applicationInfo.uid = pkgSetting.appId;
4555            pkg.mExtras = pkgSetting;
4556
4557            if (!verifySignaturesLP(pkgSetting, pkg)) {
4558                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4559                    return null;
4560                }
4561                // The signature has changed, but this package is in the system
4562                // image...  let's recover!
4563                pkgSetting.signatures.mSignatures = pkg.mSignatures;
4564                // However...  if this package is part of a shared user, but it
4565                // doesn't match the signature of the shared user, let's fail.
4566                // What this means is that you can't change the signatures
4567                // associated with an overall shared user, which doesn't seem all
4568                // that unreasonable.
4569                if (pkgSetting.sharedUser != null) {
4570                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4571                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
4572                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
4573                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
4574                        return null;
4575                    }
4576                }
4577                // File a report about this.
4578                String msg = "System package " + pkg.packageName
4579                        + " signature changed; retaining data.";
4580                reportSettingsProblem(Log.WARN, msg);
4581            }
4582
4583            // Verify that this new package doesn't have any content providers
4584            // that conflict with existing packages.  Only do this if the
4585            // package isn't already installed, since we don't want to break
4586            // things that are installed.
4587            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
4588                final int N = pkg.providers.size();
4589                int i;
4590                for (i=0; i<N; i++) {
4591                    PackageParser.Provider p = pkg.providers.get(i);
4592                    if (p.info.authority != null) {
4593                        String names[] = p.info.authority.split(";");
4594                        for (int j = 0; j < names.length; j++) {
4595                            if (mProvidersByAuthority.containsKey(names[j])) {
4596                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
4597                                Slog.w(TAG, "Can't install because provider name " + names[j] +
4598                                        " (in package " + pkg.applicationInfo.packageName +
4599                                        ") is already used by "
4600                                        + ((other != null && other.getComponentName() != null)
4601                                                ? other.getComponentName().getPackageName() : "?"));
4602                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
4603                                return null;
4604                            }
4605                        }
4606                    }
4607                }
4608            }
4609
4610            if (pkg.mAdoptPermissions != null) {
4611                // This package wants to adopt ownership of permissions from
4612                // another package.
4613                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
4614                    final String origName = pkg.mAdoptPermissions.get(i);
4615                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
4616                    if (orig != null) {
4617                        if (verifyPackageUpdateLPr(orig, pkg)) {
4618                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
4619                                    + pkg.packageName);
4620                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
4621                        }
4622                    }
4623                }
4624            }
4625        }
4626
4627        final String pkgName = pkg.packageName;
4628
4629        final long scanFileTime = scanFile.lastModified();
4630        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
4631        pkg.applicationInfo.processName = fixProcessName(
4632                pkg.applicationInfo.packageName,
4633                pkg.applicationInfo.processName,
4634                pkg.applicationInfo.uid);
4635
4636        File dataPath;
4637        if (mPlatformPackage == pkg) {
4638            // The system package is special.
4639            dataPath = new File (Environment.getDataDirectory(), "system");
4640            pkg.applicationInfo.dataDir = dataPath.getPath();
4641        } else {
4642            // This is a normal package, need to make its data directory.
4643            dataPath = getDataPathForPackage(pkg.packageName, 0);
4644
4645            boolean uidError = false;
4646
4647            if (dataPath.exists()) {
4648                int currentUid = 0;
4649                try {
4650                    StructStat stat = Os.stat(dataPath.getPath());
4651                    currentUid = stat.st_uid;
4652                } catch (ErrnoException e) {
4653                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
4654                }
4655
4656                // If we have mismatched owners for the data path, we have a problem.
4657                if (currentUid != pkg.applicationInfo.uid) {
4658                    boolean recovered = false;
4659                    if (currentUid == 0) {
4660                        // The directory somehow became owned by root.  Wow.
4661                        // This is probably because the system was stopped while
4662                        // installd was in the middle of messing with its libs
4663                        // directory.  Ask installd to fix that.
4664                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
4665                                pkg.applicationInfo.uid);
4666                        if (ret >= 0) {
4667                            recovered = true;
4668                            String msg = "Package " + pkg.packageName
4669                                    + " unexpectedly changed to uid 0; recovered to " +
4670                                    + pkg.applicationInfo.uid;
4671                            reportSettingsProblem(Log.WARN, msg);
4672                        }
4673                    }
4674                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4675                            || (scanMode&SCAN_BOOTING) != 0)) {
4676                        // If this is a system app, we can at least delete its
4677                        // current data so the application will still work.
4678                        int ret = removeDataDirsLI(pkgName);
4679                        if (ret >= 0) {
4680                            // TODO: Kill the processes first
4681                            // Old data gone!
4682                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4683                                    ? "System package " : "Third party package ";
4684                            String msg = prefix + pkg.packageName
4685                                    + " has changed from uid: "
4686                                    + currentUid + " to "
4687                                    + pkg.applicationInfo.uid + "; old data erased";
4688                            reportSettingsProblem(Log.WARN, msg);
4689                            recovered = true;
4690
4691                            // And now re-install the app.
4692                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
4693                                                   pkg.applicationInfo.seinfo);
4694                            if (ret == -1) {
4695                                // Ack should not happen!
4696                                msg = prefix + pkg.packageName
4697                                        + " could not have data directory re-created after delete.";
4698                                reportSettingsProblem(Log.WARN, msg);
4699                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4700                                return null;
4701                            }
4702                        }
4703                        if (!recovered) {
4704                            mHasSystemUidErrors = true;
4705                        }
4706                    } else if (!recovered) {
4707                        // If we allow this install to proceed, we will be broken.
4708                        // Abort, abort!
4709                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
4710                        return null;
4711                    }
4712                    if (!recovered) {
4713                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
4714                            + pkg.applicationInfo.uid + "/fs_"
4715                            + currentUid;
4716                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
4717                        String msg = "Package " + pkg.packageName
4718                                + " has mismatched uid: "
4719                                + currentUid + " on disk, "
4720                                + pkg.applicationInfo.uid + " in settings";
4721                        // writer
4722                        synchronized (mPackages) {
4723                            mSettings.mReadMessages.append(msg);
4724                            mSettings.mReadMessages.append('\n');
4725                            uidError = true;
4726                            if (!pkgSetting.uidError) {
4727                                reportSettingsProblem(Log.ERROR, msg);
4728                            }
4729                        }
4730                    }
4731                }
4732                pkg.applicationInfo.dataDir = dataPath.getPath();
4733                if (mShouldRestoreconData) {
4734                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
4735                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
4736                                pkg.applicationInfo.uid);
4737                }
4738            } else {
4739                if (DEBUG_PACKAGE_SCANNING) {
4740                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4741                        Log.v(TAG, "Want this data dir: " + dataPath);
4742                }
4743                //invoke installer to do the actual installation
4744                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
4745                                           pkg.applicationInfo.seinfo);
4746                if (ret < 0) {
4747                    // Error from installer
4748                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4749                    return null;
4750                }
4751
4752                if (dataPath.exists()) {
4753                    pkg.applicationInfo.dataDir = dataPath.getPath();
4754                } else {
4755                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
4756                    pkg.applicationInfo.dataDir = null;
4757                }
4758            }
4759
4760            /*
4761             * Set the data dir to the default "/data/data/<package name>/lib"
4762             * if we got here without anyone telling us different (e.g., apps
4763             * stored on SD card have their native libraries stored in the ASEC
4764             * container with the APK).
4765             *
4766             * This happens during an upgrade from a package settings file that
4767             * doesn't have a native library path attribute at all.
4768             */
4769            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
4770                if (pkgSetting.nativeLibraryPathString == null) {
4771                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
4772                } else {
4773                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
4774                }
4775            }
4776            pkgSetting.uidError = uidError;
4777        }
4778
4779        String path = scanFile.getPath();
4780        /* Note: We don't want to unpack the native binaries for
4781         *        system applications, unless they have been updated
4782         *        (the binaries are already under /system/lib).
4783         *        Also, don't unpack libs for apps on the external card
4784         *        since they should have their libraries in the ASEC
4785         *        container already.
4786         *
4787         *        In other words, we're going to unpack the binaries
4788         *        only for non-system apps and system app upgrades.
4789         */
4790        if (pkg.applicationInfo.nativeLibraryDir != null) {
4791            try {
4792                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
4793                final String dataPathString = dataPath.getCanonicalPath();
4794
4795                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4796                    /*
4797                     * Upgrading from a previous version of the OS sometimes
4798                     * leaves native libraries in the /data/data/<app>/lib
4799                     * directory for system apps even when they shouldn't be.
4800                     * Recent changes in the JNI library search path
4801                     * necessitates we remove those to match previous behavior.
4802                     */
4803                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
4804                        Log.i(TAG, "removed obsolete native libraries for system package "
4805                                + path);
4806                    }
4807
4808                    setInternalAppAbi(pkg, pkgSetting);
4809                } else {
4810                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
4811                        /*
4812                         * Update native library dir if it starts with
4813                         * /data/data
4814                         */
4815                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
4816                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
4817                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
4818                        }
4819
4820                        try {
4821                            int copyRet = copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir);
4822                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
4823                                Slog.e(TAG, "Unable to copy native libraries");
4824                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4825                                return null;
4826                            }
4827
4828                            // We've successfully copied native libraries across, so we make a
4829                            // note of what ABI we're using
4830                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
4831                                pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[copyRet];
4832                            } else {
4833                                pkg.applicationInfo.requiredCpuAbi = null;
4834                            }
4835                        } catch (IOException e) {
4836                            Slog.e(TAG, "Unable to copy native libraries", e);
4837                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4838                            return null;
4839                        }
4840                    } else {
4841                        // We don't have to copy the shared libraries if we're in the ASEC container
4842                        // but we still need to scan the file to figure out what ABI the app needs.
4843                        //
4844                        // TODO: This duplicates work done in the default container service. It's possible
4845                        // to clean this up but we'll need to change the interface between this service
4846                        // and IMediaContainerService (but doing so will spread this logic out, rather
4847                        // than centralizing it).
4848                        final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
4849                        final int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS);
4850                        if (abi >= 0) {
4851                            pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[abi];
4852                        } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) {
4853                            // Note that (non upgraded) system apps will not have any native
4854                            // libraries bundled in their APK, but we're guaranteed not to be
4855                            // such an app at this point.
4856                            pkg.applicationInfo.requiredCpuAbi = null;
4857                        } else {
4858                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4859                            return null;
4860                        }
4861                        handle.close();
4862                    }
4863
4864                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
4865                    final int[] userIds = sUserManager.getUserIds();
4866                    synchronized (mInstallLock) {
4867                        for (int userId : userIds) {
4868                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
4869                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
4870                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
4871                                        + ")");
4872                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4873                                return null;
4874                            }
4875                        }
4876                    }
4877                }
4878            } catch (IOException ioe) {
4879                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
4880            }
4881        }
4882        pkg.mScanPath = path;
4883
4884        if ((scanMode&SCAN_NO_DEX) == 0) {
4885            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
4886                    == DEX_OPT_FAILED) {
4887                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
4888                    removeDataDirsLI(pkg.packageName);
4889                }
4890
4891                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
4892                return null;
4893            }
4894        }
4895
4896        if (mFactoryTest && pkg.requestedPermissions.contains(
4897                android.Manifest.permission.FACTORY_TEST)) {
4898            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
4899        }
4900
4901        ArrayList<PackageParser.Package> clientLibPkgs = null;
4902
4903        // writer
4904        synchronized (mPackages) {
4905            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4906                // Only system apps can add new shared libraries.
4907                if (pkg.libraryNames != null) {
4908                    for (int i=0; i<pkg.libraryNames.size(); i++) {
4909                        String name = pkg.libraryNames.get(i);
4910                        boolean allowed = false;
4911                        if (isUpdatedSystemApp(pkg)) {
4912                            // New library entries can only be added through the
4913                            // system image.  This is important to get rid of a lot
4914                            // of nasty edge cases: for example if we allowed a non-
4915                            // system update of the app to add a library, then uninstalling
4916                            // the update would make the library go away, and assumptions
4917                            // we made such as through app install filtering would now
4918                            // have allowed apps on the device which aren't compatible
4919                            // with it.  Better to just have the restriction here, be
4920                            // conservative, and create many fewer cases that can negatively
4921                            // impact the user experience.
4922                            final PackageSetting sysPs = mSettings
4923                                    .getDisabledSystemPkgLPr(pkg.packageName);
4924                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
4925                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
4926                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
4927                                        allowed = true;
4928                                        allowed = true;
4929                                        break;
4930                                    }
4931                                }
4932                            }
4933                        } else {
4934                            allowed = true;
4935                        }
4936                        if (allowed) {
4937                            if (!mSharedLibraries.containsKey(name)) {
4938                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
4939                            } else if (!name.equals(pkg.packageName)) {
4940                                Slog.w(TAG, "Package " + pkg.packageName + " library "
4941                                        + name + " already exists; skipping");
4942                            }
4943                        } else {
4944                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
4945                                    + name + " that is not declared on system image; skipping");
4946                        }
4947                    }
4948                    if ((scanMode&SCAN_BOOTING) == 0) {
4949                        // If we are not booting, we need to update any applications
4950                        // that are clients of our shared library.  If we are booting,
4951                        // this will all be done once the scan is complete.
4952                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
4953                    }
4954                }
4955            }
4956        }
4957
4958        // We also need to dexopt any apps that are dependent on this library.  Note that
4959        // if these fail, we should abort the install since installing the library will
4960        // result in some apps being broken.
4961        if (clientLibPkgs != null) {
4962            if ((scanMode&SCAN_NO_DEX) == 0) {
4963                for (int i=0; i<clientLibPkgs.size(); i++) {
4964                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
4965                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
4966                            == DEX_OPT_FAILED) {
4967                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
4968                            removeDataDirsLI(pkg.packageName);
4969                        }
4970
4971                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
4972                        return null;
4973                    }
4974                }
4975            }
4976        }
4977
4978        // Request the ActivityManager to kill the process(only for existing packages)
4979        // so that we do not end up in a confused state while the user is still using the older
4980        // version of the application while the new one gets installed.
4981        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4982            // If the package lives in an asec, tell everyone that the container is going
4983            // away so they can clean up any references to its resources (which would prevent
4984            // vold from being able to unmount the asec)
4985            if (isForwardLocked(pkg) || isExternal(pkg)) {
4986                if (DEBUG_INSTALL) {
4987                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
4988                }
4989                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
4990                final ArrayList<String> pkgList = new ArrayList<String>(1);
4991                pkgList.add(pkg.applicationInfo.packageName);
4992                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
4993            }
4994
4995            // Post the request that it be killed now that the going-away broadcast is en route
4996            killApplication(pkg.applicationInfo.packageName,
4997                        pkg.applicationInfo.uid, "update pkg");
4998        }
4999
5000        // Also need to kill any apps that are dependent on the library.
5001        if (clientLibPkgs != null) {
5002            for (int i=0; i<clientLibPkgs.size(); i++) {
5003                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5004                killApplication(clientPkg.applicationInfo.packageName,
5005                        clientPkg.applicationInfo.uid, "update lib");
5006            }
5007        }
5008
5009        // writer
5010        synchronized (mPackages) {
5011            // We don't expect installation to fail beyond this point,
5012            if ((scanMode&SCAN_MONITOR) != 0) {
5013                mAppDirs.put(pkg.mPath, pkg);
5014            }
5015            // Add the new setting to mSettings
5016            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5017            // Add the new setting to mPackages
5018            mPackages.put(pkg.applicationInfo.packageName, pkg);
5019            // Make sure we don't accidentally delete its data.
5020            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5021            while (iter.hasNext()) {
5022                PackageCleanItem item = iter.next();
5023                if (pkgName.equals(item.packageName)) {
5024                    iter.remove();
5025                }
5026            }
5027
5028            // Take care of first install / last update times.
5029            if (currentTime != 0) {
5030                if (pkgSetting.firstInstallTime == 0) {
5031                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5032                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5033                    pkgSetting.lastUpdateTime = currentTime;
5034                }
5035            } else if (pkgSetting.firstInstallTime == 0) {
5036                // We need *something*.  Take time time stamp of the file.
5037                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5038            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5039                if (scanFileTime != pkgSetting.timeStamp) {
5040                    // A package on the system image has changed; consider this
5041                    // to be an update.
5042                    pkgSetting.lastUpdateTime = scanFileTime;
5043                }
5044            }
5045
5046            // Add the package's KeySets to the global KeySetManager
5047            KeySetManager ksm = mSettings.mKeySetManager;
5048            try {
5049                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5050                if (pkg.mKeySetMapping != null) {
5051                    for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) {
5052                        if (entry.getValue() != null) {
5053                            ksm.addDefinedKeySetToPackage(pkg.packageName,
5054                                entry.getValue(), entry.getKey());
5055                        }
5056                    }
5057                }
5058            } catch (NullPointerException e) {
5059                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5060            } catch (IllegalArgumentException e) {
5061                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5062            }
5063
5064            int N = pkg.providers.size();
5065            StringBuilder r = null;
5066            int i;
5067            for (i=0; i<N; i++) {
5068                PackageParser.Provider p = pkg.providers.get(i);
5069                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5070                        p.info.processName, pkg.applicationInfo.uid);
5071                mProviders.addProvider(p);
5072                p.syncable = p.info.isSyncable;
5073                if (p.info.authority != null) {
5074                    String names[] = p.info.authority.split(";");
5075                    p.info.authority = null;
5076                    for (int j = 0; j < names.length; j++) {
5077                        if (j == 1 && p.syncable) {
5078                            // We only want the first authority for a provider to possibly be
5079                            // syncable, so if we already added this provider using a different
5080                            // authority clear the syncable flag. We copy the provider before
5081                            // changing it because the mProviders object contains a reference
5082                            // to a provider that we don't want to change.
5083                            // Only do this for the second authority since the resulting provider
5084                            // object can be the same for all future authorities for this provider.
5085                            p = new PackageParser.Provider(p);
5086                            p.syncable = false;
5087                        }
5088                        if (!mProvidersByAuthority.containsKey(names[j])) {
5089                            mProvidersByAuthority.put(names[j], p);
5090                            if (p.info.authority == null) {
5091                                p.info.authority = names[j];
5092                            } else {
5093                                p.info.authority = p.info.authority + ";" + names[j];
5094                            }
5095                            if (DEBUG_PACKAGE_SCANNING) {
5096                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5097                                    Log.d(TAG, "Registered content provider: " + names[j]
5098                                            + ", className = " + p.info.name + ", isSyncable = "
5099                                            + p.info.isSyncable);
5100                            }
5101                        } else {
5102                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5103                            Slog.w(TAG, "Skipping provider name " + names[j] +
5104                                    " (in package " + pkg.applicationInfo.packageName +
5105                                    "): name already used by "
5106                                    + ((other != null && other.getComponentName() != null)
5107                                            ? other.getComponentName().getPackageName() : "?"));
5108                        }
5109                    }
5110                }
5111                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5112                    if (r == null) {
5113                        r = new StringBuilder(256);
5114                    } else {
5115                        r.append(' ');
5116                    }
5117                    r.append(p.info.name);
5118                }
5119            }
5120            if (r != null) {
5121                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5122            }
5123
5124            N = pkg.services.size();
5125            r = null;
5126            for (i=0; i<N; i++) {
5127                PackageParser.Service s = pkg.services.get(i);
5128                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5129                        s.info.processName, pkg.applicationInfo.uid);
5130                mServices.addService(s);
5131                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5132                    if (r == null) {
5133                        r = new StringBuilder(256);
5134                    } else {
5135                        r.append(' ');
5136                    }
5137                    r.append(s.info.name);
5138                }
5139            }
5140            if (r != null) {
5141                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5142            }
5143
5144            N = pkg.receivers.size();
5145            r = null;
5146            for (i=0; i<N; i++) {
5147                PackageParser.Activity a = pkg.receivers.get(i);
5148                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5149                        a.info.processName, pkg.applicationInfo.uid);
5150                mReceivers.addActivity(a, "receiver");
5151                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5152                    if (r == null) {
5153                        r = new StringBuilder(256);
5154                    } else {
5155                        r.append(' ');
5156                    }
5157                    r.append(a.info.name);
5158                }
5159            }
5160            if (r != null) {
5161                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5162            }
5163
5164            N = pkg.activities.size();
5165            r = null;
5166            for (i=0; i<N; i++) {
5167                PackageParser.Activity a = pkg.activities.get(i);
5168                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5169                        a.info.processName, pkg.applicationInfo.uid);
5170                mActivities.addActivity(a, "activity");
5171                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5172                    if (r == null) {
5173                        r = new StringBuilder(256);
5174                    } else {
5175                        r.append(' ');
5176                    }
5177                    r.append(a.info.name);
5178                }
5179            }
5180            if (r != null) {
5181                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5182            }
5183
5184            N = pkg.permissionGroups.size();
5185            r = null;
5186            for (i=0; i<N; i++) {
5187                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5188                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5189                if (cur == null) {
5190                    mPermissionGroups.put(pg.info.name, pg);
5191                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5192                        if (r == null) {
5193                            r = new StringBuilder(256);
5194                        } else {
5195                            r.append(' ');
5196                        }
5197                        r.append(pg.info.name);
5198                    }
5199                } else {
5200                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5201                            + pg.info.packageName + " ignored: original from "
5202                            + cur.info.packageName);
5203                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5204                        if (r == null) {
5205                            r = new StringBuilder(256);
5206                        } else {
5207                            r.append(' ');
5208                        }
5209                        r.append("DUP:");
5210                        r.append(pg.info.name);
5211                    }
5212                }
5213            }
5214            if (r != null) {
5215                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5216            }
5217
5218            N = pkg.permissions.size();
5219            r = null;
5220            for (i=0; i<N; i++) {
5221                PackageParser.Permission p = pkg.permissions.get(i);
5222                HashMap<String, BasePermission> permissionMap =
5223                        p.tree ? mSettings.mPermissionTrees
5224                        : mSettings.mPermissions;
5225                p.group = mPermissionGroups.get(p.info.group);
5226                if (p.info.group == null || p.group != null) {
5227                    BasePermission bp = permissionMap.get(p.info.name);
5228                    if (bp == null) {
5229                        bp = new BasePermission(p.info.name, p.info.packageName,
5230                                BasePermission.TYPE_NORMAL);
5231                        permissionMap.put(p.info.name, bp);
5232                    }
5233                    if (bp.perm == null) {
5234                        if (bp.sourcePackage != null
5235                                && !bp.sourcePackage.equals(p.info.packageName)) {
5236                            // If this is a permission that was formerly defined by a non-system
5237                            // app, but is now defined by a system app (following an upgrade),
5238                            // discard the previous declaration and consider the system's to be
5239                            // canonical.
5240                            if (isSystemApp(p.owner)) {
5241                                Slog.i(TAG, "New decl " + p.owner + " of permission  "
5242                                        + p.info.name + " is system");
5243                                bp.sourcePackage = null;
5244                            }
5245                        }
5246                        if (bp.sourcePackage == null
5247                                || bp.sourcePackage.equals(p.info.packageName)) {
5248                            BasePermission tree = findPermissionTreeLP(p.info.name);
5249                            if (tree == null
5250                                    || tree.sourcePackage.equals(p.info.packageName)) {
5251                                bp.packageSetting = pkgSetting;
5252                                bp.perm = p;
5253                                bp.uid = pkg.applicationInfo.uid;
5254                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5255                                    if (r == null) {
5256                                        r = new StringBuilder(256);
5257                                    } else {
5258                                        r.append(' ');
5259                                    }
5260                                    r.append(p.info.name);
5261                                }
5262                            } else {
5263                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5264                                        + p.info.packageName + " ignored: base tree "
5265                                        + tree.name + " is from package "
5266                                        + tree.sourcePackage);
5267                            }
5268                        } else {
5269                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5270                                    + p.info.packageName + " ignored: original from "
5271                                    + bp.sourcePackage);
5272                        }
5273                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5274                        if (r == null) {
5275                            r = new StringBuilder(256);
5276                        } else {
5277                            r.append(' ');
5278                        }
5279                        r.append("DUP:");
5280                        r.append(p.info.name);
5281                    }
5282                    if (bp.perm == p) {
5283                        bp.protectionLevel = p.info.protectionLevel;
5284                    }
5285                } else {
5286                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5287                            + p.info.packageName + " ignored: no group "
5288                            + p.group);
5289                }
5290            }
5291            if (r != null) {
5292                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5293            }
5294
5295            N = pkg.instrumentation.size();
5296            r = null;
5297            for (i=0; i<N; i++) {
5298                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5299                a.info.packageName = pkg.applicationInfo.packageName;
5300                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5301                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5302                a.info.dataDir = pkg.applicationInfo.dataDir;
5303                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5304                mInstrumentation.put(a.getComponentName(), a);
5305                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5306                    if (r == null) {
5307                        r = new StringBuilder(256);
5308                    } else {
5309                        r.append(' ');
5310                    }
5311                    r.append(a.info.name);
5312                }
5313            }
5314            if (r != null) {
5315                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5316            }
5317
5318            if (pkg.protectedBroadcasts != null) {
5319                N = pkg.protectedBroadcasts.size();
5320                for (i=0; i<N; i++) {
5321                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5322                }
5323            }
5324
5325            pkgSetting.setTimeStamp(scanFileTime);
5326
5327            // Create idmap files for pairs of (packages, overlay packages).
5328            // Note: "android", ie framework-res.apk, is handled by native layers.
5329            if (pkg.mOverlayTarget != null) {
5330                // This is an overlay package.
5331                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5332                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5333                        mOverlays.put(pkg.mOverlayTarget,
5334                                new HashMap<String, PackageParser.Package>());
5335                    }
5336                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5337                    map.put(pkg.packageName, pkg);
5338                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5339                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5340                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5341                        return null;
5342                    }
5343                }
5344            } else if (mOverlays.containsKey(pkg.packageName) &&
5345                    !pkg.packageName.equals("android")) {
5346                // This is a regular package, with one or more known overlay packages.
5347                createIdmapsForPackageLI(pkg);
5348            }
5349        }
5350
5351        return pkg;
5352    }
5353
5354    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
5355        synchronized (mPackages) {
5356            mResolverReplaced = true;
5357            // Set up information for custom user intent resolution activity.
5358            mResolveActivity.applicationInfo = pkg.applicationInfo;
5359            mResolveActivity.name = mCustomResolverComponentName.getClassName();
5360            mResolveActivity.packageName = pkg.applicationInfo.packageName;
5361            mResolveActivity.processName = null;
5362            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5363            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
5364                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
5365            mResolveActivity.theme = 0;
5366            mResolveActivity.exported = true;
5367            mResolveActivity.enabled = true;
5368            mResolveInfo.activityInfo = mResolveActivity;
5369            mResolveInfo.priority = 0;
5370            mResolveInfo.preferredOrder = 0;
5371            mResolveInfo.match = 0;
5372            mResolveComponentName = mCustomResolverComponentName;
5373            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
5374                    mResolveComponentName);
5375        }
5376    }
5377
5378    private String calculateApkRoot(final String codePathString) {
5379        final File codePath = new File(codePathString);
5380        final File codeRoot;
5381        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
5382            codeRoot = Environment.getRootDirectory();
5383        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
5384            codeRoot = Environment.getOemDirectory();
5385        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
5386            codeRoot = Environment.getVendorDirectory();
5387        } else {
5388            // Unrecognized code path; take its top real segment as the apk root:
5389            // e.g. /something/app/blah.apk => /something
5390            try {
5391                File f = codePath.getCanonicalFile();
5392                File parent = f.getParentFile();    // non-null because codePath is a file
5393                File tmp;
5394                while ((tmp = parent.getParentFile()) != null) {
5395                    f = parent;
5396                    parent = tmp;
5397                }
5398                codeRoot = f;
5399                Slog.w(TAG, "Unrecognized code path "
5400                        + codePath + " - using " + codeRoot);
5401            } catch (IOException e) {
5402                // Can't canonicalize the lib path -- shenanigans?
5403                Slog.w(TAG, "Can't canonicalize code path " + codePath);
5404                return Environment.getRootDirectory().getPath();
5405            }
5406        }
5407        return codeRoot.getPath();
5408    }
5409
5410    // This is the initial scan-time determination of how to handle a given
5411    // package for purposes of native library location.
5412    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
5413            PackageSetting pkgSetting) {
5414        // "bundled" here means system-installed with no overriding update
5415        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
5416        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
5417        final File libDir;
5418        if (bundledApk) {
5419            // If "/system/lib64/apkname" exists, assume that is the per-package
5420            // native library directory to use; otherwise use "/system/lib/apkname".
5421            String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
5422            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
5423            File packLib64 = new File(lib64, apkName);
5424            libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
5425        } else {
5426            libDir = mAppLibInstallDir;
5427        }
5428        final String nativeLibraryPath = (new File(libDir, apkName)).getPath();
5429        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
5430        pkgSetting.nativeLibraryPathString = nativeLibraryPath;
5431    }
5432
5433    // Deduces the required ABI of an upgraded system app.
5434    private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) {
5435        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
5436        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
5437
5438        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
5439        // or similar.
5440        final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath());
5441        final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath());
5442
5443        // Assume that the bundled native libraries always correspond to the
5444        // most preferred 32 or 64 bit ABI.
5445        if (lib64.exists()) {
5446            pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
5447            pkgSetting.requiredCpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0];
5448        } else if (lib.exists()) {
5449            pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5450            pkgSetting.requiredCpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0];
5451        } else {
5452            // This is the case where the app has no native code.
5453            pkg.applicationInfo.requiredCpuAbi = null;
5454            pkgSetting.requiredCpuAbiString = null;
5455        }
5456    }
5457
5458    private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir)
5459            throws IOException {
5460        if (!nativeLibraryDir.isDirectory()) {
5461            nativeLibraryDir.delete();
5462
5463            if (!nativeLibraryDir.mkdir()) {
5464                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
5465            }
5466
5467            try {
5468                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
5469            } catch (ErrnoException e) {
5470                throw new IOException("Cannot chmod native library directory "
5471                        + nativeLibraryDir.getPath(), e);
5472            }
5473        } else if (!SELinux.restorecon(nativeLibraryDir)) {
5474            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
5475        }
5476
5477        /*
5478         * If this is an internal application or our nativeLibraryPath points to
5479         * the app-lib directory, unpack the libraries if necessary.
5480         */
5481        final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5482        try {
5483            int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS);
5484            if (abi >= 0) {
5485                int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
5486                        nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
5487                if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
5488                    return copyRet;
5489                }
5490            }
5491
5492            return abi;
5493        } finally {
5494            handle.close();
5495        }
5496    }
5497
5498    private void killApplication(String pkgName, int appId, String reason) {
5499        // Request the ActivityManager to kill the process(only for existing packages)
5500        // so that we do not end up in a confused state while the user is still using the older
5501        // version of the application while the new one gets installed.
5502        IActivityManager am = ActivityManagerNative.getDefault();
5503        if (am != null) {
5504            try {
5505                am.killApplicationWithAppId(pkgName, appId, reason);
5506            } catch (RemoteException e) {
5507            }
5508        }
5509    }
5510
5511    void removePackageLI(PackageSetting ps, boolean chatty) {
5512        if (DEBUG_INSTALL) {
5513            if (chatty)
5514                Log.d(TAG, "Removing package " + ps.name);
5515        }
5516
5517        // writer
5518        synchronized (mPackages) {
5519            mPackages.remove(ps.name);
5520            if (ps.codePathString != null) {
5521                mAppDirs.remove(ps.codePathString);
5522            }
5523
5524            final PackageParser.Package pkg = ps.pkg;
5525            if (pkg != null) {
5526                cleanPackageDataStructuresLILPw(pkg, chatty);
5527            }
5528        }
5529    }
5530
5531    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
5532        if (DEBUG_INSTALL) {
5533            if (chatty)
5534                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
5535        }
5536
5537        // writer
5538        synchronized (mPackages) {
5539            mPackages.remove(pkg.applicationInfo.packageName);
5540            if (pkg.mPath != null) {
5541                mAppDirs.remove(pkg.mPath);
5542            }
5543            cleanPackageDataStructuresLILPw(pkg, chatty);
5544        }
5545    }
5546
5547    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
5548        int N = pkg.providers.size();
5549        StringBuilder r = null;
5550        int i;
5551        for (i=0; i<N; i++) {
5552            PackageParser.Provider p = pkg.providers.get(i);
5553            mProviders.removeProvider(p);
5554            if (p.info.authority == null) {
5555
5556                /* There was another ContentProvider with this authority when
5557                 * this app was installed so this authority is null,
5558                 * Ignore it as we don't have to unregister the provider.
5559                 */
5560                continue;
5561            }
5562            String names[] = p.info.authority.split(";");
5563            for (int j = 0; j < names.length; j++) {
5564                if (mProvidersByAuthority.get(names[j]) == p) {
5565                    mProvidersByAuthority.remove(names[j]);
5566                    if (DEBUG_REMOVE) {
5567                        if (chatty)
5568                            Log.d(TAG, "Unregistered content provider: " + names[j]
5569                                    + ", className = " + p.info.name + ", isSyncable = "
5570                                    + p.info.isSyncable);
5571                    }
5572                }
5573            }
5574            if (DEBUG_REMOVE && chatty) {
5575                if (r == null) {
5576                    r = new StringBuilder(256);
5577                } else {
5578                    r.append(' ');
5579                }
5580                r.append(p.info.name);
5581            }
5582        }
5583        if (r != null) {
5584            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
5585        }
5586
5587        N = pkg.services.size();
5588        r = null;
5589        for (i=0; i<N; i++) {
5590            PackageParser.Service s = pkg.services.get(i);
5591            mServices.removeService(s);
5592            if (chatty) {
5593                if (r == null) {
5594                    r = new StringBuilder(256);
5595                } else {
5596                    r.append(' ');
5597                }
5598                r.append(s.info.name);
5599            }
5600        }
5601        if (r != null) {
5602            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
5603        }
5604
5605        N = pkg.receivers.size();
5606        r = null;
5607        for (i=0; i<N; i++) {
5608            PackageParser.Activity a = pkg.receivers.get(i);
5609            mReceivers.removeActivity(a, "receiver");
5610            if (DEBUG_REMOVE && chatty) {
5611                if (r == null) {
5612                    r = new StringBuilder(256);
5613                } else {
5614                    r.append(' ');
5615                }
5616                r.append(a.info.name);
5617            }
5618        }
5619        if (r != null) {
5620            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
5621        }
5622
5623        N = pkg.activities.size();
5624        r = null;
5625        for (i=0; i<N; i++) {
5626            PackageParser.Activity a = pkg.activities.get(i);
5627            mActivities.removeActivity(a, "activity");
5628            if (DEBUG_REMOVE && chatty) {
5629                if (r == null) {
5630                    r = new StringBuilder(256);
5631                } else {
5632                    r.append(' ');
5633                }
5634                r.append(a.info.name);
5635            }
5636        }
5637        if (r != null) {
5638            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
5639        }
5640
5641        N = pkg.permissions.size();
5642        r = null;
5643        for (i=0; i<N; i++) {
5644            PackageParser.Permission p = pkg.permissions.get(i);
5645            BasePermission bp = mSettings.mPermissions.get(p.info.name);
5646            if (bp == null) {
5647                bp = mSettings.mPermissionTrees.get(p.info.name);
5648            }
5649            if (bp != null && bp.perm == p) {
5650                bp.perm = null;
5651                if (DEBUG_REMOVE && chatty) {
5652                    if (r == null) {
5653                        r = new StringBuilder(256);
5654                    } else {
5655                        r.append(' ');
5656                    }
5657                    r.append(p.info.name);
5658                }
5659            }
5660        }
5661        if (r != null) {
5662            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
5663        }
5664
5665        N = pkg.instrumentation.size();
5666        r = null;
5667        for (i=0; i<N; i++) {
5668            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5669            mInstrumentation.remove(a.getComponentName());
5670            if (DEBUG_REMOVE && chatty) {
5671                if (r == null) {
5672                    r = new StringBuilder(256);
5673                } else {
5674                    r.append(' ');
5675                }
5676                r.append(a.info.name);
5677            }
5678        }
5679        if (r != null) {
5680            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
5681        }
5682
5683        r = null;
5684        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5685            // Only system apps can hold shared libraries.
5686            if (pkg.libraryNames != null) {
5687                for (i=0; i<pkg.libraryNames.size(); i++) {
5688                    String name = pkg.libraryNames.get(i);
5689                    SharedLibraryEntry cur = mSharedLibraries.get(name);
5690                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
5691                        mSharedLibraries.remove(name);
5692                        if (DEBUG_REMOVE && chatty) {
5693                            if (r == null) {
5694                                r = new StringBuilder(256);
5695                            } else {
5696                                r.append(' ');
5697                            }
5698                            r.append(name);
5699                        }
5700                    }
5701                }
5702            }
5703        }
5704        if (r != null) {
5705            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
5706        }
5707    }
5708
5709    private static final boolean isPackageFilename(String name) {
5710        return name != null && name.endsWith(".apk");
5711    }
5712
5713    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
5714        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
5715            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
5716                return true;
5717            }
5718        }
5719        return false;
5720    }
5721
5722    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
5723    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
5724    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
5725
5726    private void updatePermissionsLPw(String changingPkg,
5727            PackageParser.Package pkgInfo, int flags) {
5728        // Make sure there are no dangling permission trees.
5729        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
5730        while (it.hasNext()) {
5731            final BasePermission bp = it.next();
5732            if (bp.packageSetting == null) {
5733                // We may not yet have parsed the package, so just see if
5734                // we still know about its settings.
5735                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
5736            }
5737            if (bp.packageSetting == null) {
5738                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
5739                        + " from package " + bp.sourcePackage);
5740                it.remove();
5741            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
5742                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
5743                    Slog.i(TAG, "Removing old permission tree: " + bp.name
5744                            + " from package " + bp.sourcePackage);
5745                    flags |= UPDATE_PERMISSIONS_ALL;
5746                    it.remove();
5747                }
5748            }
5749        }
5750
5751        // Make sure all dynamic permissions have been assigned to a package,
5752        // and make sure there are no dangling permissions.
5753        it = mSettings.mPermissions.values().iterator();
5754        while (it.hasNext()) {
5755            final BasePermission bp = it.next();
5756            if (bp.type == BasePermission.TYPE_DYNAMIC) {
5757                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
5758                        + bp.name + " pkg=" + bp.sourcePackage
5759                        + " info=" + bp.pendingInfo);
5760                if (bp.packageSetting == null && bp.pendingInfo != null) {
5761                    final BasePermission tree = findPermissionTreeLP(bp.name);
5762                    if (tree != null && tree.perm != null) {
5763                        bp.packageSetting = tree.packageSetting;
5764                        bp.perm = new PackageParser.Permission(tree.perm.owner,
5765                                new PermissionInfo(bp.pendingInfo));
5766                        bp.perm.info.packageName = tree.perm.info.packageName;
5767                        bp.perm.info.name = bp.name;
5768                        bp.uid = tree.uid;
5769                    }
5770                }
5771            }
5772            if (bp.packageSetting == null) {
5773                // We may not yet have parsed the package, so just see if
5774                // we still know about its settings.
5775                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
5776            }
5777            if (bp.packageSetting == null) {
5778                Slog.w(TAG, "Removing dangling permission: " + bp.name
5779                        + " from package " + bp.sourcePackage);
5780                it.remove();
5781            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
5782                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
5783                    Slog.i(TAG, "Removing old permission: " + bp.name
5784                            + " from package " + bp.sourcePackage);
5785                    flags |= UPDATE_PERMISSIONS_ALL;
5786                    it.remove();
5787                }
5788            }
5789        }
5790
5791        // Now update the permissions for all packages, in particular
5792        // replace the granted permissions of the system packages.
5793        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
5794            for (PackageParser.Package pkg : mPackages.values()) {
5795                if (pkg != pkgInfo) {
5796                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
5797                }
5798            }
5799        }
5800
5801        if (pkgInfo != null) {
5802            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
5803        }
5804    }
5805
5806    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
5807        final PackageSetting ps = (PackageSetting) pkg.mExtras;
5808        if (ps == null) {
5809            return;
5810        }
5811        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
5812        HashSet<String> origPermissions = gp.grantedPermissions;
5813        boolean changedPermission = false;
5814
5815        if (replace) {
5816            ps.permissionsFixed = false;
5817            if (gp == ps) {
5818                origPermissions = new HashSet<String>(gp.grantedPermissions);
5819                gp.grantedPermissions.clear();
5820                gp.gids = mGlobalGids;
5821            }
5822        }
5823
5824        if (gp.gids == null) {
5825            gp.gids = mGlobalGids;
5826        }
5827
5828        final int N = pkg.requestedPermissions.size();
5829        for (int i=0; i<N; i++) {
5830            final String name = pkg.requestedPermissions.get(i);
5831            final boolean required = pkg.requestedPermissionsRequired.get(i);
5832            final BasePermission bp = mSettings.mPermissions.get(name);
5833            if (DEBUG_INSTALL) {
5834                if (gp != ps) {
5835                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
5836                }
5837            }
5838
5839            if (bp == null || bp.packageSetting == null) {
5840                Slog.w(TAG, "Unknown permission " + name
5841                        + " in package " + pkg.packageName);
5842                continue;
5843            }
5844
5845            final String perm = bp.name;
5846            boolean allowed;
5847            boolean allowedSig = false;
5848            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
5849            if (level == PermissionInfo.PROTECTION_NORMAL
5850                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
5851                // We grant a normal or dangerous permission if any of the following
5852                // are true:
5853                // 1) The permission is required
5854                // 2) The permission is optional, but was granted in the past
5855                // 3) The permission is optional, but was requested by an
5856                //    app in /system (not /data)
5857                //
5858                // Otherwise, reject the permission.
5859                allowed = (required || origPermissions.contains(perm)
5860                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
5861            } else if (bp.packageSetting == null) {
5862                // This permission is invalid; skip it.
5863                allowed = false;
5864            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
5865                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
5866                if (allowed) {
5867                    allowedSig = true;
5868                }
5869            } else {
5870                allowed = false;
5871            }
5872            if (DEBUG_INSTALL) {
5873                if (gp != ps) {
5874                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
5875                }
5876            }
5877            if (allowed) {
5878                if (!isSystemApp(ps) && ps.permissionsFixed) {
5879                    // If this is an existing, non-system package, then
5880                    // we can't add any new permissions to it.
5881                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
5882                        // Except...  if this is a permission that was added
5883                        // to the platform (note: need to only do this when
5884                        // updating the platform).
5885                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
5886                    }
5887                }
5888                if (allowed) {
5889                    if (!gp.grantedPermissions.contains(perm)) {
5890                        changedPermission = true;
5891                        gp.grantedPermissions.add(perm);
5892                        gp.gids = appendInts(gp.gids, bp.gids);
5893                    } else if (!ps.haveGids) {
5894                        gp.gids = appendInts(gp.gids, bp.gids);
5895                    }
5896                } else {
5897                    Slog.w(TAG, "Not granting permission " + perm
5898                            + " to package " + pkg.packageName
5899                            + " because it was previously installed without");
5900                }
5901            } else {
5902                if (gp.grantedPermissions.remove(perm)) {
5903                    changedPermission = true;
5904                    gp.gids = removeInts(gp.gids, bp.gids);
5905                    Slog.i(TAG, "Un-granting permission " + perm
5906                            + " from package " + pkg.packageName
5907                            + " (protectionLevel=" + bp.protectionLevel
5908                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
5909                            + ")");
5910                } else {
5911                    Slog.w(TAG, "Not granting permission " + perm
5912                            + " to package " + pkg.packageName
5913                            + " (protectionLevel=" + bp.protectionLevel
5914                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
5915                            + ")");
5916                }
5917            }
5918        }
5919
5920        if ((changedPermission || replace) && !ps.permissionsFixed &&
5921                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
5922            // This is the first that we have heard about this package, so the
5923            // permissions we have now selected are fixed until explicitly
5924            // changed.
5925            ps.permissionsFixed = true;
5926        }
5927        ps.haveGids = true;
5928    }
5929
5930    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
5931        boolean allowed = false;
5932        final int NP = PackageParser.NEW_PERMISSIONS.length;
5933        for (int ip=0; ip<NP; ip++) {
5934            final PackageParser.NewPermissionInfo npi
5935                    = PackageParser.NEW_PERMISSIONS[ip];
5936            if (npi.name.equals(perm)
5937                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
5938                allowed = true;
5939                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
5940                        + pkg.packageName);
5941                break;
5942            }
5943        }
5944        return allowed;
5945    }
5946
5947    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
5948                                          BasePermission bp, HashSet<String> origPermissions) {
5949        boolean allowed;
5950        allowed = (compareSignatures(
5951                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
5952                        == PackageManager.SIGNATURE_MATCH)
5953                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
5954                        == PackageManager.SIGNATURE_MATCH);
5955        if (!allowed && (bp.protectionLevel
5956                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
5957            if (isSystemApp(pkg)) {
5958                // For updated system applications, a system permission
5959                // is granted only if it had been defined by the original application.
5960                if (isUpdatedSystemApp(pkg)) {
5961                    final PackageSetting sysPs = mSettings
5962                            .getDisabledSystemPkgLPr(pkg.packageName);
5963                    final GrantedPermissions origGp = sysPs.sharedUser != null
5964                            ? sysPs.sharedUser : sysPs;
5965
5966                    if (origGp.grantedPermissions.contains(perm)) {
5967                        // If the original was granted this permission, we take
5968                        // that grant decision as read and propagate it to the
5969                        // update.
5970                        allowed = true;
5971                    } else {
5972                        // The system apk may have been updated with an older
5973                        // version of the one on the data partition, but which
5974                        // granted a new system permission that it didn't have
5975                        // before.  In this case we do want to allow the app to
5976                        // now get the new permission if the ancestral apk is
5977                        // privileged to get it.
5978                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
5979                            for (int j=0;
5980                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
5981                                if (perm.equals(
5982                                        sysPs.pkg.requestedPermissions.get(j))) {
5983                                    allowed = true;
5984                                    break;
5985                                }
5986                            }
5987                        }
5988                    }
5989                } else {
5990                    allowed = isPrivilegedApp(pkg);
5991                }
5992            }
5993        }
5994        if (!allowed && (bp.protectionLevel
5995                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
5996            // For development permissions, a development permission
5997            // is granted only if it was already granted.
5998            allowed = origPermissions.contains(perm);
5999        }
6000        return allowed;
6001    }
6002
6003    final class ActivityIntentResolver
6004            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6005        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6006                boolean defaultOnly, int userId) {
6007            if (!sUserManager.exists(userId)) return null;
6008            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6009            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6010        }
6011
6012        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6013                int userId) {
6014            if (!sUserManager.exists(userId)) return null;
6015            mFlags = flags;
6016            return super.queryIntent(intent, resolvedType,
6017                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6018        }
6019
6020        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6021                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6022            if (!sUserManager.exists(userId)) return null;
6023            if (packageActivities == null) {
6024                return null;
6025            }
6026            mFlags = flags;
6027            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6028            final int N = packageActivities.size();
6029            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6030                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6031
6032            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6033            for (int i = 0; i < N; ++i) {
6034                intentFilters = packageActivities.get(i).intents;
6035                if (intentFilters != null && intentFilters.size() > 0) {
6036                    PackageParser.ActivityIntentInfo[] array =
6037                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6038                    intentFilters.toArray(array);
6039                    listCut.add(array);
6040                }
6041            }
6042            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6043        }
6044
6045        public final void addActivity(PackageParser.Activity a, String type) {
6046            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6047            mActivities.put(a.getComponentName(), a);
6048            if (DEBUG_SHOW_INFO)
6049                Log.v(
6050                TAG, "  " + type + " " +
6051                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6052            if (DEBUG_SHOW_INFO)
6053                Log.v(TAG, "    Class=" + a.info.name);
6054            final int NI = a.intents.size();
6055            for (int j=0; j<NI; j++) {
6056                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6057                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6058                    intent.setPriority(0);
6059                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6060                            + a.className + " with priority > 0, forcing to 0");
6061                }
6062                if (DEBUG_SHOW_INFO) {
6063                    Log.v(TAG, "    IntentFilter:");
6064                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6065                }
6066                if (!intent.debugCheck()) {
6067                    Log.w(TAG, "==> For Activity " + a.info.name);
6068                }
6069                addFilter(intent);
6070            }
6071        }
6072
6073        public final void removeActivity(PackageParser.Activity a, String type) {
6074            mActivities.remove(a.getComponentName());
6075            if (DEBUG_SHOW_INFO) {
6076                Log.v(TAG, "  " + type + " "
6077                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6078                                : a.info.name) + ":");
6079                Log.v(TAG, "    Class=" + a.info.name);
6080            }
6081            final int NI = a.intents.size();
6082            for (int j=0; j<NI; j++) {
6083                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6084                if (DEBUG_SHOW_INFO) {
6085                    Log.v(TAG, "    IntentFilter:");
6086                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6087                }
6088                removeFilter(intent);
6089            }
6090        }
6091
6092        @Override
6093        protected boolean allowFilterResult(
6094                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6095            ActivityInfo filterAi = filter.activity.info;
6096            for (int i=dest.size()-1; i>=0; i--) {
6097                ActivityInfo destAi = dest.get(i).activityInfo;
6098                if (destAi.name == filterAi.name
6099                        && destAi.packageName == filterAi.packageName) {
6100                    return false;
6101                }
6102            }
6103            return true;
6104        }
6105
6106        @Override
6107        protected ActivityIntentInfo[] newArray(int size) {
6108            return new ActivityIntentInfo[size];
6109        }
6110
6111        @Override
6112        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6113            if (!sUserManager.exists(userId)) return true;
6114            PackageParser.Package p = filter.activity.owner;
6115            if (p != null) {
6116                PackageSetting ps = (PackageSetting)p.mExtras;
6117                if (ps != null) {
6118                    // System apps are never considered stopped for purposes of
6119                    // filtering, because there may be no way for the user to
6120                    // actually re-launch them.
6121                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6122                            && ps.getStopped(userId);
6123                }
6124            }
6125            return false;
6126        }
6127
6128        @Override
6129        protected boolean isPackageForFilter(String packageName,
6130                PackageParser.ActivityIntentInfo info) {
6131            return packageName.equals(info.activity.owner.packageName);
6132        }
6133
6134        @Override
6135        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6136                int match, int userId) {
6137            if (!sUserManager.exists(userId)) return null;
6138            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6139                return null;
6140            }
6141            final PackageParser.Activity activity = info.activity;
6142            if (mSafeMode && (activity.info.applicationInfo.flags
6143                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6144                return null;
6145            }
6146            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6147            if (ps == null) {
6148                return null;
6149            }
6150            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6151                    ps.readUserState(userId), userId);
6152            if (ai == null) {
6153                return null;
6154            }
6155            final ResolveInfo res = new ResolveInfo();
6156            res.activityInfo = ai;
6157            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6158                res.filter = info;
6159            }
6160            res.priority = info.getPriority();
6161            res.preferredOrder = activity.owner.mPreferredOrder;
6162            //System.out.println("Result: " + res.activityInfo.className +
6163            //                   " = " + res.priority);
6164            res.match = match;
6165            res.isDefault = info.hasDefault;
6166            res.labelRes = info.labelRes;
6167            res.nonLocalizedLabel = info.nonLocalizedLabel;
6168            res.icon = info.icon;
6169            res.system = isSystemApp(res.activityInfo.applicationInfo);
6170            return res;
6171        }
6172
6173        @Override
6174        protected void sortResults(List<ResolveInfo> results) {
6175            Collections.sort(results, mResolvePrioritySorter);
6176        }
6177
6178        @Override
6179        protected void dumpFilter(PrintWriter out, String prefix,
6180                PackageParser.ActivityIntentInfo filter) {
6181            out.print(prefix); out.print(
6182                    Integer.toHexString(System.identityHashCode(filter.activity)));
6183                    out.print(' ');
6184                    filter.activity.printComponentShortName(out);
6185                    out.print(" filter ");
6186                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6187        }
6188
6189//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6190//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6191//            final List<ResolveInfo> retList = Lists.newArrayList();
6192//            while (i.hasNext()) {
6193//                final ResolveInfo resolveInfo = i.next();
6194//                if (isEnabledLP(resolveInfo.activityInfo)) {
6195//                    retList.add(resolveInfo);
6196//                }
6197//            }
6198//            return retList;
6199//        }
6200
6201        // Keys are String (activity class name), values are Activity.
6202        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6203                = new HashMap<ComponentName, PackageParser.Activity>();
6204        private int mFlags;
6205    }
6206
6207    private final class ServiceIntentResolver
6208            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6209        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6210                boolean defaultOnly, int userId) {
6211            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6212            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6213        }
6214
6215        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6216                int userId) {
6217            if (!sUserManager.exists(userId)) return null;
6218            mFlags = flags;
6219            return super.queryIntent(intent, resolvedType,
6220                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6221        }
6222
6223        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6224                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6225            if (!sUserManager.exists(userId)) return null;
6226            if (packageServices == null) {
6227                return null;
6228            }
6229            mFlags = flags;
6230            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6231            final int N = packageServices.size();
6232            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6233                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6234
6235            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6236            for (int i = 0; i < N; ++i) {
6237                intentFilters = packageServices.get(i).intents;
6238                if (intentFilters != null && intentFilters.size() > 0) {
6239                    PackageParser.ServiceIntentInfo[] array =
6240                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6241                    intentFilters.toArray(array);
6242                    listCut.add(array);
6243                }
6244            }
6245            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6246        }
6247
6248        public final void addService(PackageParser.Service s) {
6249            mServices.put(s.getComponentName(), s);
6250            if (DEBUG_SHOW_INFO) {
6251                Log.v(TAG, "  "
6252                        + (s.info.nonLocalizedLabel != null
6253                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6254                Log.v(TAG, "    Class=" + s.info.name);
6255            }
6256            final int NI = s.intents.size();
6257            int j;
6258            for (j=0; j<NI; j++) {
6259                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6260                if (DEBUG_SHOW_INFO) {
6261                    Log.v(TAG, "    IntentFilter:");
6262                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6263                }
6264                if (!intent.debugCheck()) {
6265                    Log.w(TAG, "==> For Service " + s.info.name);
6266                }
6267                addFilter(intent);
6268            }
6269        }
6270
6271        public final void removeService(PackageParser.Service s) {
6272            mServices.remove(s.getComponentName());
6273            if (DEBUG_SHOW_INFO) {
6274                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
6275                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6276                Log.v(TAG, "    Class=" + s.info.name);
6277            }
6278            final int NI = s.intents.size();
6279            int j;
6280            for (j=0; j<NI; j++) {
6281                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6282                if (DEBUG_SHOW_INFO) {
6283                    Log.v(TAG, "    IntentFilter:");
6284                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6285                }
6286                removeFilter(intent);
6287            }
6288        }
6289
6290        @Override
6291        protected boolean allowFilterResult(
6292                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
6293            ServiceInfo filterSi = filter.service.info;
6294            for (int i=dest.size()-1; i>=0; i--) {
6295                ServiceInfo destAi = dest.get(i).serviceInfo;
6296                if (destAi.name == filterSi.name
6297                        && destAi.packageName == filterSi.packageName) {
6298                    return false;
6299                }
6300            }
6301            return true;
6302        }
6303
6304        @Override
6305        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
6306            return new PackageParser.ServiceIntentInfo[size];
6307        }
6308
6309        @Override
6310        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
6311            if (!sUserManager.exists(userId)) return true;
6312            PackageParser.Package p = filter.service.owner;
6313            if (p != null) {
6314                PackageSetting ps = (PackageSetting)p.mExtras;
6315                if (ps != null) {
6316                    // System apps are never considered stopped for purposes of
6317                    // filtering, because there may be no way for the user to
6318                    // actually re-launch them.
6319                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6320                            && ps.getStopped(userId);
6321                }
6322            }
6323            return false;
6324        }
6325
6326        @Override
6327        protected boolean isPackageForFilter(String packageName,
6328                PackageParser.ServiceIntentInfo info) {
6329            return packageName.equals(info.service.owner.packageName);
6330        }
6331
6332        @Override
6333        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
6334                int match, int userId) {
6335            if (!sUserManager.exists(userId)) return null;
6336            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
6337            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
6338                return null;
6339            }
6340            final PackageParser.Service service = info.service;
6341            if (mSafeMode && (service.info.applicationInfo.flags
6342                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6343                return null;
6344            }
6345            PackageSetting ps = (PackageSetting) service.owner.mExtras;
6346            if (ps == null) {
6347                return null;
6348            }
6349            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
6350                    ps.readUserState(userId), userId);
6351            if (si == null) {
6352                return null;
6353            }
6354            final ResolveInfo res = new ResolveInfo();
6355            res.serviceInfo = si;
6356            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6357                res.filter = filter;
6358            }
6359            res.priority = info.getPriority();
6360            res.preferredOrder = service.owner.mPreferredOrder;
6361            //System.out.println("Result: " + res.activityInfo.className +
6362            //                   " = " + res.priority);
6363            res.match = match;
6364            res.isDefault = info.hasDefault;
6365            res.labelRes = info.labelRes;
6366            res.nonLocalizedLabel = info.nonLocalizedLabel;
6367            res.icon = info.icon;
6368            res.system = isSystemApp(res.serviceInfo.applicationInfo);
6369            return res;
6370        }
6371
6372        @Override
6373        protected void sortResults(List<ResolveInfo> results) {
6374            Collections.sort(results, mResolvePrioritySorter);
6375        }
6376
6377        @Override
6378        protected void dumpFilter(PrintWriter out, String prefix,
6379                PackageParser.ServiceIntentInfo filter) {
6380            out.print(prefix); out.print(
6381                    Integer.toHexString(System.identityHashCode(filter.service)));
6382                    out.print(' ');
6383                    filter.service.printComponentShortName(out);
6384                    out.print(" filter ");
6385                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6386        }
6387
6388//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6389//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6390//            final List<ResolveInfo> retList = Lists.newArrayList();
6391//            while (i.hasNext()) {
6392//                final ResolveInfo resolveInfo = (ResolveInfo) i;
6393//                if (isEnabledLP(resolveInfo.serviceInfo)) {
6394//                    retList.add(resolveInfo);
6395//                }
6396//            }
6397//            return retList;
6398//        }
6399
6400        // Keys are String (activity class name), values are Activity.
6401        private final HashMap<ComponentName, PackageParser.Service> mServices
6402                = new HashMap<ComponentName, PackageParser.Service>();
6403        private int mFlags;
6404    };
6405
6406    private final class ProviderIntentResolver
6407            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
6408        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6409                boolean defaultOnly, int userId) {
6410            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6411            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6412        }
6413
6414        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6415                int userId) {
6416            if (!sUserManager.exists(userId))
6417                return null;
6418            mFlags = flags;
6419            return super.queryIntent(intent, resolvedType,
6420                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6421        }
6422
6423        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6424                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
6425            if (!sUserManager.exists(userId))
6426                return null;
6427            if (packageProviders == null) {
6428                return null;
6429            }
6430            mFlags = flags;
6431            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
6432            final int N = packageProviders.size();
6433            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
6434                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
6435
6436            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
6437            for (int i = 0; i < N; ++i) {
6438                intentFilters = packageProviders.get(i).intents;
6439                if (intentFilters != null && intentFilters.size() > 0) {
6440                    PackageParser.ProviderIntentInfo[] array =
6441                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
6442                    intentFilters.toArray(array);
6443                    listCut.add(array);
6444                }
6445            }
6446            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6447        }
6448
6449        public final void addProvider(PackageParser.Provider p) {
6450            mProviders.put(p.getComponentName(), p);
6451            if (DEBUG_SHOW_INFO) {
6452                Log.v(TAG, "  "
6453                        + (p.info.nonLocalizedLabel != null
6454                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
6455                Log.v(TAG, "    Class=" + p.info.name);
6456            }
6457            final int NI = p.intents.size();
6458            int j;
6459            for (j = 0; j < NI; j++) {
6460                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
6461                if (DEBUG_SHOW_INFO) {
6462                    Log.v(TAG, "    IntentFilter:");
6463                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6464                }
6465                if (!intent.debugCheck()) {
6466                    Log.w(TAG, "==> For Provider " + p.info.name);
6467                }
6468                addFilter(intent);
6469            }
6470        }
6471
6472        public final void removeProvider(PackageParser.Provider p) {
6473            mProviders.remove(p.getComponentName());
6474            if (DEBUG_SHOW_INFO) {
6475                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
6476                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
6477                Log.v(TAG, "    Class=" + p.info.name);
6478            }
6479            final int NI = p.intents.size();
6480            int j;
6481            for (j = 0; j < NI; j++) {
6482                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
6483                if (DEBUG_SHOW_INFO) {
6484                    Log.v(TAG, "    IntentFilter:");
6485                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6486                }
6487                removeFilter(intent);
6488            }
6489        }
6490
6491        @Override
6492        protected boolean allowFilterResult(
6493                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
6494            ProviderInfo filterPi = filter.provider.info;
6495            for (int i = dest.size() - 1; i >= 0; i--) {
6496                ProviderInfo destPi = dest.get(i).providerInfo;
6497                if (destPi.name == filterPi.name
6498                        && destPi.packageName == filterPi.packageName) {
6499                    return false;
6500                }
6501            }
6502            return true;
6503        }
6504
6505        @Override
6506        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
6507            return new PackageParser.ProviderIntentInfo[size];
6508        }
6509
6510        @Override
6511        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
6512            if (!sUserManager.exists(userId))
6513                return true;
6514            PackageParser.Package p = filter.provider.owner;
6515            if (p != null) {
6516                PackageSetting ps = (PackageSetting) p.mExtras;
6517                if (ps != null) {
6518                    // System apps are never considered stopped for purposes of
6519                    // filtering, because there may be no way for the user to
6520                    // actually re-launch them.
6521                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6522                            && ps.getStopped(userId);
6523                }
6524            }
6525            return false;
6526        }
6527
6528        @Override
6529        protected boolean isPackageForFilter(String packageName,
6530                PackageParser.ProviderIntentInfo info) {
6531            return packageName.equals(info.provider.owner.packageName);
6532        }
6533
6534        @Override
6535        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
6536                int match, int userId) {
6537            if (!sUserManager.exists(userId))
6538                return null;
6539            final PackageParser.ProviderIntentInfo info = filter;
6540            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
6541                return null;
6542            }
6543            final PackageParser.Provider provider = info.provider;
6544            if (mSafeMode && (provider.info.applicationInfo.flags
6545                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
6546                return null;
6547            }
6548            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
6549            if (ps == null) {
6550                return null;
6551            }
6552            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
6553                    ps.readUserState(userId), userId);
6554            if (pi == null) {
6555                return null;
6556            }
6557            final ResolveInfo res = new ResolveInfo();
6558            res.providerInfo = pi;
6559            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
6560                res.filter = filter;
6561            }
6562            res.priority = info.getPriority();
6563            res.preferredOrder = provider.owner.mPreferredOrder;
6564            res.match = match;
6565            res.isDefault = info.hasDefault;
6566            res.labelRes = info.labelRes;
6567            res.nonLocalizedLabel = info.nonLocalizedLabel;
6568            res.icon = info.icon;
6569            res.system = isSystemApp(res.providerInfo.applicationInfo);
6570            return res;
6571        }
6572
6573        @Override
6574        protected void sortResults(List<ResolveInfo> results) {
6575            Collections.sort(results, mResolvePrioritySorter);
6576        }
6577
6578        @Override
6579        protected void dumpFilter(PrintWriter out, String prefix,
6580                PackageParser.ProviderIntentInfo filter) {
6581            out.print(prefix);
6582            out.print(
6583                    Integer.toHexString(System.identityHashCode(filter.provider)));
6584            out.print(' ');
6585            filter.provider.printComponentShortName(out);
6586            out.print(" filter ");
6587            out.println(Integer.toHexString(System.identityHashCode(filter)));
6588        }
6589
6590        private final HashMap<ComponentName, PackageParser.Provider> mProviders
6591                = new HashMap<ComponentName, PackageParser.Provider>();
6592        private int mFlags;
6593    };
6594
6595    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
6596            new Comparator<ResolveInfo>() {
6597        public int compare(ResolveInfo r1, ResolveInfo r2) {
6598            int v1 = r1.priority;
6599            int v2 = r2.priority;
6600            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
6601            if (v1 != v2) {
6602                return (v1 > v2) ? -1 : 1;
6603            }
6604            v1 = r1.preferredOrder;
6605            v2 = r2.preferredOrder;
6606            if (v1 != v2) {
6607                return (v1 > v2) ? -1 : 1;
6608            }
6609            if (r1.isDefault != r2.isDefault) {
6610                return r1.isDefault ? -1 : 1;
6611            }
6612            v1 = r1.match;
6613            v2 = r2.match;
6614            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
6615            if (v1 != v2) {
6616                return (v1 > v2) ? -1 : 1;
6617            }
6618            if (r1.system != r2.system) {
6619                return r1.system ? -1 : 1;
6620            }
6621            return 0;
6622        }
6623    };
6624
6625    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
6626            new Comparator<ProviderInfo>() {
6627        public int compare(ProviderInfo p1, ProviderInfo p2) {
6628            final int v1 = p1.initOrder;
6629            final int v2 = p2.initOrder;
6630            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
6631        }
6632    };
6633
6634    static final void sendPackageBroadcast(String action, String pkg,
6635            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
6636            int[] userIds) {
6637        IActivityManager am = ActivityManagerNative.getDefault();
6638        if (am != null) {
6639            try {
6640                if (userIds == null) {
6641                    userIds = am.getRunningUserIds();
6642                }
6643                for (int id : userIds) {
6644                    final Intent intent = new Intent(action,
6645                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
6646                    if (extras != null) {
6647                        intent.putExtras(extras);
6648                    }
6649                    if (targetPkg != null) {
6650                        intent.setPackage(targetPkg);
6651                    }
6652                    // Modify the UID when posting to other users
6653                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
6654                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
6655                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
6656                        intent.putExtra(Intent.EXTRA_UID, uid);
6657                    }
6658                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
6659                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
6660                    if (DEBUG_BROADCASTS) {
6661                        RuntimeException here = new RuntimeException("here");
6662                        here.fillInStackTrace();
6663                        Slog.d(TAG, "Sending to user " + id + ": "
6664                                + intent.toShortString(false, true, false, false)
6665                                + " " + intent.getExtras(), here);
6666                    }
6667                    am.broadcastIntent(null, intent, null, finishedReceiver,
6668                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
6669                            finishedReceiver != null, false, id);
6670                }
6671            } catch (RemoteException ex) {
6672            }
6673        }
6674    }
6675
6676    /**
6677     * Check if the external storage media is available. This is true if there
6678     * is a mounted external storage medium or if the external storage is
6679     * emulated.
6680     */
6681    private boolean isExternalMediaAvailable() {
6682        return mMediaMounted || Environment.isExternalStorageEmulated();
6683    }
6684
6685    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
6686        // writer
6687        synchronized (mPackages) {
6688            if (!isExternalMediaAvailable()) {
6689                // If the external storage is no longer mounted at this point,
6690                // the caller may not have been able to delete all of this
6691                // packages files and can not delete any more.  Bail.
6692                return null;
6693            }
6694            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
6695            if (lastPackage != null) {
6696                pkgs.remove(lastPackage);
6697            }
6698            if (pkgs.size() > 0) {
6699                return pkgs.get(0);
6700            }
6701        }
6702        return null;
6703    }
6704
6705    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
6706        if (false) {
6707            RuntimeException here = new RuntimeException("here");
6708            here.fillInStackTrace();
6709            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
6710                    + " andCode=" + andCode, here);
6711        }
6712        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
6713                userId, andCode ? 1 : 0, packageName));
6714    }
6715
6716    void startCleaningPackages() {
6717        // reader
6718        synchronized (mPackages) {
6719            if (!isExternalMediaAvailable()) {
6720                return;
6721            }
6722            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
6723                return;
6724            }
6725        }
6726        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
6727        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
6728        IActivityManager am = ActivityManagerNative.getDefault();
6729        if (am != null) {
6730            try {
6731                am.startService(null, intent, null, UserHandle.USER_OWNER);
6732            } catch (RemoteException e) {
6733            }
6734        }
6735    }
6736
6737    private final class AppDirObserver extends FileObserver {
6738        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
6739            super(path, mask);
6740            mRootDir = path;
6741            mIsRom = isrom;
6742            mIsPrivileged = isPrivileged;
6743        }
6744
6745        public void onEvent(int event, String path) {
6746            String removedPackage = null;
6747            int removedAppId = -1;
6748            int[] removedUsers = null;
6749            String addedPackage = null;
6750            int addedAppId = -1;
6751            int[] addedUsers = null;
6752
6753            // TODO post a message to the handler to obtain serial ordering
6754            synchronized (mInstallLock) {
6755                String fullPathStr = null;
6756                File fullPath = null;
6757                if (path != null) {
6758                    fullPath = new File(mRootDir, path);
6759                    fullPathStr = fullPath.getPath();
6760                }
6761
6762                if (DEBUG_APP_DIR_OBSERVER)
6763                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
6764
6765                if (!isPackageFilename(path)) {
6766                    if (DEBUG_APP_DIR_OBSERVER)
6767                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
6768                    return;
6769                }
6770
6771                // Ignore packages that are being installed or
6772                // have just been installed.
6773                if (ignoreCodePath(fullPathStr)) {
6774                    return;
6775                }
6776                PackageParser.Package p = null;
6777                PackageSetting ps = null;
6778                // reader
6779                synchronized (mPackages) {
6780                    p = mAppDirs.get(fullPathStr);
6781                    if (p != null) {
6782                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
6783                        if (ps != null) {
6784                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
6785                        } else {
6786                            removedUsers = sUserManager.getUserIds();
6787                        }
6788                    }
6789                    addedUsers = sUserManager.getUserIds();
6790                }
6791                if ((event&REMOVE_EVENTS) != 0) {
6792                    if (ps != null) {
6793                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
6794                        removePackageLI(ps, true);
6795                        removedPackage = ps.name;
6796                        removedAppId = ps.appId;
6797                    }
6798                }
6799
6800                if ((event&ADD_EVENTS) != 0) {
6801                    if (p == null) {
6802                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
6803                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
6804                        if (mIsRom) {
6805                            flags |= PackageParser.PARSE_IS_SYSTEM
6806                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
6807                            if (mIsPrivileged) {
6808                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
6809                            }
6810                        }
6811                        p = scanPackageLI(fullPath, flags,
6812                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
6813                                System.currentTimeMillis(), UserHandle.ALL);
6814                        if (p != null) {
6815                            /*
6816                             * TODO this seems dangerous as the package may have
6817                             * changed since we last acquired the mPackages
6818                             * lock.
6819                             */
6820                            // writer
6821                            synchronized (mPackages) {
6822                                updatePermissionsLPw(p.packageName, p,
6823                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
6824                            }
6825                            addedPackage = p.applicationInfo.packageName;
6826                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
6827                        }
6828                    }
6829                }
6830
6831                // reader
6832                synchronized (mPackages) {
6833                    mSettings.writeLPr();
6834                }
6835            }
6836
6837            if (removedPackage != null) {
6838                Bundle extras = new Bundle(1);
6839                extras.putInt(Intent.EXTRA_UID, removedAppId);
6840                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
6841                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
6842                        extras, null, null, removedUsers);
6843            }
6844            if (addedPackage != null) {
6845                Bundle extras = new Bundle(1);
6846                extras.putInt(Intent.EXTRA_UID, addedAppId);
6847                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
6848                        extras, null, null, addedUsers);
6849            }
6850        }
6851
6852        private final String mRootDir;
6853        private final boolean mIsRom;
6854        private final boolean mIsPrivileged;
6855    }
6856
6857    /* Called when a downloaded package installation has been confirmed by the user */
6858    public void installPackage(
6859            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
6860        installPackage(packageURI, observer, flags, null);
6861    }
6862
6863    /* Called when a downloaded package installation has been confirmed by the user */
6864    public void installPackage(
6865            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
6866            final String installerPackageName) {
6867        installPackageWithVerification(packageURI, observer, flags, installerPackageName, null,
6868                null, null);
6869    }
6870
6871    @Override
6872    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
6873            int flags, String installerPackageName, Uri verificationURI,
6874            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
6875        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
6876                VerificationParams.NO_UID, manifestDigest);
6877        installPackageWithVerificationAndEncryption(packageURI, observer, flags,
6878                installerPackageName, verificationParams, encryptionParams);
6879    }
6880
6881    public void installPackageWithVerificationAndEncryption(Uri packageURI,
6882            IPackageInstallObserver observer, int flags, String installerPackageName,
6883            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
6884        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
6885                null);
6886
6887        final int uid = Binder.getCallingUid();
6888        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
6889            try {
6890                observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
6891            } catch (RemoteException re) {
6892            }
6893            return;
6894        }
6895
6896        UserHandle user;
6897        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
6898            user = UserHandle.ALL;
6899        } else {
6900            user = new UserHandle(UserHandle.getUserId(uid));
6901        }
6902
6903        final int filteredFlags;
6904
6905        if (uid == Process.SHELL_UID || uid == 0) {
6906            if (DEBUG_INSTALL) {
6907                Slog.v(TAG, "Install from ADB");
6908            }
6909            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
6910        } else {
6911            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
6912        }
6913
6914        verificationParams.setInstallerUid(uid);
6915
6916        final Message msg = mHandler.obtainMessage(INIT_COPY);
6917        msg.obj = new InstallParams(packageURI, observer, filteredFlags, installerPackageName,
6918                verificationParams, encryptionParams, user);
6919        mHandler.sendMessage(msg);
6920    }
6921
6922    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
6923        Bundle extras = new Bundle(1);
6924        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
6925
6926        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
6927                packageName, extras, null, null, new int[] {userId});
6928        try {
6929            IActivityManager am = ActivityManagerNative.getDefault();
6930            final boolean isSystem =
6931                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
6932            if (isSystem && am.isUserRunning(userId, false)) {
6933                // The just-installed/enabled app is bundled on the system, so presumed
6934                // to be able to run automatically without needing an explicit launch.
6935                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
6936                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
6937                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
6938                        .setPackage(packageName);
6939                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
6940                        android.app.AppOpsManager.OP_NONE, false, false, userId);
6941            }
6942        } catch (RemoteException e) {
6943            // shouldn't happen
6944            Slog.w(TAG, "Unable to bootstrap installed package", e);
6945        }
6946    }
6947
6948    @Override
6949    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
6950            int userId) {
6951        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6952        PackageSetting pkgSetting;
6953        final int uid = Binder.getCallingUid();
6954        if (UserHandle.getUserId(uid) != userId) {
6955            mContext.enforceCallingOrSelfPermission(
6956                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6957                    "setApplicationBlockedSetting for user " + userId);
6958        }
6959
6960        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
6961            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
6962            return false;
6963        }
6964
6965        long callingId = Binder.clearCallingIdentity();
6966        try {
6967            boolean sendAdded = false;
6968            boolean sendRemoved = false;
6969            // writer
6970            synchronized (mPackages) {
6971                pkgSetting = mSettings.mPackages.get(packageName);
6972                if (pkgSetting == null) {
6973                    return false;
6974                }
6975                if (pkgSetting.getBlocked(userId) != blocked) {
6976                    pkgSetting.setBlocked(blocked, userId);
6977                    mSettings.writePackageRestrictionsLPr(userId);
6978                    if (blocked) {
6979                        sendRemoved = true;
6980                    } else {
6981                        sendAdded = true;
6982                    }
6983                }
6984            }
6985            if (sendAdded) {
6986                sendPackageAddedForUser(packageName, pkgSetting, userId);
6987                return true;
6988            }
6989            if (sendRemoved) {
6990                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
6991                        "blocking pkg");
6992                sendPackageBlockedForUser(packageName, pkgSetting, userId);
6993            }
6994        } finally {
6995            Binder.restoreCallingIdentity(callingId);
6996        }
6997        return false;
6998    }
6999
7000    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7001            int userId) {
7002        final PackageRemovedInfo info = new PackageRemovedInfo();
7003        info.removedPackage = packageName;
7004        info.removedUsers = new int[] {userId};
7005        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7006        info.sendBroadcast(false, false, false);
7007    }
7008
7009    /**
7010     * Returns true if application is not found or there was an error. Otherwise it returns
7011     * the blocked state of the package for the given user.
7012     */
7013    @Override
7014    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7015        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7016        PackageSetting pkgSetting;
7017        final int uid = Binder.getCallingUid();
7018        if (UserHandle.getUserId(uid) != userId) {
7019            mContext.enforceCallingPermission(
7020                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7021                    "getApplicationBlocked for user " + userId);
7022        }
7023        long callingId = Binder.clearCallingIdentity();
7024        try {
7025            // writer
7026            synchronized (mPackages) {
7027                pkgSetting = mSettings.mPackages.get(packageName);
7028                if (pkgSetting == null) {
7029                    return true;
7030                }
7031                return pkgSetting.getBlocked(userId);
7032            }
7033        } finally {
7034            Binder.restoreCallingIdentity(callingId);
7035        }
7036    }
7037
7038    /**
7039     * @hide
7040     */
7041    @Override
7042    public int installExistingPackageAsUser(String packageName, int userId) {
7043        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7044                null);
7045        PackageSetting pkgSetting;
7046        final int uid = Binder.getCallingUid();
7047        if (UserHandle.getUserId(uid) != userId) {
7048            mContext.enforceCallingPermission(
7049                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7050                    "installExistingPackage for user " + userId);
7051        }
7052        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7053            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7054        }
7055
7056        long callingId = Binder.clearCallingIdentity();
7057        try {
7058            boolean sendAdded = false;
7059            Bundle extras = new Bundle(1);
7060
7061            // writer
7062            synchronized (mPackages) {
7063                pkgSetting = mSettings.mPackages.get(packageName);
7064                if (pkgSetting == null) {
7065                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7066                }
7067                if (!pkgSetting.getInstalled(userId)) {
7068                    pkgSetting.setInstalled(true, userId);
7069                    pkgSetting.setBlocked(false, userId);
7070                    mSettings.writePackageRestrictionsLPr(userId);
7071                    sendAdded = true;
7072                }
7073            }
7074
7075            if (sendAdded) {
7076                sendPackageAddedForUser(packageName, pkgSetting, userId);
7077            }
7078        } finally {
7079            Binder.restoreCallingIdentity(callingId);
7080        }
7081
7082        return PackageManager.INSTALL_SUCCEEDED;
7083    }
7084
7085    private boolean isUserRestricted(int userId, String restrictionKey) {
7086        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7087        if (restrictions.getBoolean(restrictionKey, false)) {
7088            Log.w(TAG, "User is restricted: " + restrictionKey);
7089            return true;
7090        }
7091        return false;
7092    }
7093
7094    @Override
7095    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7096        mContext.enforceCallingOrSelfPermission(
7097                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7098                "Only package verification agents can verify applications");
7099
7100        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7101        final PackageVerificationResponse response = new PackageVerificationResponse(
7102                verificationCode, Binder.getCallingUid());
7103        msg.arg1 = id;
7104        msg.obj = response;
7105        mHandler.sendMessage(msg);
7106    }
7107
7108    @Override
7109    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7110            long millisecondsToDelay) {
7111        mContext.enforceCallingOrSelfPermission(
7112                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7113                "Only package verification agents can extend verification timeouts");
7114
7115        final PackageVerificationState state = mPendingVerification.get(id);
7116        final PackageVerificationResponse response = new PackageVerificationResponse(
7117                verificationCodeAtTimeout, Binder.getCallingUid());
7118
7119        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7120            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7121        }
7122        if (millisecondsToDelay < 0) {
7123            millisecondsToDelay = 0;
7124        }
7125        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7126                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7127            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7128        }
7129
7130        if ((state != null) && !state.timeoutExtended()) {
7131            state.extendTimeout();
7132
7133            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7134            msg.arg1 = id;
7135            msg.obj = response;
7136            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7137        }
7138    }
7139
7140    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7141            int verificationCode, UserHandle user) {
7142        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7143        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7144        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7145        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7146        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7147
7148        mContext.sendBroadcastAsUser(intent, user,
7149                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7150    }
7151
7152    private ComponentName matchComponentForVerifier(String packageName,
7153            List<ResolveInfo> receivers) {
7154        ActivityInfo targetReceiver = null;
7155
7156        final int NR = receivers.size();
7157        for (int i = 0; i < NR; i++) {
7158            final ResolveInfo info = receivers.get(i);
7159            if (info.activityInfo == null) {
7160                continue;
7161            }
7162
7163            if (packageName.equals(info.activityInfo.packageName)) {
7164                targetReceiver = info.activityInfo;
7165                break;
7166            }
7167        }
7168
7169        if (targetReceiver == null) {
7170            return null;
7171        }
7172
7173        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7174    }
7175
7176    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7177            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7178        if (pkgInfo.verifiers.length == 0) {
7179            return null;
7180        }
7181
7182        final int N = pkgInfo.verifiers.length;
7183        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7184        for (int i = 0; i < N; i++) {
7185            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7186
7187            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7188                    receivers);
7189            if (comp == null) {
7190                continue;
7191            }
7192
7193            final int verifierUid = getUidForVerifier(verifierInfo);
7194            if (verifierUid == -1) {
7195                continue;
7196            }
7197
7198            if (DEBUG_VERIFY) {
7199                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
7200                        + " with the correct signature");
7201            }
7202            sufficientVerifiers.add(comp);
7203            verificationState.addSufficientVerifier(verifierUid);
7204        }
7205
7206        return sufficientVerifiers;
7207    }
7208
7209    private int getUidForVerifier(VerifierInfo verifierInfo) {
7210        synchronized (mPackages) {
7211            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
7212            if (pkg == null) {
7213                return -1;
7214            } else if (pkg.mSignatures.length != 1) {
7215                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7216                        + " has more than one signature; ignoring");
7217                return -1;
7218            }
7219
7220            /*
7221             * If the public key of the package's signature does not match
7222             * our expected public key, then this is a different package and
7223             * we should skip.
7224             */
7225
7226            final byte[] expectedPublicKey;
7227            try {
7228                final Signature verifierSig = pkg.mSignatures[0];
7229                final PublicKey publicKey = verifierSig.getPublicKey();
7230                expectedPublicKey = publicKey.getEncoded();
7231            } catch (CertificateException e) {
7232                return -1;
7233            }
7234
7235            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
7236
7237            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
7238                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7239                        + " does not have the expected public key; ignoring");
7240                return -1;
7241            }
7242
7243            return pkg.applicationInfo.uid;
7244        }
7245    }
7246
7247    public void finishPackageInstall(int token) {
7248        enforceSystemOrRoot("Only the system is allowed to finish installs");
7249
7250        if (DEBUG_INSTALL) {
7251            Slog.v(TAG, "BM finishing package install for " + token);
7252        }
7253
7254        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7255        mHandler.sendMessage(msg);
7256    }
7257
7258    /**
7259     * Get the verification agent timeout.
7260     *
7261     * @return verification timeout in milliseconds
7262     */
7263    private long getVerificationTimeout() {
7264        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
7265                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
7266                DEFAULT_VERIFICATION_TIMEOUT);
7267    }
7268
7269    /**
7270     * Get the default verification agent response code.
7271     *
7272     * @return default verification response code
7273     */
7274    private int getDefaultVerificationResponse() {
7275        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7276                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
7277                DEFAULT_VERIFICATION_RESPONSE);
7278    }
7279
7280    /**
7281     * Check whether or not package verification has been enabled.
7282     *
7283     * @return true if verification should be performed
7284     */
7285    private boolean isVerificationEnabled(int flags) {
7286        if (!DEFAULT_VERIFY_ENABLE) {
7287            return false;
7288        }
7289
7290        // Check if installing from ADB
7291        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
7292            // Do not run verification in a test harness environment
7293            if (ActivityManager.isRunningInTestHarness()) {
7294                return false;
7295            }
7296            // Check if the developer does not want package verification for ADB installs
7297            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7298                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
7299                return false;
7300            }
7301        }
7302
7303        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7304                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
7305    }
7306
7307    /**
7308     * Get the "allow unknown sources" setting.
7309     *
7310     * @return the current "allow unknown sources" setting
7311     */
7312    private int getUnknownSourcesSettings() {
7313        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7314                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
7315                -1);
7316    }
7317
7318    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
7319        final int uid = Binder.getCallingUid();
7320        // writer
7321        synchronized (mPackages) {
7322            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
7323            if (targetPackageSetting == null) {
7324                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
7325            }
7326
7327            PackageSetting installerPackageSetting;
7328            if (installerPackageName != null) {
7329                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
7330                if (installerPackageSetting == null) {
7331                    throw new IllegalArgumentException("Unknown installer package: "
7332                            + installerPackageName);
7333                }
7334            } else {
7335                installerPackageSetting = null;
7336            }
7337
7338            Signature[] callerSignature;
7339            Object obj = mSettings.getUserIdLPr(uid);
7340            if (obj != null) {
7341                if (obj instanceof SharedUserSetting) {
7342                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
7343                } else if (obj instanceof PackageSetting) {
7344                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
7345                } else {
7346                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
7347                }
7348            } else {
7349                throw new SecurityException("Unknown calling uid " + uid);
7350            }
7351
7352            // Verify: can't set installerPackageName to a package that is
7353            // not signed with the same cert as the caller.
7354            if (installerPackageSetting != null) {
7355                if (compareSignatures(callerSignature,
7356                        installerPackageSetting.signatures.mSignatures)
7357                        != PackageManager.SIGNATURE_MATCH) {
7358                    throw new SecurityException(
7359                            "Caller does not have same cert as new installer package "
7360                            + installerPackageName);
7361                }
7362            }
7363
7364            // Verify: if target already has an installer package, it must
7365            // be signed with the same cert as the caller.
7366            if (targetPackageSetting.installerPackageName != null) {
7367                PackageSetting setting = mSettings.mPackages.get(
7368                        targetPackageSetting.installerPackageName);
7369                // If the currently set package isn't valid, then it's always
7370                // okay to change it.
7371                if (setting != null) {
7372                    if (compareSignatures(callerSignature,
7373                            setting.signatures.mSignatures)
7374                            != PackageManager.SIGNATURE_MATCH) {
7375                        throw new SecurityException(
7376                                "Caller does not have same cert as old installer package "
7377                                + targetPackageSetting.installerPackageName);
7378                    }
7379                }
7380            }
7381
7382            // Okay!
7383            targetPackageSetting.installerPackageName = installerPackageName;
7384            scheduleWriteSettingsLocked();
7385        }
7386    }
7387
7388    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
7389        // Queue up an async operation since the package installation may take a little while.
7390        mHandler.post(new Runnable() {
7391            public void run() {
7392                mHandler.removeCallbacks(this);
7393                 // Result object to be returned
7394                PackageInstalledInfo res = new PackageInstalledInfo();
7395                res.returnCode = currentStatus;
7396                res.uid = -1;
7397                res.pkg = null;
7398                res.removedInfo = new PackageRemovedInfo();
7399                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
7400                    args.doPreInstall(res.returnCode);
7401                    synchronized (mInstallLock) {
7402                        installPackageLI(args, true, res);
7403                    }
7404                    args.doPostInstall(res.returnCode, res.uid);
7405                }
7406
7407                // A restore should be performed at this point if (a) the install
7408                // succeeded, (b) the operation is not an update, and (c) the new
7409                // package has a backupAgent defined.
7410                final boolean update = res.removedInfo.removedPackage != null;
7411                boolean doRestore = (!update
7412                        && res.pkg != null
7413                        && res.pkg.applicationInfo.backupAgentName != null);
7414
7415                // Set up the post-install work request bookkeeping.  This will be used
7416                // and cleaned up by the post-install event handling regardless of whether
7417                // there's a restore pass performed.  Token values are >= 1.
7418                int token;
7419                if (mNextInstallToken < 0) mNextInstallToken = 1;
7420                token = mNextInstallToken++;
7421
7422                PostInstallData data = new PostInstallData(args, res);
7423                mRunningInstalls.put(token, data);
7424                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
7425
7426                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
7427                    // Pass responsibility to the Backup Manager.  It will perform a
7428                    // restore if appropriate, then pass responsibility back to the
7429                    // Package Manager to run the post-install observer callbacks
7430                    // and broadcasts.
7431                    IBackupManager bm = IBackupManager.Stub.asInterface(
7432                            ServiceManager.getService(Context.BACKUP_SERVICE));
7433                    if (bm != null) {
7434                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
7435                                + " to BM for possible restore");
7436                        try {
7437                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
7438                        } catch (RemoteException e) {
7439                            // can't happen; the backup manager is local
7440                        } catch (Exception e) {
7441                            Slog.e(TAG, "Exception trying to enqueue restore", e);
7442                            doRestore = false;
7443                        }
7444                    } else {
7445                        Slog.e(TAG, "Backup Manager not found!");
7446                        doRestore = false;
7447                    }
7448                }
7449
7450                if (!doRestore) {
7451                    // No restore possible, or the Backup Manager was mysteriously not
7452                    // available -- just fire the post-install work request directly.
7453                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
7454                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7455                    mHandler.sendMessage(msg);
7456                }
7457            }
7458        });
7459    }
7460
7461    private abstract class HandlerParams {
7462        private static final int MAX_RETRIES = 4;
7463
7464        /**
7465         * Number of times startCopy() has been attempted and had a non-fatal
7466         * error.
7467         */
7468        private int mRetries = 0;
7469
7470        /** User handle for the user requesting the information or installation. */
7471        private final UserHandle mUser;
7472
7473        HandlerParams(UserHandle user) {
7474            mUser = user;
7475        }
7476
7477        UserHandle getUser() {
7478            return mUser;
7479        }
7480
7481        final boolean startCopy() {
7482            boolean res;
7483            try {
7484                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
7485
7486                if (++mRetries > MAX_RETRIES) {
7487                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
7488                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
7489                    handleServiceError();
7490                    return false;
7491                } else {
7492                    handleStartCopy();
7493                    res = true;
7494                }
7495            } catch (RemoteException e) {
7496                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
7497                mHandler.sendEmptyMessage(MCS_RECONNECT);
7498                res = false;
7499            }
7500            handleReturnCode();
7501            return res;
7502        }
7503
7504        final void serviceError() {
7505            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
7506            handleServiceError();
7507            handleReturnCode();
7508        }
7509
7510        abstract void handleStartCopy() throws RemoteException;
7511        abstract void handleServiceError();
7512        abstract void handleReturnCode();
7513    }
7514
7515    class MeasureParams extends HandlerParams {
7516        private final PackageStats mStats;
7517        private boolean mSuccess;
7518
7519        private final IPackageStatsObserver mObserver;
7520
7521        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
7522            super(new UserHandle(stats.userHandle));
7523            mObserver = observer;
7524            mStats = stats;
7525        }
7526
7527        @Override
7528        public String toString() {
7529            return "MeasureParams{"
7530                + Integer.toHexString(System.identityHashCode(this))
7531                + " " + mStats.packageName + "}";
7532        }
7533
7534        @Override
7535        void handleStartCopy() throws RemoteException {
7536            synchronized (mInstallLock) {
7537                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
7538            }
7539
7540            final boolean mounted;
7541            if (Environment.isExternalStorageEmulated()) {
7542                mounted = true;
7543            } else {
7544                final String status = Environment.getExternalStorageState();
7545                mounted = (Environment.MEDIA_MOUNTED.equals(status)
7546                        || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
7547            }
7548
7549            if (mounted) {
7550                final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
7551
7552                mStats.externalCacheSize = calculateDirectorySize(mContainerService,
7553                        userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
7554
7555                mStats.externalDataSize = calculateDirectorySize(mContainerService,
7556                        userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
7557
7558                // Always subtract cache size, since it's a subdirectory
7559                mStats.externalDataSize -= mStats.externalCacheSize;
7560
7561                mStats.externalMediaSize = calculateDirectorySize(mContainerService,
7562                        userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
7563
7564                mStats.externalObbSize = calculateDirectorySize(mContainerService,
7565                        userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
7566            }
7567        }
7568
7569        @Override
7570        void handleReturnCode() {
7571            if (mObserver != null) {
7572                try {
7573                    mObserver.onGetStatsCompleted(mStats, mSuccess);
7574                } catch (RemoteException e) {
7575                    Slog.i(TAG, "Observer no longer exists.");
7576                }
7577            }
7578        }
7579
7580        @Override
7581        void handleServiceError() {
7582            Slog.e(TAG, "Could not measure application " + mStats.packageName
7583                            + " external storage");
7584        }
7585    }
7586
7587    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
7588            throws RemoteException {
7589        long result = 0;
7590        for (File path : paths) {
7591            result += mcs.calculateDirectorySize(path.getAbsolutePath());
7592        }
7593        return result;
7594    }
7595
7596    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
7597        for (File path : paths) {
7598            try {
7599                mcs.clearDirectory(path.getAbsolutePath());
7600            } catch (RemoteException e) {
7601            }
7602        }
7603    }
7604
7605    class InstallParams extends HandlerParams {
7606        final IPackageInstallObserver observer;
7607        int flags;
7608
7609        private final Uri mPackageURI;
7610        final String installerPackageName;
7611        final VerificationParams verificationParams;
7612        private InstallArgs mArgs;
7613        private int mRet;
7614        private File mTempPackage;
7615        final ContainerEncryptionParams encryptionParams;
7616
7617        InstallParams(Uri packageURI,
7618                IPackageInstallObserver observer, int flags,
7619                String installerPackageName, VerificationParams verificationParams,
7620                ContainerEncryptionParams encryptionParams, UserHandle user) {
7621            super(user);
7622            this.mPackageURI = packageURI;
7623            this.flags = flags;
7624            this.observer = observer;
7625            this.installerPackageName = installerPackageName;
7626            this.verificationParams = verificationParams;
7627            this.encryptionParams = encryptionParams;
7628        }
7629
7630        @Override
7631        public String toString() {
7632            return "InstallParams{"
7633                + Integer.toHexString(System.identityHashCode(this))
7634                + " " + mPackageURI + "}";
7635        }
7636
7637        public ManifestDigest getManifestDigest() {
7638            if (verificationParams == null) {
7639                return null;
7640            }
7641            return verificationParams.getManifestDigest();
7642        }
7643
7644        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
7645            String packageName = pkgLite.packageName;
7646            int installLocation = pkgLite.installLocation;
7647            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
7648            // reader
7649            synchronized (mPackages) {
7650                PackageParser.Package pkg = mPackages.get(packageName);
7651                if (pkg != null) {
7652                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
7653                        // Check for downgrading.
7654                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
7655                            if (pkgLite.versionCode < pkg.mVersionCode) {
7656                                Slog.w(TAG, "Can't install update of " + packageName
7657                                        + " update version " + pkgLite.versionCode
7658                                        + " is older than installed version "
7659                                        + pkg.mVersionCode);
7660                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
7661                            }
7662                        }
7663                        // Check for updated system application.
7664                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7665                            if (onSd) {
7666                                Slog.w(TAG, "Cannot install update to system app on sdcard");
7667                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
7668                            }
7669                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
7670                        } else {
7671                            if (onSd) {
7672                                // Install flag overrides everything.
7673                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
7674                            }
7675                            // If current upgrade specifies particular preference
7676                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
7677                                // Application explicitly specified internal.
7678                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
7679                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
7680                                // App explictly prefers external. Let policy decide
7681                            } else {
7682                                // Prefer previous location
7683                                if (isExternal(pkg)) {
7684                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
7685                                }
7686                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
7687                            }
7688                        }
7689                    } else {
7690                        // Invalid install. Return error code
7691                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
7692                    }
7693                }
7694            }
7695            // All the special cases have been taken care of.
7696            // Return result based on recommended install location.
7697            if (onSd) {
7698                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
7699            }
7700            return pkgLite.recommendedInstallLocation;
7701        }
7702
7703        private long getMemoryLowThreshold() {
7704            final DeviceStorageMonitorInternal
7705                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
7706            if (dsm == null) {
7707                return 0L;
7708            }
7709            return dsm.getMemoryLowThreshold();
7710        }
7711
7712        /*
7713         * Invoke remote method to get package information and install
7714         * location values. Override install location based on default
7715         * policy if needed and then create install arguments based
7716         * on the install location.
7717         */
7718        public void handleStartCopy() throws RemoteException {
7719            int ret = PackageManager.INSTALL_SUCCEEDED;
7720            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
7721            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
7722            PackageInfoLite pkgLite = null;
7723
7724            if (onInt && onSd) {
7725                // Check if both bits are set.
7726                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
7727                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
7728            } else {
7729                final long lowThreshold = getMemoryLowThreshold();
7730                if (lowThreshold == 0L) {
7731                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
7732                }
7733
7734                try {
7735                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
7736                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
7737
7738                    final File packageFile;
7739                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
7740                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
7741                        if (mTempPackage != null) {
7742                            ParcelFileDescriptor out;
7743                            try {
7744                                out = ParcelFileDescriptor.open(mTempPackage,
7745                                        ParcelFileDescriptor.MODE_READ_WRITE);
7746                            } catch (FileNotFoundException e) {
7747                                out = null;
7748                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
7749                            }
7750
7751                            // Make a temporary file for decryption.
7752                            ret = mContainerService
7753                                    .copyResource(mPackageURI, encryptionParams, out);
7754                            IoUtils.closeQuietly(out);
7755
7756                            packageFile = mTempPackage;
7757
7758                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
7759                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
7760                                            | FileUtils.S_IROTH,
7761                                    -1, -1);
7762                        } else {
7763                            packageFile = null;
7764                        }
7765                    } else {
7766                        packageFile = new File(mPackageURI.getPath());
7767                    }
7768
7769                    if (packageFile != null) {
7770                        // Remote call to find out default install location
7771                        final String packageFilePath = packageFile.getAbsolutePath();
7772                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
7773                                lowThreshold);
7774
7775                        /*
7776                         * If we have too little free space, try to free cache
7777                         * before giving up.
7778                         */
7779                        if (pkgLite.recommendedInstallLocation
7780                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
7781                            final long size = mContainerService.calculateInstalledSize(
7782                                    packageFilePath, isForwardLocked());
7783                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
7784                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
7785                                        flags, lowThreshold);
7786                            }
7787                            /*
7788                             * The cache free must have deleted the file we
7789                             * downloaded to install.
7790                             *
7791                             * TODO: fix the "freeCache" call to not delete
7792                             *       the file we care about.
7793                             */
7794                            if (pkgLite.recommendedInstallLocation
7795                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
7796                                pkgLite.recommendedInstallLocation
7797                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
7798                            }
7799                        }
7800                    }
7801                } finally {
7802                    mContext.revokeUriPermission(mPackageURI,
7803                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
7804                }
7805            }
7806
7807            if (ret == PackageManager.INSTALL_SUCCEEDED) {
7808                int loc = pkgLite.recommendedInstallLocation;
7809                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
7810                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
7811                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
7812                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
7813                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
7814                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7815                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
7816                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
7817                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
7818                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
7819                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
7820                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
7821                } else {
7822                    // Override with defaults if needed.
7823                    loc = installLocationPolicy(pkgLite, flags);
7824                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
7825                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
7826                    } else if (!onSd && !onInt) {
7827                        // Override install location with flags
7828                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
7829                            // Set the flag to install on external media.
7830                            flags |= PackageManager.INSTALL_EXTERNAL;
7831                            flags &= ~PackageManager.INSTALL_INTERNAL;
7832                        } else {
7833                            // Make sure the flag for installing on external
7834                            // media is unset
7835                            flags |= PackageManager.INSTALL_INTERNAL;
7836                            flags &= ~PackageManager.INSTALL_EXTERNAL;
7837                        }
7838                    }
7839                }
7840            }
7841
7842            final InstallArgs args = createInstallArgs(this);
7843            mArgs = args;
7844
7845            if (ret == PackageManager.INSTALL_SUCCEEDED) {
7846                 /*
7847                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
7848                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
7849                 */
7850                int userIdentifier = getUser().getIdentifier();
7851                if (userIdentifier == UserHandle.USER_ALL
7852                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
7853                    userIdentifier = UserHandle.USER_OWNER;
7854                }
7855
7856                /*
7857                 * Determine if we have any installed package verifiers. If we
7858                 * do, then we'll defer to them to verify the packages.
7859                 */
7860                final int requiredUid = mRequiredVerifierPackage == null ? -1
7861                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
7862                if (requiredUid != -1 && isVerificationEnabled(flags)) {
7863                    final Intent verification = new Intent(
7864                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
7865                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
7866                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7867
7868                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
7869                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
7870                            0 /* TODO: Which userId? */);
7871
7872                    if (DEBUG_VERIFY) {
7873                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
7874                                + verification.toString() + " with " + pkgLite.verifiers.length
7875                                + " optional verifiers");
7876                    }
7877
7878                    final int verificationId = mPendingVerificationToken++;
7879
7880                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7881
7882                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
7883                            installerPackageName);
7884
7885                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
7886
7887                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
7888                            pkgLite.packageName);
7889
7890                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
7891                            pkgLite.versionCode);
7892
7893                    if (verificationParams != null) {
7894                        if (verificationParams.getVerificationURI() != null) {
7895                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
7896                                 verificationParams.getVerificationURI());
7897                        }
7898                        if (verificationParams.getOriginatingURI() != null) {
7899                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
7900                                  verificationParams.getOriginatingURI());
7901                        }
7902                        if (verificationParams.getReferrer() != null) {
7903                            verification.putExtra(Intent.EXTRA_REFERRER,
7904                                  verificationParams.getReferrer());
7905                        }
7906                        if (verificationParams.getOriginatingUid() >= 0) {
7907                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
7908                                  verificationParams.getOriginatingUid());
7909                        }
7910                        if (verificationParams.getInstallerUid() >= 0) {
7911                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
7912                                  verificationParams.getInstallerUid());
7913                        }
7914                    }
7915
7916                    final PackageVerificationState verificationState = new PackageVerificationState(
7917                            requiredUid, args);
7918
7919                    mPendingVerification.append(verificationId, verificationState);
7920
7921                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
7922                            receivers, verificationState);
7923
7924                    /*
7925                     * If any sufficient verifiers were listed in the package
7926                     * manifest, attempt to ask them.
7927                     */
7928                    if (sufficientVerifiers != null) {
7929                        final int N = sufficientVerifiers.size();
7930                        if (N == 0) {
7931                            Slog.i(TAG, "Additional verifiers required, but none installed.");
7932                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
7933                        } else {
7934                            for (int i = 0; i < N; i++) {
7935                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
7936
7937                                final Intent sufficientIntent = new Intent(verification);
7938                                sufficientIntent.setComponent(verifierComponent);
7939
7940                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
7941                            }
7942                        }
7943                    }
7944
7945                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
7946                            mRequiredVerifierPackage, receivers);
7947                    if (ret == PackageManager.INSTALL_SUCCEEDED
7948                            && mRequiredVerifierPackage != null) {
7949                        /*
7950                         * Send the intent to the required verification agent,
7951                         * but only start the verification timeout after the
7952                         * target BroadcastReceivers have run.
7953                         */
7954                        verification.setComponent(requiredVerifierComponent);
7955                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
7956                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7957                                new BroadcastReceiver() {
7958                                    @Override
7959                                    public void onReceive(Context context, Intent intent) {
7960                                        final Message msg = mHandler
7961                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
7962                                        msg.arg1 = verificationId;
7963                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
7964                                    }
7965                                }, null, 0, null, null);
7966
7967                        /*
7968                         * We don't want the copy to proceed until verification
7969                         * succeeds, so null out this field.
7970                         */
7971                        mArgs = null;
7972                    }
7973                } else {
7974                    /*
7975                     * No package verification is enabled, so immediately start
7976                     * the remote call to initiate copy using temporary file.
7977                     */
7978                    ret = args.copyApk(mContainerService, true);
7979                }
7980            }
7981
7982            mRet = ret;
7983        }
7984
7985        @Override
7986        void handleReturnCode() {
7987            // If mArgs is null, then MCS couldn't be reached. When it
7988            // reconnects, it will try again to install. At that point, this
7989            // will succeed.
7990            if (mArgs != null) {
7991                processPendingInstall(mArgs, mRet);
7992
7993                if (mTempPackage != null) {
7994                    if (!mTempPackage.delete()) {
7995                        Slog.w(TAG, "Couldn't delete temporary file: " +
7996                                mTempPackage.getAbsolutePath());
7997                    }
7998                }
7999            }
8000        }
8001
8002        @Override
8003        void handleServiceError() {
8004            mArgs = createInstallArgs(this);
8005            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8006        }
8007
8008        public boolean isForwardLocked() {
8009            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8010        }
8011
8012        public Uri getPackageUri() {
8013            if (mTempPackage != null) {
8014                return Uri.fromFile(mTempPackage);
8015            } else {
8016                return mPackageURI;
8017            }
8018        }
8019    }
8020
8021    /*
8022     * Utility class used in movePackage api.
8023     * srcArgs and targetArgs are not set for invalid flags and make
8024     * sure to do null checks when invoking methods on them.
8025     * We probably want to return ErrorPrams for both failed installs
8026     * and moves.
8027     */
8028    class MoveParams extends HandlerParams {
8029        final IPackageMoveObserver observer;
8030        final int flags;
8031        final String packageName;
8032        final InstallArgs srcArgs;
8033        final InstallArgs targetArgs;
8034        int uid;
8035        int mRet;
8036
8037        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8038                String packageName, String dataDir, String instructionSet,
8039                int uid, UserHandle user) {
8040            super(user);
8041            this.srcArgs = srcArgs;
8042            this.observer = observer;
8043            this.flags = flags;
8044            this.packageName = packageName;
8045            this.uid = uid;
8046            if (srcArgs != null) {
8047                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
8048                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet);
8049            } else {
8050                targetArgs = null;
8051            }
8052        }
8053
8054        @Override
8055        public String toString() {
8056            return "MoveParams{"
8057                + Integer.toHexString(System.identityHashCode(this))
8058                + " " + packageName + "}";
8059        }
8060
8061        public void handleStartCopy() throws RemoteException {
8062            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8063            // Check for storage space on target medium
8064            if (!targetArgs.checkFreeStorage(mContainerService)) {
8065                Log.w(TAG, "Insufficient storage to install");
8066                return;
8067            }
8068
8069            mRet = srcArgs.doPreCopy();
8070            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8071                return;
8072            }
8073
8074            mRet = targetArgs.copyApk(mContainerService, false);
8075            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8076                srcArgs.doPostCopy(uid);
8077                return;
8078            }
8079
8080            mRet = srcArgs.doPostCopy(uid);
8081            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8082                return;
8083            }
8084
8085            mRet = targetArgs.doPreInstall(mRet);
8086            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8087                return;
8088            }
8089
8090            if (DEBUG_SD_INSTALL) {
8091                StringBuilder builder = new StringBuilder();
8092                if (srcArgs != null) {
8093                    builder.append("src: ");
8094                    builder.append(srcArgs.getCodePath());
8095                }
8096                if (targetArgs != null) {
8097                    builder.append(" target : ");
8098                    builder.append(targetArgs.getCodePath());
8099                }
8100                Log.i(TAG, builder.toString());
8101            }
8102        }
8103
8104        @Override
8105        void handleReturnCode() {
8106            targetArgs.doPostInstall(mRet, uid);
8107            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8108            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8109                currentStatus = PackageManager.MOVE_SUCCEEDED;
8110            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8111                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8112            }
8113            processPendingMove(this, currentStatus);
8114        }
8115
8116        @Override
8117        void handleServiceError() {
8118            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8119        }
8120    }
8121
8122    /**
8123     * Used during creation of InstallArgs
8124     *
8125     * @param flags package installation flags
8126     * @return true if should be installed on external storage
8127     */
8128    private static boolean installOnSd(int flags) {
8129        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8130            return false;
8131        }
8132        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8133            return true;
8134        }
8135        return false;
8136    }
8137
8138    /**
8139     * Used during creation of InstallArgs
8140     *
8141     * @param flags package installation flags
8142     * @return true if should be installed as forward locked
8143     */
8144    private static boolean installForwardLocked(int flags) {
8145        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8146    }
8147
8148    private InstallArgs createInstallArgs(InstallParams params) {
8149        if (installOnSd(params.flags) || params.isForwardLocked()) {
8150            return new AsecInstallArgs(params);
8151        } else {
8152            return new FileInstallArgs(params);
8153        }
8154    }
8155
8156    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
8157            String nativeLibraryPath, String instructionSet) {
8158        final boolean isInAsec;
8159        if (installOnSd(flags)) {
8160            /* Apps on SD card are always in ASEC containers. */
8161            isInAsec = true;
8162        } else if (installForwardLocked(flags)
8163                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8164            /*
8165             * Forward-locked apps are only in ASEC containers if they're the
8166             * new style
8167             */
8168            isInAsec = true;
8169        } else {
8170            isInAsec = false;
8171        }
8172
8173        if (isInAsec) {
8174            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8175                    instructionSet, installOnSd(flags), installForwardLocked(flags));
8176        } else {
8177            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8178                    instructionSet);
8179        }
8180    }
8181
8182    // Used by package mover
8183    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir,
8184            String instructionSet) {
8185        if (installOnSd(flags) || installForwardLocked(flags)) {
8186            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
8187                    + AsecInstallArgs.RES_FILE_NAME);
8188            return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags),
8189                    installForwardLocked(flags));
8190        } else {
8191            return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet);
8192        }
8193    }
8194
8195    static abstract class InstallArgs {
8196        final IPackageInstallObserver observer;
8197        // Always refers to PackageManager flags only
8198        final int flags;
8199        final Uri packageURI;
8200        final String installerPackageName;
8201        final ManifestDigest manifestDigest;
8202        final UserHandle user;
8203        final String instructionSet;
8204
8205        InstallArgs(Uri packageURI, IPackageInstallObserver observer, int flags,
8206                String installerPackageName, ManifestDigest manifestDigest,
8207                UserHandle user, String instructionSet) {
8208            this.packageURI = packageURI;
8209            this.flags = flags;
8210            this.observer = observer;
8211            this.installerPackageName = installerPackageName;
8212            this.manifestDigest = manifestDigest;
8213            this.user = user;
8214            this.instructionSet = instructionSet;
8215        }
8216
8217        abstract void createCopyFile();
8218        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8219        abstract int doPreInstall(int status);
8220        abstract boolean doRename(int status, String pkgName, String oldCodePath);
8221
8222        abstract int doPostInstall(int status, int uid);
8223        abstract String getCodePath();
8224        abstract String getResourcePath();
8225        abstract String getNativeLibraryPath();
8226        // Need installer lock especially for dex file removal.
8227        abstract void cleanUpResourcesLI();
8228        abstract boolean doPostDeleteLI(boolean delete);
8229        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
8230
8231        /**
8232         * Called before the source arguments are copied. This is used mostly
8233         * for MoveParams when it needs to read the source file to put it in the
8234         * destination.
8235         */
8236        int doPreCopy() {
8237            return PackageManager.INSTALL_SUCCEEDED;
8238        }
8239
8240        /**
8241         * Called after the source arguments are copied. This is used mostly for
8242         * MoveParams when it needs to read the source file to put it in the
8243         * destination.
8244         *
8245         * @return
8246         */
8247        int doPostCopy(int uid) {
8248            return PackageManager.INSTALL_SUCCEEDED;
8249        }
8250
8251        protected boolean isFwdLocked() {
8252            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8253        }
8254
8255        UserHandle getUser() {
8256            return user;
8257        }
8258    }
8259
8260    class FileInstallArgs extends InstallArgs {
8261        File installDir;
8262        String codeFileName;
8263        String resourceFileName;
8264        String libraryPath;
8265        boolean created = false;
8266
8267        FileInstallArgs(InstallParams params) {
8268            super(params.getPackageUri(), params.observer, params.flags,
8269                    params.installerPackageName, params.getManifestDigest(),
8270                    params.getUser(), null /* instruction set */);
8271        }
8272
8273        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
8274                String instructionSet) {
8275            super(null, null, 0, null, null, null, instructionSet);
8276            File codeFile = new File(fullCodePath);
8277            installDir = codeFile.getParentFile();
8278            codeFileName = fullCodePath;
8279            resourceFileName = fullResourcePath;
8280            libraryPath = nativeLibraryPath;
8281        }
8282
8283        FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) {
8284            super(packageURI, null, 0, null, null, null, instructionSet);
8285            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8286            String apkName = getNextCodePath(null, pkgName, ".apk");
8287            codeFileName = new File(installDir, apkName + ".apk").getPath();
8288            resourceFileName = getResourcePathFromCodePath();
8289            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
8290        }
8291
8292        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
8293            final long lowThreshold;
8294
8295            final DeviceStorageMonitorInternal
8296                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8297            if (dsm == null) {
8298                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8299                lowThreshold = 0L;
8300            } else {
8301                if (dsm.isMemoryLow()) {
8302                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
8303                    return false;
8304                }
8305
8306                lowThreshold = dsm.getMemoryLowThreshold();
8307            }
8308
8309            try {
8310                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8311                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8312                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
8313            } finally {
8314                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8315            }
8316        }
8317
8318        String getCodePath() {
8319            return codeFileName;
8320        }
8321
8322        void createCopyFile() {
8323            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8324            codeFileName = createTempPackageFile(installDir).getPath();
8325            resourceFileName = getResourcePathFromCodePath();
8326            libraryPath = getLibraryPathFromCodePath();
8327            created = true;
8328        }
8329
8330        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
8331            if (temp) {
8332                // Generate temp file name
8333                createCopyFile();
8334            }
8335            // Get a ParcelFileDescriptor to write to the output file
8336            File codeFile = new File(codeFileName);
8337            if (!created) {
8338                try {
8339                    codeFile.createNewFile();
8340                    // Set permissions
8341                    if (!setPermissions()) {
8342                        // Failed setting permissions.
8343                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8344                    }
8345                } catch (IOException e) {
8346                   Slog.w(TAG, "Failed to create file " + codeFile);
8347                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8348                }
8349            }
8350            ParcelFileDescriptor out = null;
8351            try {
8352                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
8353            } catch (FileNotFoundException e) {
8354                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
8355                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8356            }
8357            // Copy the resource now
8358            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8359            try {
8360                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8361                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8362                ret = imcs.copyResource(packageURI, null, out);
8363            } finally {
8364                IoUtils.closeQuietly(out);
8365                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8366            }
8367
8368            if (isFwdLocked()) {
8369                final File destResourceFile = new File(getResourcePath());
8370
8371                // Copy the public files
8372                try {
8373                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
8374                } catch (IOException e) {
8375                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
8376                            + " forward-locked app.");
8377                    destResourceFile.delete();
8378                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8379                }
8380            }
8381
8382            final File nativeLibraryFile = new File(getNativeLibraryPath());
8383            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
8384            if (nativeLibraryFile.exists()) {
8385                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
8386                nativeLibraryFile.delete();
8387            }
8388            try {
8389                int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile);
8390                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8391                    return copyRet;
8392                }
8393            } catch (IOException e) {
8394                Slog.e(TAG, "Copying native libraries failed", e);
8395                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8396            }
8397
8398            return ret;
8399        }
8400
8401        int doPreInstall(int status) {
8402            if (status != PackageManager.INSTALL_SUCCEEDED) {
8403                cleanUp();
8404            }
8405            return status;
8406        }
8407
8408        boolean doRename(int status, final String pkgName, String oldCodePath) {
8409            if (status != PackageManager.INSTALL_SUCCEEDED) {
8410                cleanUp();
8411                return false;
8412            } else {
8413                final File oldCodeFile = new File(getCodePath());
8414                final File oldResourceFile = new File(getResourcePath());
8415                final File oldLibraryFile = new File(getNativeLibraryPath());
8416
8417                // Rename APK file based on packageName
8418                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
8419                final File newCodeFile = new File(installDir, apkName + ".apk");
8420                if (!oldCodeFile.renameTo(newCodeFile)) {
8421                    return false;
8422                }
8423                codeFileName = newCodeFile.getPath();
8424
8425                // Rename public resource file if it's forward-locked.
8426                final File newResFile = new File(getResourcePathFromCodePath());
8427                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
8428                    return false;
8429                }
8430                resourceFileName = newResFile.getPath();
8431
8432                // Rename library path
8433                final File newLibraryFile = new File(getLibraryPathFromCodePath());
8434                if (newLibraryFile.exists()) {
8435                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
8436                    newLibraryFile.delete();
8437                }
8438                if (!oldLibraryFile.renameTo(newLibraryFile)) {
8439                    Slog.e(TAG, "Cannot rename native library directory "
8440                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
8441                    return false;
8442                }
8443                libraryPath = newLibraryFile.getPath();
8444
8445                // Attempt to set permissions
8446                if (!setPermissions()) {
8447                    return false;
8448                }
8449
8450                if (!SELinux.restorecon(newCodeFile)) {
8451                    return false;
8452                }
8453
8454                return true;
8455            }
8456        }
8457
8458        int doPostInstall(int status, int uid) {
8459            if (status != PackageManager.INSTALL_SUCCEEDED) {
8460                cleanUp();
8461            }
8462            return status;
8463        }
8464
8465        String getResourcePath() {
8466            return resourceFileName;
8467        }
8468
8469        private String getResourcePathFromCodePath() {
8470            final String codePath = getCodePath();
8471            if (isFwdLocked()) {
8472                final StringBuilder sb = new StringBuilder();
8473
8474                sb.append(mAppInstallDir.getPath());
8475                sb.append('/');
8476                sb.append(getApkName(codePath));
8477                sb.append(".zip");
8478
8479                /*
8480                 * If our APK is a temporary file, mark the resource as a
8481                 * temporary file as well so it can be cleaned up after
8482                 * catastrophic failure.
8483                 */
8484                if (codePath.endsWith(".tmp")) {
8485                    sb.append(".tmp");
8486                }
8487
8488                return sb.toString();
8489            } else {
8490                return codePath;
8491            }
8492        }
8493
8494        private String getLibraryPathFromCodePath() {
8495            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
8496        }
8497
8498        @Override
8499        String getNativeLibraryPath() {
8500            if (libraryPath == null) {
8501                libraryPath = getLibraryPathFromCodePath();
8502            }
8503            return libraryPath;
8504        }
8505
8506        private boolean cleanUp() {
8507            boolean ret = true;
8508            String sourceDir = getCodePath();
8509            String publicSourceDir = getResourcePath();
8510            if (sourceDir != null) {
8511                File sourceFile = new File(sourceDir);
8512                if (!sourceFile.exists()) {
8513                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
8514                    ret = false;
8515                }
8516                // Delete application's code and resources
8517                sourceFile.delete();
8518            }
8519            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
8520                final File publicSourceFile = new File(publicSourceDir);
8521                if (!publicSourceFile.exists()) {
8522                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
8523                }
8524                if (publicSourceFile.exists()) {
8525                    publicSourceFile.delete();
8526                }
8527            }
8528
8529            if (libraryPath != null) {
8530                File nativeLibraryFile = new File(libraryPath);
8531                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
8532                if (!nativeLibraryFile.delete()) {
8533                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
8534                }
8535            }
8536
8537            return ret;
8538        }
8539
8540        void cleanUpResourcesLI() {
8541            String sourceDir = getCodePath();
8542            if (cleanUp()) {
8543                if (instructionSet == null) {
8544                    throw new IllegalStateException("instructionSet == null");
8545                }
8546                int retCode = mInstaller.rmdex(sourceDir, instructionSet);
8547                if (retCode < 0) {
8548                    Slog.w(TAG, "Couldn't remove dex file for package: "
8549                            +  " at location "
8550                            + sourceDir + ", retcode=" + retCode);
8551                    // we don't consider this to be a failure of the core package deletion
8552                }
8553            }
8554        }
8555
8556        private boolean setPermissions() {
8557            // TODO Do this in a more elegant way later on. for now just a hack
8558            if (!isFwdLocked()) {
8559                final int filePermissions =
8560                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
8561                    |FileUtils.S_IROTH;
8562                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
8563                if (retCode != 0) {
8564                    Slog.e(TAG, "Couldn't set new package file permissions for " +
8565                            getCodePath()
8566                            + ". The return code was: " + retCode);
8567                    // TODO Define new internal error
8568                    return false;
8569                }
8570                return true;
8571            }
8572            return true;
8573        }
8574
8575        boolean doPostDeleteLI(boolean delete) {
8576            // XXX err, shouldn't we respect the delete flag?
8577            cleanUpResourcesLI();
8578            return true;
8579        }
8580    }
8581
8582    private boolean isAsecExternal(String cid) {
8583        final String asecPath = PackageHelper.getSdFilesystem(cid);
8584        return !asecPath.startsWith(mAsecInternalPath);
8585    }
8586
8587    /**
8588     * Extract the MountService "container ID" from the full code path of an
8589     * .apk.
8590     */
8591    static String cidFromCodePath(String fullCodePath) {
8592        int eidx = fullCodePath.lastIndexOf("/");
8593        String subStr1 = fullCodePath.substring(0, eidx);
8594        int sidx = subStr1.lastIndexOf("/");
8595        return subStr1.substring(sidx+1, eidx);
8596    }
8597
8598    class AsecInstallArgs extends InstallArgs {
8599        static final String RES_FILE_NAME = "pkg.apk";
8600        static final String PUBLIC_RES_FILE_NAME = "res.zip";
8601
8602        String cid;
8603        String packagePath;
8604        String resourcePath;
8605        String libraryPath;
8606
8607        AsecInstallArgs(InstallParams params) {
8608            super(params.getPackageUri(), params.observer, params.flags,
8609                    params.installerPackageName, params.getManifestDigest(),
8610                    params.getUser(), null /* instruction set */);
8611        }
8612
8613        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
8614                String instructionSet, boolean isExternal, boolean isForwardLocked) {
8615            super(null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
8616                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8617                    null, null, null, instructionSet);
8618            // Extract cid from fullCodePath
8619            int eidx = fullCodePath.lastIndexOf("/");
8620            String subStr1 = fullCodePath.substring(0, eidx);
8621            int sidx = subStr1.lastIndexOf("/");
8622            cid = subStr1.substring(sidx+1, eidx);
8623            setCachePath(subStr1);
8624        }
8625
8626        AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) {
8627            super(null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
8628                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8629                    null, null, null, instructionSet);
8630            this.cid = cid;
8631            setCachePath(PackageHelper.getSdDir(cid));
8632        }
8633
8634        AsecInstallArgs(Uri packageURI, String cid, String instructionSet,
8635                boolean isExternal, boolean isForwardLocked) {
8636            super(packageURI, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
8637                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8638                    null, null, null, instructionSet);
8639            this.cid = cid;
8640        }
8641
8642        void createCopyFile() {
8643            cid = getTempContainerId();
8644        }
8645
8646        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
8647            try {
8648                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8649                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8650                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
8651            } finally {
8652                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8653            }
8654        }
8655
8656        private final boolean isExternal() {
8657            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8658        }
8659
8660        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
8661            if (temp) {
8662                createCopyFile();
8663            } else {
8664                /*
8665                 * Pre-emptively destroy the container since it's destroyed if
8666                 * copying fails due to it existing anyway.
8667                 */
8668                PackageHelper.destroySdDir(cid);
8669            }
8670
8671            final String newCachePath;
8672            try {
8673                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8674                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8675                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
8676                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
8677            } finally {
8678                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8679            }
8680
8681            if (newCachePath != null) {
8682                setCachePath(newCachePath);
8683                return PackageManager.INSTALL_SUCCEEDED;
8684            } else {
8685                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8686            }
8687        }
8688
8689        @Override
8690        String getCodePath() {
8691            return packagePath;
8692        }
8693
8694        @Override
8695        String getResourcePath() {
8696            return resourcePath;
8697        }
8698
8699        @Override
8700        String getNativeLibraryPath() {
8701            return libraryPath;
8702        }
8703
8704        int doPreInstall(int status) {
8705            if (status != PackageManager.INSTALL_SUCCEEDED) {
8706                // Destroy container
8707                PackageHelper.destroySdDir(cid);
8708            } else {
8709                boolean mounted = PackageHelper.isContainerMounted(cid);
8710                if (!mounted) {
8711                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
8712                            Process.SYSTEM_UID);
8713                    if (newCachePath != null) {
8714                        setCachePath(newCachePath);
8715                    } else {
8716                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8717                    }
8718                }
8719            }
8720            return status;
8721        }
8722
8723        boolean doRename(int status, final String pkgName,
8724                String oldCodePath) {
8725            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
8726            String newCachePath = null;
8727            if (PackageHelper.isContainerMounted(cid)) {
8728                // Unmount the container
8729                if (!PackageHelper.unMountSdDir(cid)) {
8730                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
8731                    return false;
8732                }
8733            }
8734            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
8735                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
8736                        " which might be stale. Will try to clean up.");
8737                // Clean up the stale container and proceed to recreate.
8738                if (!PackageHelper.destroySdDir(newCacheId)) {
8739                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
8740                    return false;
8741                }
8742                // Successfully cleaned up stale container. Try to rename again.
8743                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
8744                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
8745                            + " inspite of cleaning it up.");
8746                    return false;
8747                }
8748            }
8749            if (!PackageHelper.isContainerMounted(newCacheId)) {
8750                Slog.w(TAG, "Mounting container " + newCacheId);
8751                newCachePath = PackageHelper.mountSdDir(newCacheId,
8752                        getEncryptKey(), Process.SYSTEM_UID);
8753            } else {
8754                newCachePath = PackageHelper.getSdDir(newCacheId);
8755            }
8756            if (newCachePath == null) {
8757                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
8758                return false;
8759            }
8760            Log.i(TAG, "Succesfully renamed " + cid +
8761                    " to " + newCacheId +
8762                    " at new path: " + newCachePath);
8763            cid = newCacheId;
8764            setCachePath(newCachePath);
8765            return true;
8766        }
8767
8768        private void setCachePath(String newCachePath) {
8769            File cachePath = new File(newCachePath);
8770            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
8771            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
8772
8773            if (isFwdLocked()) {
8774                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
8775            } else {
8776                resourcePath = packagePath;
8777            }
8778        }
8779
8780        int doPostInstall(int status, int uid) {
8781            if (status != PackageManager.INSTALL_SUCCEEDED) {
8782                cleanUp();
8783            } else {
8784                final int groupOwner;
8785                final String protectedFile;
8786                if (isFwdLocked()) {
8787                    groupOwner = UserHandle.getSharedAppGid(uid);
8788                    protectedFile = RES_FILE_NAME;
8789                } else {
8790                    groupOwner = -1;
8791                    protectedFile = null;
8792                }
8793
8794                if (uid < Process.FIRST_APPLICATION_UID
8795                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
8796                    Slog.e(TAG, "Failed to finalize " + cid);
8797                    PackageHelper.destroySdDir(cid);
8798                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8799                }
8800
8801                boolean mounted = PackageHelper.isContainerMounted(cid);
8802                if (!mounted) {
8803                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
8804                }
8805            }
8806            return status;
8807        }
8808
8809        private void cleanUp() {
8810            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
8811
8812            // Destroy secure container
8813            PackageHelper.destroySdDir(cid);
8814        }
8815
8816        void cleanUpResourcesLI() {
8817            String sourceFile = getCodePath();
8818            // Remove dex file
8819            if (instructionSet == null) {
8820                throw new IllegalStateException("instructionSet == null");
8821            }
8822            int retCode = mInstaller.rmdex(sourceFile, instructionSet);
8823            if (retCode < 0) {
8824                Slog.w(TAG, "Couldn't remove dex file for package: "
8825                        + " at location "
8826                        + sourceFile.toString() + ", retcode=" + retCode);
8827                // we don't consider this to be a failure of the core package deletion
8828            }
8829            cleanUp();
8830        }
8831
8832        boolean matchContainer(String app) {
8833            if (cid.startsWith(app)) {
8834                return true;
8835            }
8836            return false;
8837        }
8838
8839        String getPackageName() {
8840            return getAsecPackageName(cid);
8841        }
8842
8843        boolean doPostDeleteLI(boolean delete) {
8844            boolean ret = false;
8845            boolean mounted = PackageHelper.isContainerMounted(cid);
8846            if (mounted) {
8847                // Unmount first
8848                ret = PackageHelper.unMountSdDir(cid);
8849            }
8850            if (ret && delete) {
8851                cleanUpResourcesLI();
8852            }
8853            return ret;
8854        }
8855
8856        @Override
8857        int doPreCopy() {
8858            if (isFwdLocked()) {
8859                if (!PackageHelper.fixSdPermissions(cid,
8860                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
8861                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8862                }
8863            }
8864
8865            return PackageManager.INSTALL_SUCCEEDED;
8866        }
8867
8868        @Override
8869        int doPostCopy(int uid) {
8870            if (isFwdLocked()) {
8871                if (uid < Process.FIRST_APPLICATION_UID
8872                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
8873                                RES_FILE_NAME)) {
8874                    Slog.e(TAG, "Failed to finalize " + cid);
8875                    PackageHelper.destroySdDir(cid);
8876                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8877                }
8878            }
8879
8880            return PackageManager.INSTALL_SUCCEEDED;
8881        }
8882    };
8883
8884    static String getAsecPackageName(String packageCid) {
8885        int idx = packageCid.lastIndexOf("-");
8886        if (idx == -1) {
8887            return packageCid;
8888        }
8889        return packageCid.substring(0, idx);
8890    }
8891
8892    // Utility method used to create code paths based on package name and available index.
8893    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
8894        String idxStr = "";
8895        int idx = 1;
8896        // Fall back to default value of idx=1 if prefix is not
8897        // part of oldCodePath
8898        if (oldCodePath != null) {
8899            String subStr = oldCodePath;
8900            // Drop the suffix right away
8901            if (subStr.endsWith(suffix)) {
8902                subStr = subStr.substring(0, subStr.length() - suffix.length());
8903            }
8904            // If oldCodePath already contains prefix find out the
8905            // ending index to either increment or decrement.
8906            int sidx = subStr.lastIndexOf(prefix);
8907            if (sidx != -1) {
8908                subStr = subStr.substring(sidx + prefix.length());
8909                if (subStr != null) {
8910                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
8911                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
8912                    }
8913                    try {
8914                        idx = Integer.parseInt(subStr);
8915                        if (idx <= 1) {
8916                            idx++;
8917                        } else {
8918                            idx--;
8919                        }
8920                    } catch(NumberFormatException e) {
8921                    }
8922                }
8923            }
8924        }
8925        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
8926        return prefix + idxStr;
8927    }
8928
8929    // Utility method used to ignore ADD/REMOVE events
8930    // by directory observer.
8931    private static boolean ignoreCodePath(String fullPathStr) {
8932        String apkName = getApkName(fullPathStr);
8933        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
8934        if (idx != -1 && ((idx+1) < apkName.length())) {
8935            // Make sure the package ends with a numeral
8936            String version = apkName.substring(idx+1);
8937            try {
8938                Integer.parseInt(version);
8939                return true;
8940            } catch (NumberFormatException e) {}
8941        }
8942        return false;
8943    }
8944
8945    // Utility method that returns the relative package path with respect
8946    // to the installation directory. Like say for /data/data/com.test-1.apk
8947    // string com.test-1 is returned.
8948    static String getApkName(String codePath) {
8949        if (codePath == null) {
8950            return null;
8951        }
8952        int sidx = codePath.lastIndexOf("/");
8953        int eidx = codePath.lastIndexOf(".");
8954        if (eidx == -1) {
8955            eidx = codePath.length();
8956        } else if (eidx == 0) {
8957            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
8958            return null;
8959        }
8960        return codePath.substring(sidx+1, eidx);
8961    }
8962
8963    class PackageInstalledInfo {
8964        String name;
8965        int uid;
8966        // The set of users that originally had this package installed.
8967        int[] origUsers;
8968        // The set of users that now have this package installed.
8969        int[] newUsers;
8970        PackageParser.Package pkg;
8971        int returnCode;
8972        PackageRemovedInfo removedInfo;
8973    }
8974
8975    /*
8976     * Install a non-existing package.
8977     */
8978    private void installNewPackageLI(PackageParser.Package pkg,
8979            int parseFlags, int scanMode, UserHandle user,
8980            String installerPackageName, PackageInstalledInfo res) {
8981        // Remember this for later, in case we need to rollback this install
8982        String pkgName = pkg.packageName;
8983
8984        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
8985        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
8986        synchronized(mPackages) {
8987            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
8988                // A package with the same name is already installed, though
8989                // it has been renamed to an older name.  The package we
8990                // are trying to install should be installed as an update to
8991                // the existing one, but that has not been requested, so bail.
8992                Slog.w(TAG, "Attempt to re-install " + pkgName
8993                        + " without first uninstalling package running as "
8994                        + mSettings.mRenamedPackages.get(pkgName));
8995                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8996                return;
8997            }
8998            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
8999                // Don't allow installation over an existing package with the same name.
9000                Slog.w(TAG, "Attempt to re-install " + pkgName
9001                        + " without first uninstalling.");
9002                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9003                return;
9004            }
9005        }
9006        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9007        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9008                System.currentTimeMillis(), user);
9009        if (newPackage == null) {
9010            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9011            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9012                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9013            }
9014        } else {
9015            updateSettingsLI(newPackage,
9016                    installerPackageName,
9017                    null, null,
9018                    res);
9019            // delete the partially installed application. the data directory will have to be
9020            // restored if it was already existing
9021            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9022                // remove package from internal structures.  Note that we want deletePackageX to
9023                // delete the package data and cache directories that it created in
9024                // scanPackageLocked, unless those directories existed before we even tried to
9025                // install.
9026                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9027                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9028                                res.removedInfo, true);
9029            }
9030        }
9031    }
9032
9033    private void replacePackageLI(PackageParser.Package pkg,
9034            int parseFlags, int scanMode, UserHandle user,
9035            String installerPackageName, PackageInstalledInfo res) {
9036
9037        PackageParser.Package oldPackage;
9038        String pkgName = pkg.packageName;
9039        int[] allUsers;
9040        boolean[] perUserInstalled;
9041
9042        // First find the old package info and check signatures
9043        synchronized(mPackages) {
9044            oldPackage = mPackages.get(pkgName);
9045            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9046            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9047                    != PackageManager.SIGNATURE_MATCH) {
9048                Slog.w(TAG, "New package has a different signature: " + pkgName);
9049                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9050                return;
9051            }
9052
9053            // In case of rollback, remember per-user/profile install state
9054            PackageSetting ps = mSettings.mPackages.get(pkgName);
9055            allUsers = sUserManager.getUserIds();
9056            perUserInstalled = new boolean[allUsers.length];
9057            for (int i = 0; i < allUsers.length; i++) {
9058                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9059            }
9060        }
9061        boolean sysPkg = (isSystemApp(oldPackage));
9062        if (sysPkg) {
9063            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9064                    user, allUsers, perUserInstalled, installerPackageName, res);
9065        } else {
9066            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9067                    user, allUsers, perUserInstalled, installerPackageName, res);
9068        }
9069    }
9070
9071    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9072            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9073            int[] allUsers, boolean[] perUserInstalled,
9074            String installerPackageName, PackageInstalledInfo res) {
9075        PackageParser.Package newPackage = null;
9076        String pkgName = deletedPackage.packageName;
9077        boolean deletedPkg = true;
9078        boolean updatedSettings = false;
9079
9080        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9081                + deletedPackage);
9082        long origUpdateTime;
9083        if (pkg.mExtras != null) {
9084            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9085        } else {
9086            origUpdateTime = 0;
9087        }
9088
9089        // First delete the existing package while retaining the data directory
9090        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9091                res.removedInfo, true)) {
9092            // If the existing package wasn't successfully deleted
9093            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9094            deletedPkg = false;
9095        } else {
9096            // Successfully deleted the old package. Now proceed with re-installation
9097            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9098            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
9099                    System.currentTimeMillis(), user);
9100            if (newPackage == null) {
9101                Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9102                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9103                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9104                }
9105            } else {
9106                updateSettingsLI(newPackage,
9107                        installerPackageName,
9108                        allUsers, perUserInstalled,
9109                        res);
9110                updatedSettings = true;
9111            }
9112        }
9113
9114        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9115            // remove package from internal structures.  Note that we want deletePackageX to
9116            // delete the package data and cache directories that it created in
9117            // scanPackageLocked, unless those directories existed before we even tried to
9118            // install.
9119            if(updatedSettings) {
9120                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9121                deletePackageLI(
9122                        pkgName, null, true, allUsers, perUserInstalled,
9123                        PackageManager.DELETE_KEEP_DATA,
9124                                res.removedInfo, true);
9125            }
9126            // Since we failed to install the new package we need to restore the old
9127            // package that we deleted.
9128            if(deletedPkg) {
9129                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9130                File restoreFile = new File(deletedPackage.mPath);
9131                // Parse old package
9132                boolean oldOnSd = isExternal(deletedPackage);
9133                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9134                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9135                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9136                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
9137                        | SCAN_UPDATE_TIME;
9138                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
9139                        origUpdateTime, null) == null) {
9140                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
9141                    return;
9142                }
9143                // Restore of old package succeeded. Update permissions.
9144                // writer
9145                synchronized (mPackages) {
9146                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9147                            UPDATE_PERMISSIONS_ALL);
9148                    // can downgrade to reader
9149                    mSettings.writeLPr();
9150                }
9151                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9152            }
9153        }
9154    }
9155
9156    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9157            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9158            int[] allUsers, boolean[] perUserInstalled,
9159            String installerPackageName, PackageInstalledInfo res) {
9160        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9161                + ", old=" + deletedPackage);
9162        PackageParser.Package newPackage = null;
9163        boolean updatedSettings = false;
9164        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
9165                PackageParser.PARSE_IS_SYSTEM;
9166        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9167            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9168        }
9169        String packageName = deletedPackage.packageName;
9170        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9171        if (packageName == null) {
9172            Slog.w(TAG, "Attempt to delete null packageName.");
9173            return;
9174        }
9175        PackageParser.Package oldPkg;
9176        PackageSetting oldPkgSetting;
9177        // reader
9178        synchronized (mPackages) {
9179            oldPkg = mPackages.get(packageName);
9180            oldPkgSetting = mSettings.mPackages.get(packageName);
9181            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9182                    (oldPkgSetting == null)) {
9183                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
9184                return;
9185            }
9186        }
9187
9188        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9189
9190        res.removedInfo.uid = oldPkg.applicationInfo.uid;
9191        res.removedInfo.removedPackage = packageName;
9192        // Remove existing system package
9193        removePackageLI(oldPkgSetting, true);
9194        // writer
9195        synchronized (mPackages) {
9196            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
9197                // We didn't need to disable the .apk as a current system package,
9198                // which means we are replacing another update that is already
9199                // installed.  We need to make sure to delete the older one's .apk.
9200                res.removedInfo.args = createInstallArgs(0,
9201                        deletedPackage.applicationInfo.sourceDir,
9202                        deletedPackage.applicationInfo.publicSourceDir,
9203                        deletedPackage.applicationInfo.nativeLibraryDir,
9204                        getAppInstructionSet(deletedPackage.applicationInfo));
9205            } else {
9206                res.removedInfo.args = null;
9207            }
9208        }
9209
9210        // Successfully disabled the old package. Now proceed with re-installation
9211        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9212        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9213        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
9214        if (newPackage == null) {
9215            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9216            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9217                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9218            }
9219        } else {
9220            if (newPackage.mExtras != null) {
9221                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
9222                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
9223                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
9224            }
9225            updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9226            updatedSettings = true;
9227        }
9228
9229        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9230            // Re installation failed. Restore old information
9231            // Remove new pkg information
9232            if (newPackage != null) {
9233                removeInstalledPackageLI(newPackage, true);
9234            }
9235            // Add back the old system package
9236            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
9237            // Restore the old system information in Settings
9238            synchronized(mPackages) {
9239                if (updatedSettings) {
9240                    mSettings.enableSystemPackageLPw(packageName);
9241                    mSettings.setInstallerPackageName(packageName,
9242                            oldPkgSetting.installerPackageName);
9243                }
9244                mSettings.writeLPr();
9245            }
9246        }
9247    }
9248
9249    // Utility method used to move dex files during install.
9250    private int moveDexFilesLI(PackageParser.Package newPackage) {
9251        int retCode;
9252        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
9253            retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath,
9254                    getAppInstructionSet(newPackage.applicationInfo));
9255            if (retCode != 0) {
9256                if (mNoDexOpt) {
9257                    /*
9258                     * If we're in an engineering build, programs are lazily run
9259                     * through dexopt. If the .dex file doesn't exist yet, it
9260                     * will be created when the program is run next.
9261                     */
9262                    Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
9263                } else {
9264                    Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
9265                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9266                }
9267            }
9268        }
9269        return PackageManager.INSTALL_SUCCEEDED;
9270    }
9271
9272    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
9273            int[] allUsers, boolean[] perUserInstalled,
9274            PackageInstalledInfo res) {
9275        String pkgName = newPackage.packageName;
9276        synchronized (mPackages) {
9277            //write settings. the installStatus will be incomplete at this stage.
9278            //note that the new package setting would have already been
9279            //added to mPackages. It hasn't been persisted yet.
9280            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
9281            mSettings.writeLPr();
9282        }
9283
9284        if ((res.returnCode = moveDexFilesLI(newPackage))
9285                != PackageManager.INSTALL_SUCCEEDED) {
9286            // Discontinue if moving dex files failed.
9287            return;
9288        }
9289
9290        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath);
9291
9292        synchronized (mPackages) {
9293            updatePermissionsLPw(newPackage.packageName, newPackage,
9294                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
9295                            ? UPDATE_PERMISSIONS_ALL : 0));
9296            // For system-bundled packages, we assume that installing an upgraded version
9297            // of the package implies that the user actually wants to run that new code,
9298            // so we enable the package.
9299            if (isSystemApp(newPackage)) {
9300                // NB: implicit assumption that system package upgrades apply to all users
9301                if (DEBUG_INSTALL) {
9302                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
9303                }
9304                PackageSetting ps = mSettings.mPackages.get(pkgName);
9305                if (ps != null) {
9306                    if (res.origUsers != null) {
9307                        for (int userHandle : res.origUsers) {
9308                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
9309                                    userHandle, installerPackageName);
9310                        }
9311                    }
9312                    // Also convey the prior install/uninstall state
9313                    if (allUsers != null && perUserInstalled != null) {
9314                        for (int i = 0; i < allUsers.length; i++) {
9315                            if (DEBUG_INSTALL) {
9316                                Slog.d(TAG, "    user " + allUsers[i]
9317                                        + " => " + perUserInstalled[i]);
9318                            }
9319                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
9320                        }
9321                        // these install state changes will be persisted in the
9322                        // upcoming call to mSettings.writeLPr().
9323                    }
9324                }
9325            }
9326            res.name = pkgName;
9327            res.uid = newPackage.applicationInfo.uid;
9328            res.pkg = newPackage;
9329            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
9330            mSettings.setInstallerPackageName(pkgName, installerPackageName);
9331            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9332            //to update install status
9333            mSettings.writeLPr();
9334        }
9335    }
9336
9337    private void installPackageLI(InstallArgs args,
9338            boolean newInstall, PackageInstalledInfo res) {
9339        int pFlags = args.flags;
9340        String installerPackageName = args.installerPackageName;
9341        File tmpPackageFile = new File(args.getCodePath());
9342        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
9343        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
9344        boolean replace = false;
9345        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
9346                | (newInstall ? SCAN_NEW_INSTALL : 0);
9347        // Result object to be returned
9348        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9349
9350        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
9351        // Retrieve PackageSettings and parse package
9352        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
9353                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
9354                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
9355        PackageParser pp = new PackageParser(tmpPackageFile.getPath());
9356        pp.setSeparateProcesses(mSeparateProcesses);
9357        final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
9358                null, mMetrics, parseFlags);
9359        if (pkg == null) {
9360            res.returnCode = pp.getParseError();
9361            return;
9362        }
9363        String pkgName = res.name = pkg.packageName;
9364        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
9365            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
9366                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
9367                return;
9368            }
9369        }
9370        if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
9371            res.returnCode = pp.getParseError();
9372            return;
9373        }
9374
9375        /* If the installer passed in a manifest digest, compare it now. */
9376        if (args.manifestDigest != null) {
9377            if (DEBUG_INSTALL) {
9378                final String parsedManifest = pkg.manifestDigest == null ? "null"
9379                        : pkg.manifestDigest.toString();
9380                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
9381                        + parsedManifest);
9382            }
9383
9384            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
9385                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
9386                return;
9387            }
9388        } else if (DEBUG_INSTALL) {
9389            final String parsedManifest = pkg.manifestDigest == null
9390                    ? "null" : pkg.manifestDigest.toString();
9391            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
9392        }
9393
9394        // Get rid of all references to package scan path via parser.
9395        pp = null;
9396        String oldCodePath = null;
9397        boolean systemApp = false;
9398        synchronized (mPackages) {
9399            // Check if installing already existing package
9400            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9401                String oldName = mSettings.mRenamedPackages.get(pkgName);
9402                if (pkg.mOriginalPackages != null
9403                        && pkg.mOriginalPackages.contains(oldName)
9404                        && mPackages.containsKey(oldName)) {
9405                    // This package is derived from an original package,
9406                    // and this device has been updating from that original
9407                    // name.  We must continue using the original name, so
9408                    // rename the new package here.
9409                    pkg.setPackageName(oldName);
9410                    pkgName = pkg.packageName;
9411                    replace = true;
9412                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
9413                            + oldName + " pkgName=" + pkgName);
9414                } else if (mPackages.containsKey(pkgName)) {
9415                    // This package, under its official name, already exists
9416                    // on the device; we should replace it.
9417                    replace = true;
9418                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
9419                }
9420            }
9421            PackageSetting ps = mSettings.mPackages.get(pkgName);
9422            if (ps != null) {
9423                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
9424                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
9425                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
9426                    systemApp = (ps.pkg.applicationInfo.flags &
9427                            ApplicationInfo.FLAG_SYSTEM) != 0;
9428                }
9429                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
9430            }
9431        }
9432
9433        if (systemApp && onSd) {
9434            // Disable updates to system apps on sdcard
9435            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
9436            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9437            return;
9438        }
9439
9440        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
9441            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9442            return;
9443        }
9444        // Set application objects path explicitly after the rename
9445        setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
9446        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
9447        if (replace) {
9448            replacePackageLI(pkg, parseFlags, scanMode, args.user,
9449                    installerPackageName, res);
9450        } else {
9451            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
9452                    installerPackageName, res);
9453        }
9454        synchronized (mPackages) {
9455            final PackageSetting ps = mSettings.mPackages.get(pkgName);
9456            if (ps != null) {
9457                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
9458            }
9459        }
9460    }
9461
9462    private static boolean isForwardLocked(PackageParser.Package pkg) {
9463        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
9464    }
9465
9466
9467    private boolean isForwardLocked(PackageSetting ps) {
9468        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
9469    }
9470
9471    private static boolean isExternal(PackageParser.Package pkg) {
9472        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
9473    }
9474
9475    private static boolean isExternal(PackageSetting ps) {
9476        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
9477    }
9478
9479    private static boolean isSystemApp(PackageParser.Package pkg) {
9480        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9481    }
9482
9483    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
9484        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
9485    }
9486
9487    private static boolean isSystemApp(ApplicationInfo info) {
9488        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9489    }
9490
9491    private static boolean isSystemApp(PackageSetting ps) {
9492        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
9493    }
9494
9495    private static boolean isUpdatedSystemApp(PackageSetting ps) {
9496        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
9497    }
9498
9499    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
9500        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
9501    }
9502
9503    private int packageFlagsToInstallFlags(PackageSetting ps) {
9504        int installFlags = 0;
9505        if (isExternal(ps)) {
9506            installFlags |= PackageManager.INSTALL_EXTERNAL;
9507        }
9508        if (isForwardLocked(ps)) {
9509            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9510        }
9511        return installFlags;
9512    }
9513
9514    private void deleteTempPackageFiles() {
9515        final FilenameFilter filter = new FilenameFilter() {
9516            public boolean accept(File dir, String name) {
9517                return name.startsWith("vmdl") && name.endsWith(".tmp");
9518            }
9519        };
9520        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
9521        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
9522    }
9523
9524    private static final void deleteTempPackageFilesInDirectory(File directory,
9525            FilenameFilter filter) {
9526        final String[] tmpFilesList = directory.list(filter);
9527        if (tmpFilesList == null) {
9528            return;
9529        }
9530        for (int i = 0; i < tmpFilesList.length; i++) {
9531            final File tmpFile = new File(directory, tmpFilesList[i]);
9532            tmpFile.delete();
9533        }
9534    }
9535
9536    private File createTempPackageFile(File installDir) {
9537        File tmpPackageFile;
9538        try {
9539            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
9540        } catch (IOException e) {
9541            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
9542            return null;
9543        }
9544        try {
9545            FileUtils.setPermissions(
9546                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
9547                    -1, -1);
9548            if (!SELinux.restorecon(tmpPackageFile)) {
9549                return null;
9550            }
9551        } catch (IOException e) {
9552            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
9553            return null;
9554        }
9555        return tmpPackageFile;
9556    }
9557
9558    @Override
9559    public void deletePackageAsUser(final String packageName,
9560                                    final IPackageDeleteObserver observer,
9561                                    final int userId, final int flags) {
9562        mContext.enforceCallingOrSelfPermission(
9563                android.Manifest.permission.DELETE_PACKAGES, null);
9564        final int uid = Binder.getCallingUid();
9565        if (UserHandle.getUserId(uid) != userId) {
9566            mContext.enforceCallingPermission(
9567                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
9568                    "deletePackage for user " + userId);
9569        }
9570        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
9571            try {
9572                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
9573            } catch (RemoteException re) {
9574            }
9575            return;
9576        }
9577
9578        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
9579        // Queue up an async operation since the package deletion may take a little while.
9580        mHandler.post(new Runnable() {
9581            public void run() {
9582                mHandler.removeCallbacks(this);
9583                final int returnCode = deletePackageX(packageName, userId, flags);
9584                if (observer != null) {
9585                    try {
9586                        observer.packageDeleted(packageName, returnCode);
9587                    } catch (RemoteException e) {
9588                        Log.i(TAG, "Observer no longer exists.");
9589                    } //end catch
9590                } //end if
9591            } //end run
9592        });
9593    }
9594
9595    private boolean isPackageDeviceAdmin(String packageName, int userId) {
9596        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
9597                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
9598        try {
9599            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
9600                    || dpm.isDeviceOwner(packageName))) {
9601                return true;
9602            }
9603        } catch (RemoteException e) {
9604        }
9605        return false;
9606    }
9607
9608    /**
9609     *  This method is an internal method that could be get invoked either
9610     *  to delete an installed package or to clean up a failed installation.
9611     *  After deleting an installed package, a broadcast is sent to notify any
9612     *  listeners that the package has been installed. For cleaning up a failed
9613     *  installation, the broadcast is not necessary since the package's
9614     *  installation wouldn't have sent the initial broadcast either
9615     *  The key steps in deleting a package are
9616     *  deleting the package information in internal structures like mPackages,
9617     *  deleting the packages base directories through installd
9618     *  updating mSettings to reflect current status
9619     *  persisting settings for later use
9620     *  sending a broadcast if necessary
9621     */
9622    private int deletePackageX(String packageName, int userId, int flags) {
9623        final PackageRemovedInfo info = new PackageRemovedInfo();
9624        final boolean res;
9625
9626        if (isPackageDeviceAdmin(packageName, userId)) {
9627            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
9628            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
9629        }
9630
9631        boolean removedForAllUsers = false;
9632        boolean systemUpdate = false;
9633
9634        // for the uninstall-updates case and restricted profiles, remember the per-
9635        // userhandle installed state
9636        int[] allUsers;
9637        boolean[] perUserInstalled;
9638        synchronized (mPackages) {
9639            PackageSetting ps = mSettings.mPackages.get(packageName);
9640            allUsers = sUserManager.getUserIds();
9641            perUserInstalled = new boolean[allUsers.length];
9642            for (int i = 0; i < allUsers.length; i++) {
9643                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9644            }
9645        }
9646
9647        synchronized (mInstallLock) {
9648            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
9649            res = deletePackageLI(packageName,
9650                    (flags & PackageManager.DELETE_ALL_USERS) != 0
9651                            ? UserHandle.ALL : new UserHandle(userId),
9652                    true, allUsers, perUserInstalled,
9653                    flags | REMOVE_CHATTY, info, true);
9654            systemUpdate = info.isRemovedPackageSystemUpdate;
9655            if (res && !systemUpdate && mPackages.get(packageName) == null) {
9656                removedForAllUsers = true;
9657            }
9658            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
9659                    + " removedForAllUsers=" + removedForAllUsers);
9660        }
9661
9662        if (res) {
9663            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
9664
9665            // If the removed package was a system update, the old system package
9666            // was re-enabled; we need to broadcast this information
9667            if (systemUpdate) {
9668                Bundle extras = new Bundle(1);
9669                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
9670                        ? info.removedAppId : info.uid);
9671                extras.putBoolean(Intent.EXTRA_REPLACING, true);
9672
9673                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
9674                        extras, null, null, null);
9675                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
9676                        extras, null, null, null);
9677                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
9678                        null, packageName, null, null);
9679            }
9680        }
9681        // Force a gc here.
9682        Runtime.getRuntime().gc();
9683        // Delete the resources here after sending the broadcast to let
9684        // other processes clean up before deleting resources.
9685        if (info.args != null) {
9686            synchronized (mInstallLock) {
9687                info.args.doPostDeleteLI(true);
9688            }
9689        }
9690
9691        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
9692    }
9693
9694    static class PackageRemovedInfo {
9695        String removedPackage;
9696        int uid = -1;
9697        int removedAppId = -1;
9698        int[] removedUsers = null;
9699        boolean isRemovedPackageSystemUpdate = false;
9700        // Clean up resources deleted packages.
9701        InstallArgs args = null;
9702
9703        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
9704            Bundle extras = new Bundle(1);
9705            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
9706            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
9707            if (replacing) {
9708                extras.putBoolean(Intent.EXTRA_REPLACING, true);
9709            }
9710            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
9711            if (removedPackage != null) {
9712                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
9713                        extras, null, null, removedUsers);
9714                if (fullRemove && !replacing) {
9715                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
9716                            extras, null, null, removedUsers);
9717                }
9718            }
9719            if (removedAppId >= 0) {
9720                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
9721                        removedUsers);
9722            }
9723        }
9724    }
9725
9726    /*
9727     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
9728     * flag is not set, the data directory is removed as well.
9729     * make sure this flag is set for partially installed apps. If not its meaningless to
9730     * delete a partially installed application.
9731     */
9732    private void removePackageDataLI(PackageSetting ps,
9733            int[] allUserHandles, boolean[] perUserInstalled,
9734            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
9735        String packageName = ps.name;
9736        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
9737        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
9738        // Retrieve object to delete permissions for shared user later on
9739        final PackageSetting deletedPs;
9740        // reader
9741        synchronized (mPackages) {
9742            deletedPs = mSettings.mPackages.get(packageName);
9743            if (outInfo != null) {
9744                outInfo.removedPackage = packageName;
9745                outInfo.removedUsers = deletedPs != null
9746                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
9747                        : null;
9748            }
9749        }
9750        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
9751            removeDataDirsLI(packageName);
9752            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
9753        }
9754        // writer
9755        synchronized (mPackages) {
9756            if (deletedPs != null) {
9757                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
9758                    if (outInfo != null) {
9759                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
9760                    }
9761                    if (deletedPs != null) {
9762                        updatePermissionsLPw(deletedPs.name, null, 0);
9763                        if (deletedPs.sharedUser != null) {
9764                            // remove permissions associated with package
9765                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
9766                        }
9767                    }
9768                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
9769                }
9770                // make sure to preserve per-user disabled state if this removal was just
9771                // a downgrade of a system app to the factory package
9772                if (allUserHandles != null && perUserInstalled != null) {
9773                    if (DEBUG_REMOVE) {
9774                        Slog.d(TAG, "Propagating install state across downgrade");
9775                    }
9776                    for (int i = 0; i < allUserHandles.length; i++) {
9777                        if (DEBUG_REMOVE) {
9778                            Slog.d(TAG, "    user " + allUserHandles[i]
9779                                    + " => " + perUserInstalled[i]);
9780                        }
9781                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
9782                    }
9783                }
9784            }
9785            // can downgrade to reader
9786            if (writeSettings) {
9787                // Save settings now
9788                mSettings.writeLPr();
9789            }
9790        }
9791        if (outInfo != null) {
9792            // A user ID was deleted here. Go through all users and remove it
9793            // from KeyStore.
9794            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
9795        }
9796    }
9797
9798    static boolean locationIsPrivileged(File path) {
9799        try {
9800            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
9801                    .getCanonicalPath();
9802            return path.getCanonicalPath().startsWith(privilegedAppDir);
9803        } catch (IOException e) {
9804            Slog.e(TAG, "Unable to access code path " + path);
9805        }
9806        return false;
9807    }
9808
9809    /*
9810     * Tries to delete system package.
9811     */
9812    private boolean deleteSystemPackageLI(PackageSetting newPs,
9813            int[] allUserHandles, boolean[] perUserInstalled,
9814            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
9815        final boolean applyUserRestrictions
9816                = (allUserHandles != null) && (perUserInstalled != null);
9817        PackageSetting disabledPs = null;
9818        // Confirm if the system package has been updated
9819        // An updated system app can be deleted. This will also have to restore
9820        // the system pkg from system partition
9821        // reader
9822        synchronized (mPackages) {
9823            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
9824        }
9825        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
9826                + " disabledPs=" + disabledPs);
9827        if (disabledPs == null) {
9828            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
9829            return false;
9830        } else if (DEBUG_REMOVE) {
9831            Slog.d(TAG, "Deleting system pkg from data partition");
9832        }
9833        if (DEBUG_REMOVE) {
9834            if (applyUserRestrictions) {
9835                Slog.d(TAG, "Remembering install states:");
9836                for (int i = 0; i < allUserHandles.length; i++) {
9837                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
9838                }
9839            }
9840        }
9841        // Delete the updated package
9842        outInfo.isRemovedPackageSystemUpdate = true;
9843        if (disabledPs.versionCode < newPs.versionCode) {
9844            // Delete data for downgrades
9845            flags &= ~PackageManager.DELETE_KEEP_DATA;
9846        } else {
9847            // Preserve data by setting flag
9848            flags |= PackageManager.DELETE_KEEP_DATA;
9849        }
9850        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
9851                allUserHandles, perUserInstalled, outInfo, writeSettings);
9852        if (!ret) {
9853            return false;
9854        }
9855        // writer
9856        synchronized (mPackages) {
9857            // Reinstate the old system package
9858            mSettings.enableSystemPackageLPw(newPs.name);
9859            // Remove any native libraries from the upgraded package.
9860            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
9861        }
9862        // Install the system package
9863        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
9864        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
9865        if (locationIsPrivileged(disabledPs.codePath)) {
9866            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9867        }
9868        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
9869                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
9870
9871        if (newPkg == null) {
9872            Slog.w(TAG, "Failed to restore system package:" + newPs.name
9873                    + " with error:" + mLastScanError);
9874            return false;
9875        }
9876        // writer
9877        synchronized (mPackages) {
9878            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
9879            setInternalAppNativeLibraryPath(newPkg, ps);
9880            updatePermissionsLPw(newPkg.packageName, newPkg,
9881                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
9882            if (applyUserRestrictions) {
9883                if (DEBUG_REMOVE) {
9884                    Slog.d(TAG, "Propagating install state across reinstall");
9885                }
9886                for (int i = 0; i < allUserHandles.length; i++) {
9887                    if (DEBUG_REMOVE) {
9888                        Slog.d(TAG, "    user " + allUserHandles[i]
9889                                + " => " + perUserInstalled[i]);
9890                    }
9891                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
9892                }
9893                // Regardless of writeSettings we need to ensure that this restriction
9894                // state propagation is persisted
9895                mSettings.writeAllUsersPackageRestrictionsLPr();
9896            }
9897            // can downgrade to reader here
9898            if (writeSettings) {
9899                mSettings.writeLPr();
9900            }
9901        }
9902        return true;
9903    }
9904
9905    private boolean deleteInstalledPackageLI(PackageSetting ps,
9906            boolean deleteCodeAndResources, int flags,
9907            int[] allUserHandles, boolean[] perUserInstalled,
9908            PackageRemovedInfo outInfo, boolean writeSettings) {
9909        if (outInfo != null) {
9910            outInfo.uid = ps.appId;
9911        }
9912
9913        // Delete package data from internal structures and also remove data if flag is set
9914        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
9915
9916        // Delete application code and resources
9917        if (deleteCodeAndResources && (outInfo != null)) {
9918            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
9919                    ps.resourcePathString, ps.nativeLibraryPathString,
9920                    getAppInstructionSetFromSettings(ps));
9921        }
9922        return true;
9923    }
9924
9925    /*
9926     * This method handles package deletion in general
9927     */
9928    private boolean deletePackageLI(String packageName, UserHandle user,
9929            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
9930            int flags, PackageRemovedInfo outInfo,
9931            boolean writeSettings) {
9932        if (packageName == null) {
9933            Slog.w(TAG, "Attempt to delete null packageName.");
9934            return false;
9935        }
9936        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
9937        PackageSetting ps;
9938        boolean dataOnly = false;
9939        int removeUser = -1;
9940        int appId = -1;
9941        synchronized (mPackages) {
9942            ps = mSettings.mPackages.get(packageName);
9943            if (ps == null) {
9944                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
9945                return false;
9946            }
9947            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
9948                    && user.getIdentifier() != UserHandle.USER_ALL) {
9949                // The caller is asking that the package only be deleted for a single
9950                // user.  To do this, we just mark its uninstalled state and delete
9951                // its data.  If this is a system app, we only allow this to happen if
9952                // they have set the special DELETE_SYSTEM_APP which requests different
9953                // semantics than normal for uninstalling system apps.
9954                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
9955                ps.setUserState(user.getIdentifier(),
9956                        COMPONENT_ENABLED_STATE_DEFAULT,
9957                        false, //installed
9958                        true,  //stopped
9959                        true,  //notLaunched
9960                        false, //blocked
9961                        null, null, null);
9962                if (!isSystemApp(ps)) {
9963                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
9964                        // Other user still have this package installed, so all
9965                        // we need to do is clear this user's data and save that
9966                        // it is uninstalled.
9967                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
9968                        removeUser = user.getIdentifier();
9969                        appId = ps.appId;
9970                        mSettings.writePackageRestrictionsLPr(removeUser);
9971                    } else {
9972                        // We need to set it back to 'installed' so the uninstall
9973                        // broadcasts will be sent correctly.
9974                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
9975                        ps.setInstalled(true, user.getIdentifier());
9976                    }
9977                } else {
9978                    // This is a system app, so we assume that the
9979                    // other users still have this package installed, so all
9980                    // we need to do is clear this user's data and save that
9981                    // it is uninstalled.
9982                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
9983                    removeUser = user.getIdentifier();
9984                    appId = ps.appId;
9985                    mSettings.writePackageRestrictionsLPr(removeUser);
9986                }
9987            }
9988        }
9989
9990        if (removeUser >= 0) {
9991            // From above, we determined that we are deleting this only
9992            // for a single user.  Continue the work here.
9993            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
9994            if (outInfo != null) {
9995                outInfo.removedPackage = packageName;
9996                outInfo.removedAppId = appId;
9997                outInfo.removedUsers = new int[] {removeUser};
9998            }
9999            mInstaller.clearUserData(packageName, removeUser);
10000            removeKeystoreDataIfNeeded(removeUser, appId);
10001            schedulePackageCleaning(packageName, removeUser, false);
10002            return true;
10003        }
10004
10005        if (dataOnly) {
10006            // Delete application data first
10007            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10008            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10009            return true;
10010        }
10011
10012        boolean ret = false;
10013        mSettings.mKeySetManager.removeAppKeySetData(packageName);
10014        if (isSystemApp(ps)) {
10015            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10016            // When an updated system application is deleted we delete the existing resources as well and
10017            // fall back to existing code in system partition
10018            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10019                    flags, outInfo, writeSettings);
10020        } else {
10021            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10022            // Kill application pre-emptively especially for apps on sd.
10023            killApplication(packageName, ps.appId, "uninstall pkg");
10024            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10025                    allUserHandles, perUserInstalled,
10026                    outInfo, writeSettings);
10027        }
10028
10029        return ret;
10030    }
10031
10032    private final class ClearStorageConnection implements ServiceConnection {
10033        IMediaContainerService mContainerService;
10034
10035        @Override
10036        public void onServiceConnected(ComponentName name, IBinder service) {
10037            synchronized (this) {
10038                mContainerService = IMediaContainerService.Stub.asInterface(service);
10039                notifyAll();
10040            }
10041        }
10042
10043        @Override
10044        public void onServiceDisconnected(ComponentName name) {
10045        }
10046    }
10047
10048    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10049        final boolean mounted;
10050        if (Environment.isExternalStorageEmulated()) {
10051            mounted = true;
10052        } else {
10053            final String status = Environment.getExternalStorageState();
10054
10055            mounted = status.equals(Environment.MEDIA_MOUNTED)
10056                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10057        }
10058
10059        if (!mounted) {
10060            return;
10061        }
10062
10063        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10064        int[] users;
10065        if (userId == UserHandle.USER_ALL) {
10066            users = sUserManager.getUserIds();
10067        } else {
10068            users = new int[] { userId };
10069        }
10070        final ClearStorageConnection conn = new ClearStorageConnection();
10071        if (mContext.bindServiceAsUser(
10072                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10073            try {
10074                for (int curUser : users) {
10075                    long timeout = SystemClock.uptimeMillis() + 5000;
10076                    synchronized (conn) {
10077                        long now = SystemClock.uptimeMillis();
10078                        while (conn.mContainerService == null && now < timeout) {
10079                            try {
10080                                conn.wait(timeout - now);
10081                            } catch (InterruptedException e) {
10082                            }
10083                        }
10084                    }
10085                    if (conn.mContainerService == null) {
10086                        return;
10087                    }
10088
10089                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10090                    clearDirectory(conn.mContainerService,
10091                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10092                    if (allData) {
10093                        clearDirectory(conn.mContainerService,
10094                                userEnv.buildExternalStorageAppDataDirs(packageName));
10095                        clearDirectory(conn.mContainerService,
10096                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10097                    }
10098                }
10099            } finally {
10100                mContext.unbindService(conn);
10101            }
10102        }
10103    }
10104
10105    @Override
10106    public void clearApplicationUserData(final String packageName,
10107            final IPackageDataObserver observer, final int userId) {
10108        mContext.enforceCallingOrSelfPermission(
10109                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10110        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
10111        // Queue up an async operation since the package deletion may take a little while.
10112        mHandler.post(new Runnable() {
10113            public void run() {
10114                mHandler.removeCallbacks(this);
10115                final boolean succeeded;
10116                synchronized (mInstallLock) {
10117                    succeeded = clearApplicationUserDataLI(packageName, userId);
10118                }
10119                clearExternalStorageDataSync(packageName, userId, true);
10120                if (succeeded) {
10121                    // invoke DeviceStorageMonitor's update method to clear any notifications
10122                    DeviceStorageMonitorInternal
10123                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
10124                    if (dsm != null) {
10125                        dsm.checkMemory();
10126                    }
10127                }
10128                if(observer != null) {
10129                    try {
10130                        observer.onRemoveCompleted(packageName, succeeded);
10131                    } catch (RemoteException e) {
10132                        Log.i(TAG, "Observer no longer exists.");
10133                    }
10134                } //end if observer
10135            } //end run
10136        });
10137    }
10138
10139    private boolean clearApplicationUserDataLI(String packageName, int userId) {
10140        if (packageName == null) {
10141            Slog.w(TAG, "Attempt to delete null packageName.");
10142            return false;
10143        }
10144        PackageParser.Package p;
10145        boolean dataOnly = false;
10146        final int appId;
10147        synchronized (mPackages) {
10148            p = mPackages.get(packageName);
10149            if (p == null) {
10150                dataOnly = true;
10151                PackageSetting ps = mSettings.mPackages.get(packageName);
10152                if ((ps == null) || (ps.pkg == null)) {
10153                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10154                    return false;
10155                }
10156                p = ps.pkg;
10157            }
10158            if (!dataOnly) {
10159                // need to check this only for fully installed applications
10160                if (p == null) {
10161                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10162                    return false;
10163                }
10164                final ApplicationInfo applicationInfo = p.applicationInfo;
10165                if (applicationInfo == null) {
10166                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10167                    return false;
10168                }
10169            }
10170            if (p != null && p.applicationInfo != null) {
10171                appId = p.applicationInfo.uid;
10172            } else {
10173                appId = -1;
10174            }
10175        }
10176        int retCode = mInstaller.clearUserData(packageName, userId);
10177        if (retCode < 0) {
10178            Slog.w(TAG, "Couldn't remove cache files for package: "
10179                    + packageName);
10180            return false;
10181        }
10182        removeKeystoreDataIfNeeded(userId, appId);
10183        return true;
10184    }
10185
10186    /**
10187     * Remove entries from the keystore daemon. Will only remove it if the
10188     * {@code appId} is valid.
10189     */
10190    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
10191        if (appId < 0) {
10192            return;
10193        }
10194
10195        final KeyStore keyStore = KeyStore.getInstance();
10196        if (keyStore != null) {
10197            if (userId == UserHandle.USER_ALL) {
10198                for (final int individual : sUserManager.getUserIds()) {
10199                    keyStore.clearUid(UserHandle.getUid(individual, appId));
10200                }
10201            } else {
10202                keyStore.clearUid(UserHandle.getUid(userId, appId));
10203            }
10204        } else {
10205            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
10206        }
10207    }
10208
10209    public void deleteApplicationCacheFiles(final String packageName,
10210            final IPackageDataObserver observer) {
10211        mContext.enforceCallingOrSelfPermission(
10212                android.Manifest.permission.DELETE_CACHE_FILES, null);
10213        // Queue up an async operation since the package deletion may take a little while.
10214        final int userId = UserHandle.getCallingUserId();
10215        mHandler.post(new Runnable() {
10216            public void run() {
10217                mHandler.removeCallbacks(this);
10218                final boolean succeded;
10219                synchronized (mInstallLock) {
10220                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
10221                }
10222                clearExternalStorageDataSync(packageName, userId, false);
10223                if(observer != null) {
10224                    try {
10225                        observer.onRemoveCompleted(packageName, succeded);
10226                    } catch (RemoteException e) {
10227                        Log.i(TAG, "Observer no longer exists.");
10228                    }
10229                } //end if observer
10230            } //end run
10231        });
10232    }
10233
10234    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
10235        if (packageName == null) {
10236            Slog.w(TAG, "Attempt to delete null packageName.");
10237            return false;
10238        }
10239        PackageParser.Package p;
10240        synchronized (mPackages) {
10241            p = mPackages.get(packageName);
10242        }
10243        if (p == null) {
10244            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10245            return false;
10246        }
10247        final ApplicationInfo applicationInfo = p.applicationInfo;
10248        if (applicationInfo == null) {
10249            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10250            return false;
10251        }
10252        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
10253        if (retCode < 0) {
10254            Slog.w(TAG, "Couldn't remove cache files for package: "
10255                       + packageName + " u" + userId);
10256            return false;
10257        }
10258        return true;
10259    }
10260
10261    public void getPackageSizeInfo(final String packageName, int userHandle,
10262            final IPackageStatsObserver observer) {
10263        mContext.enforceCallingOrSelfPermission(
10264                android.Manifest.permission.GET_PACKAGE_SIZE, null);
10265
10266        PackageStats stats = new PackageStats(packageName, userHandle);
10267
10268        /*
10269         * Queue up an async operation since the package measurement may take a
10270         * little while.
10271         */
10272        Message msg = mHandler.obtainMessage(INIT_COPY);
10273        msg.obj = new MeasureParams(stats, observer);
10274        mHandler.sendMessage(msg);
10275    }
10276
10277    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
10278            PackageStats pStats) {
10279        if (packageName == null) {
10280            Slog.w(TAG, "Attempt to get size of null packageName.");
10281            return false;
10282        }
10283        PackageParser.Package p;
10284        boolean dataOnly = false;
10285        String libDirPath = null;
10286        String asecPath = null;
10287        PackageSetting ps = null;
10288        synchronized (mPackages) {
10289            p = mPackages.get(packageName);
10290            ps = mSettings.mPackages.get(packageName);
10291            if(p == null) {
10292                dataOnly = true;
10293                if((ps == null) || (ps.pkg == null)) {
10294                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10295                    return false;
10296                }
10297                p = ps.pkg;
10298            }
10299            if (ps != null) {
10300                libDirPath = ps.nativeLibraryPathString;
10301            }
10302            if (p != null && (isExternal(p) || isForwardLocked(p))) {
10303                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
10304                if (secureContainerId != null) {
10305                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
10306                }
10307            }
10308        }
10309        String publicSrcDir = null;
10310        if(!dataOnly) {
10311            final ApplicationInfo applicationInfo = p.applicationInfo;
10312            if (applicationInfo == null) {
10313                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10314                return false;
10315            }
10316            if (isForwardLocked(p)) {
10317                publicSrcDir = applicationInfo.publicSourceDir;
10318            }
10319        }
10320        int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath,
10321                publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps),
10322                pStats);
10323        if (res < 0) {
10324            return false;
10325        }
10326
10327        // Fix-up for forward-locked applications in ASEC containers.
10328        if (!isExternal(p)) {
10329            pStats.codeSize += pStats.externalCodeSize;
10330            pStats.externalCodeSize = 0L;
10331        }
10332
10333        return true;
10334    }
10335
10336
10337    public void addPackageToPreferred(String packageName) {
10338        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
10339    }
10340
10341    public void removePackageFromPreferred(String packageName) {
10342        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
10343    }
10344
10345    public List<PackageInfo> getPreferredPackages(int flags) {
10346        return new ArrayList<PackageInfo>();
10347    }
10348
10349    private int getUidTargetSdkVersionLockedLPr(int uid) {
10350        Object obj = mSettings.getUserIdLPr(uid);
10351        if (obj instanceof SharedUserSetting) {
10352            final SharedUserSetting sus = (SharedUserSetting) obj;
10353            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
10354            final Iterator<PackageSetting> it = sus.packages.iterator();
10355            while (it.hasNext()) {
10356                final PackageSetting ps = it.next();
10357                if (ps.pkg != null) {
10358                    int v = ps.pkg.applicationInfo.targetSdkVersion;
10359                    if (v < vers) vers = v;
10360                }
10361            }
10362            return vers;
10363        } else if (obj instanceof PackageSetting) {
10364            final PackageSetting ps = (PackageSetting) obj;
10365            if (ps.pkg != null) {
10366                return ps.pkg.applicationInfo.targetSdkVersion;
10367            }
10368        }
10369        return Build.VERSION_CODES.CUR_DEVELOPMENT;
10370    }
10371
10372    public void addPreferredActivity(IntentFilter filter, int match,
10373            ComponentName[] set, ComponentName activity, int userId) {
10374        addPreferredActivityInternal(filter, match, set, activity, true, userId);
10375    }
10376
10377    private void addPreferredActivityInternal(IntentFilter filter, int match,
10378            ComponentName[] set, ComponentName activity, boolean always, int userId) {
10379        // writer
10380        int callingUid = Binder.getCallingUid();
10381        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
10382        if (filter.countActions() == 0) {
10383            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
10384            return;
10385        }
10386        synchronized (mPackages) {
10387            if (mContext.checkCallingOrSelfPermission(
10388                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10389                    != PackageManager.PERMISSION_GRANTED) {
10390                if (getUidTargetSdkVersionLockedLPr(callingUid)
10391                        < Build.VERSION_CODES.FROYO) {
10392                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
10393                            + callingUid);
10394                    return;
10395                }
10396                mContext.enforceCallingOrSelfPermission(
10397                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10398            }
10399
10400            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
10401            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10402            mSettings.editPreferredActivitiesLPw(userId).addFilter(
10403                    new PreferredActivity(filter, match, set, activity, always));
10404            mSettings.writePackageRestrictionsLPr(userId);
10405        }
10406    }
10407
10408    public void replacePreferredActivity(IntentFilter filter, int match,
10409            ComponentName[] set, ComponentName activity) {
10410        if (filter.countActions() != 1) {
10411            throw new IllegalArgumentException(
10412                    "replacePreferredActivity expects filter to have only 1 action.");
10413        }
10414        if (filter.countDataAuthorities() != 0
10415                || filter.countDataPaths() != 0
10416                || filter.countDataSchemes() > 1
10417                || filter.countDataTypes() != 0) {
10418            throw new IllegalArgumentException(
10419                    "replacePreferredActivity expects filter to have no data authorities, " +
10420                    "paths, or types; and at most one scheme.");
10421        }
10422        synchronized (mPackages) {
10423            if (mContext.checkCallingOrSelfPermission(
10424                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10425                    != PackageManager.PERMISSION_GRANTED) {
10426                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
10427                        < Build.VERSION_CODES.FROYO) {
10428                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
10429                            + Binder.getCallingUid());
10430                    return;
10431                }
10432                mContext.enforceCallingOrSelfPermission(
10433                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10434            }
10435
10436            final int callingUserId = UserHandle.getCallingUserId();
10437            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
10438            if (pir != null) {
10439                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
10440                if (filter.countDataSchemes() == 1) {
10441                    Uri.Builder builder = new Uri.Builder();
10442                    builder.scheme(filter.getDataScheme(0));
10443                    intent.setData(builder.build());
10444                }
10445                List<PreferredActivity> matches = pir.queryIntent(
10446                        intent, null, true, callingUserId);
10447                if (DEBUG_PREFERRED) {
10448                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
10449                }
10450                for (int i = 0; i < matches.size(); i++) {
10451                    PreferredActivity pa = matches.get(i);
10452                    if (DEBUG_PREFERRED) {
10453                        Slog.i(TAG, "Removing preferred activity "
10454                                + pa.mPref.mComponent + ":");
10455                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10456                    }
10457                    pir.removeFilter(pa);
10458                }
10459            }
10460            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
10461        }
10462    }
10463
10464    public void clearPackagePreferredActivities(String packageName) {
10465        final int uid = Binder.getCallingUid();
10466        // writer
10467        synchronized (mPackages) {
10468            PackageParser.Package pkg = mPackages.get(packageName);
10469            if (pkg == null || pkg.applicationInfo.uid != uid) {
10470                if (mContext.checkCallingOrSelfPermission(
10471                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10472                        != PackageManager.PERMISSION_GRANTED) {
10473                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
10474                            < Build.VERSION_CODES.FROYO) {
10475                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
10476                                + Binder.getCallingUid());
10477                        return;
10478                    }
10479                    mContext.enforceCallingOrSelfPermission(
10480                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10481                }
10482            }
10483
10484            int user = UserHandle.getCallingUserId();
10485            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
10486                mSettings.writePackageRestrictionsLPr(user);
10487                scheduleWriteSettingsLocked();
10488            }
10489        }
10490    }
10491
10492    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
10493    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
10494        ArrayList<PreferredActivity> removed = null;
10495        boolean changed = false;
10496        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
10497            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
10498            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
10499            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
10500                continue;
10501            }
10502            Iterator<PreferredActivity> it = pir.filterIterator();
10503            while (it.hasNext()) {
10504                PreferredActivity pa = it.next();
10505                // Mark entry for removal only if it matches the package name
10506                // and the entry is of type "always".
10507                if (packageName == null ||
10508                        (pa.mPref.mComponent.getPackageName().equals(packageName)
10509                                && pa.mPref.mAlways)) {
10510                    if (removed == null) {
10511                        removed = new ArrayList<PreferredActivity>();
10512                    }
10513                    removed.add(pa);
10514                }
10515            }
10516            if (removed != null) {
10517                for (int j=0; j<removed.size(); j++) {
10518                    PreferredActivity pa = removed.get(j);
10519                    pir.removeFilter(pa);
10520                }
10521                changed = true;
10522            }
10523        }
10524        return changed;
10525    }
10526
10527    public void resetPreferredActivities(int userId) {
10528        mContext.enforceCallingOrSelfPermission(
10529                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10530        // writer
10531        synchronized (mPackages) {
10532            int user = UserHandle.getCallingUserId();
10533            clearPackagePreferredActivitiesLPw(null, user);
10534            mSettings.readDefaultPreferredAppsLPw(this, user);
10535            mSettings.writePackageRestrictionsLPr(user);
10536            scheduleWriteSettingsLocked();
10537        }
10538    }
10539
10540    public int getPreferredActivities(List<IntentFilter> outFilters,
10541            List<ComponentName> outActivities, String packageName) {
10542
10543        int num = 0;
10544        final int userId = UserHandle.getCallingUserId();
10545        // reader
10546        synchronized (mPackages) {
10547            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
10548            if (pir != null) {
10549                final Iterator<PreferredActivity> it = pir.filterIterator();
10550                while (it.hasNext()) {
10551                    final PreferredActivity pa = it.next();
10552                    if (packageName == null
10553                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
10554                                    && pa.mPref.mAlways)) {
10555                        if (outFilters != null) {
10556                            outFilters.add(new IntentFilter(pa));
10557                        }
10558                        if (outActivities != null) {
10559                            outActivities.add(pa.mPref.mComponent);
10560                        }
10561                    }
10562                }
10563            }
10564        }
10565
10566        return num;
10567    }
10568
10569    @Override
10570    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
10571        Intent intent = new Intent(Intent.ACTION_MAIN);
10572        intent.addCategory(Intent.CATEGORY_HOME);
10573
10574        final int callingUserId = UserHandle.getCallingUserId();
10575        List<ResolveInfo> list = queryIntentActivities(intent, null,
10576                PackageManager.GET_META_DATA, callingUserId);
10577        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
10578                true, false, false, callingUserId);
10579
10580        allHomeCandidates.clear();
10581        if (list != null) {
10582            for (ResolveInfo ri : list) {
10583                allHomeCandidates.add(ri);
10584            }
10585        }
10586        return (preferred == null || preferred.activityInfo == null)
10587                ? null
10588                : new ComponentName(preferred.activityInfo.packageName,
10589                        preferred.activityInfo.name);
10590    }
10591
10592    @Override
10593    public void setApplicationEnabledSetting(String appPackageName,
10594            int newState, int flags, int userId, String callingPackage) {
10595        if (!sUserManager.exists(userId)) return;
10596        if (callingPackage == null) {
10597            callingPackage = Integer.toString(Binder.getCallingUid());
10598        }
10599        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
10600    }
10601
10602    @Override
10603    public void setComponentEnabledSetting(ComponentName componentName,
10604            int newState, int flags, int userId) {
10605        if (!sUserManager.exists(userId)) return;
10606        setEnabledSetting(componentName.getPackageName(),
10607                componentName.getClassName(), newState, flags, userId, null);
10608    }
10609
10610    private void setEnabledSetting(final String packageName, String className, int newState,
10611            final int flags, int userId, String callingPackage) {
10612        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
10613              || newState == COMPONENT_ENABLED_STATE_ENABLED
10614              || newState == COMPONENT_ENABLED_STATE_DISABLED
10615              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
10616              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
10617            throw new IllegalArgumentException("Invalid new component state: "
10618                    + newState);
10619        }
10620        PackageSetting pkgSetting;
10621        final int uid = Binder.getCallingUid();
10622        final int permission = mContext.checkCallingOrSelfPermission(
10623                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
10624        enforceCrossUserPermission(uid, userId, false, "set enabled");
10625        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
10626        boolean sendNow = false;
10627        boolean isApp = (className == null);
10628        String componentName = isApp ? packageName : className;
10629        int packageUid = -1;
10630        ArrayList<String> components;
10631
10632        // writer
10633        synchronized (mPackages) {
10634            pkgSetting = mSettings.mPackages.get(packageName);
10635            if (pkgSetting == null) {
10636                if (className == null) {
10637                    throw new IllegalArgumentException(
10638                            "Unknown package: " + packageName);
10639                }
10640                throw new IllegalArgumentException(
10641                        "Unknown component: " + packageName
10642                        + "/" + className);
10643            }
10644            // Allow root and verify that userId is not being specified by a different user
10645            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
10646                throw new SecurityException(
10647                        "Permission Denial: attempt to change component state from pid="
10648                        + Binder.getCallingPid()
10649                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
10650            }
10651            if (className == null) {
10652                // We're dealing with an application/package level state change
10653                if (pkgSetting.getEnabled(userId) == newState) {
10654                    // Nothing to do
10655                    return;
10656                }
10657                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
10658                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
10659                    // Don't care about who enables an app.
10660                    callingPackage = null;
10661                }
10662                pkgSetting.setEnabled(newState, userId, callingPackage);
10663                // pkgSetting.pkg.mSetEnabled = newState;
10664            } else {
10665                // We're dealing with a component level state change
10666                // First, verify that this is a valid class name.
10667                PackageParser.Package pkg = pkgSetting.pkg;
10668                if (pkg == null || !pkg.hasComponentClassName(className)) {
10669                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
10670                        throw new IllegalArgumentException("Component class " + className
10671                                + " does not exist in " + packageName);
10672                    } else {
10673                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
10674                                + className + " does not exist in " + packageName);
10675                    }
10676                }
10677                switch (newState) {
10678                case COMPONENT_ENABLED_STATE_ENABLED:
10679                    if (!pkgSetting.enableComponentLPw(className, userId)) {
10680                        return;
10681                    }
10682                    break;
10683                case COMPONENT_ENABLED_STATE_DISABLED:
10684                    if (!pkgSetting.disableComponentLPw(className, userId)) {
10685                        return;
10686                    }
10687                    break;
10688                case COMPONENT_ENABLED_STATE_DEFAULT:
10689                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
10690                        return;
10691                    }
10692                    break;
10693                default:
10694                    Slog.e(TAG, "Invalid new component state: " + newState);
10695                    return;
10696                }
10697            }
10698            mSettings.writePackageRestrictionsLPr(userId);
10699            components = mPendingBroadcasts.get(userId, packageName);
10700            final boolean newPackage = components == null;
10701            if (newPackage) {
10702                components = new ArrayList<String>();
10703            }
10704            if (!components.contains(componentName)) {
10705                components.add(componentName);
10706            }
10707            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
10708                sendNow = true;
10709                // Purge entry from pending broadcast list if another one exists already
10710                // since we are sending one right away.
10711                mPendingBroadcasts.remove(userId, packageName);
10712            } else {
10713                if (newPackage) {
10714                    mPendingBroadcasts.put(userId, packageName, components);
10715                }
10716                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
10717                    // Schedule a message
10718                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
10719                }
10720            }
10721        }
10722
10723        long callingId = Binder.clearCallingIdentity();
10724        try {
10725            if (sendNow) {
10726                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
10727                sendPackageChangedBroadcast(packageName,
10728                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
10729            }
10730        } finally {
10731            Binder.restoreCallingIdentity(callingId);
10732        }
10733    }
10734
10735    private void sendPackageChangedBroadcast(String packageName,
10736            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
10737        if (DEBUG_INSTALL)
10738            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
10739                    + componentNames);
10740        Bundle extras = new Bundle(4);
10741        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
10742        String nameList[] = new String[componentNames.size()];
10743        componentNames.toArray(nameList);
10744        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
10745        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
10746        extras.putInt(Intent.EXTRA_UID, packageUid);
10747        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
10748                new int[] {UserHandle.getUserId(packageUid)});
10749    }
10750
10751    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
10752        if (!sUserManager.exists(userId)) return;
10753        final int uid = Binder.getCallingUid();
10754        final int permission = mContext.checkCallingOrSelfPermission(
10755                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
10756        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
10757        enforceCrossUserPermission(uid, userId, true, "stop package");
10758        // writer
10759        synchronized (mPackages) {
10760            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
10761                    uid, userId)) {
10762                scheduleWritePackageRestrictionsLocked(userId);
10763            }
10764        }
10765    }
10766
10767    public String getInstallerPackageName(String packageName) {
10768        // reader
10769        synchronized (mPackages) {
10770            return mSettings.getInstallerPackageNameLPr(packageName);
10771        }
10772    }
10773
10774    @Override
10775    public int getApplicationEnabledSetting(String packageName, int userId) {
10776        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
10777        int uid = Binder.getCallingUid();
10778        enforceCrossUserPermission(uid, userId, false, "get enabled");
10779        // reader
10780        synchronized (mPackages) {
10781            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
10782        }
10783    }
10784
10785    @Override
10786    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
10787        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
10788        int uid = Binder.getCallingUid();
10789        enforceCrossUserPermission(uid, userId, false, "get component enabled");
10790        // reader
10791        synchronized (mPackages) {
10792            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
10793        }
10794    }
10795
10796    public void enterSafeMode() {
10797        enforceSystemOrRoot("Only the system can request entering safe mode");
10798
10799        if (!mSystemReady) {
10800            mSafeMode = true;
10801        }
10802    }
10803
10804    public void systemReady() {
10805        mSystemReady = true;
10806
10807        // Read the compatibilty setting when the system is ready.
10808        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
10809                mContext.getContentResolver(),
10810                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
10811        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
10812        if (DEBUG_SETTINGS) {
10813            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
10814        }
10815
10816        synchronized (mPackages) {
10817            // Verify that all of the preferred activity components actually
10818            // exist.  It is possible for applications to be updated and at
10819            // that point remove a previously declared activity component that
10820            // had been set as a preferred activity.  We try to clean this up
10821            // the next time we encounter that preferred activity, but it is
10822            // possible for the user flow to never be able to return to that
10823            // situation so here we do a sanity check to make sure we haven't
10824            // left any junk around.
10825            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
10826            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
10827                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
10828                removed.clear();
10829                for (PreferredActivity pa : pir.filterSet()) {
10830                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
10831                        removed.add(pa);
10832                    }
10833                }
10834                if (removed.size() > 0) {
10835                    for (int j=0; j<removed.size(); j++) {
10836                        PreferredActivity pa = removed.get(i);
10837                        Slog.w(TAG, "Removing dangling preferred activity: "
10838                                + pa.mPref.mComponent);
10839                        pir.removeFilter(pa);
10840                    }
10841                    mSettings.writePackageRestrictionsLPr(
10842                            mSettings.mPreferredActivities.keyAt(i));
10843                }
10844            }
10845        }
10846        sUserManager.systemReady();
10847    }
10848
10849    public boolean isSafeMode() {
10850        return mSafeMode;
10851    }
10852
10853    public boolean hasSystemUidErrors() {
10854        return mHasSystemUidErrors;
10855    }
10856
10857    static String arrayToString(int[] array) {
10858        StringBuffer buf = new StringBuffer(128);
10859        buf.append('[');
10860        if (array != null) {
10861            for (int i=0; i<array.length; i++) {
10862                if (i > 0) buf.append(", ");
10863                buf.append(array[i]);
10864            }
10865        }
10866        buf.append(']');
10867        return buf.toString();
10868    }
10869
10870    static class DumpState {
10871        public static final int DUMP_LIBS = 1 << 0;
10872
10873        public static final int DUMP_FEATURES = 1 << 1;
10874
10875        public static final int DUMP_RESOLVERS = 1 << 2;
10876
10877        public static final int DUMP_PERMISSIONS = 1 << 3;
10878
10879        public static final int DUMP_PACKAGES = 1 << 4;
10880
10881        public static final int DUMP_SHARED_USERS = 1 << 5;
10882
10883        public static final int DUMP_MESSAGES = 1 << 6;
10884
10885        public static final int DUMP_PROVIDERS = 1 << 7;
10886
10887        public static final int DUMP_VERIFIERS = 1 << 8;
10888
10889        public static final int DUMP_PREFERRED = 1 << 9;
10890
10891        public static final int DUMP_PREFERRED_XML = 1 << 10;
10892
10893        public static final int DUMP_KEYSETS = 1 << 11;
10894
10895        public static final int OPTION_SHOW_FILTERS = 1 << 0;
10896
10897        private int mTypes;
10898
10899        private int mOptions;
10900
10901        private boolean mTitlePrinted;
10902
10903        private SharedUserSetting mSharedUser;
10904
10905        public boolean isDumping(int type) {
10906            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
10907                return true;
10908            }
10909
10910            return (mTypes & type) != 0;
10911        }
10912
10913        public void setDump(int type) {
10914            mTypes |= type;
10915        }
10916
10917        public boolean isOptionEnabled(int option) {
10918            return (mOptions & option) != 0;
10919        }
10920
10921        public void setOptionEnabled(int option) {
10922            mOptions |= option;
10923        }
10924
10925        public boolean onTitlePrinted() {
10926            final boolean printed = mTitlePrinted;
10927            mTitlePrinted = true;
10928            return printed;
10929        }
10930
10931        public boolean getTitlePrinted() {
10932            return mTitlePrinted;
10933        }
10934
10935        public void setTitlePrinted(boolean enabled) {
10936            mTitlePrinted = enabled;
10937        }
10938
10939        public SharedUserSetting getSharedUser() {
10940            return mSharedUser;
10941        }
10942
10943        public void setSharedUser(SharedUserSetting user) {
10944            mSharedUser = user;
10945        }
10946    }
10947
10948    @Override
10949    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
10950        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
10951                != PackageManager.PERMISSION_GRANTED) {
10952            pw.println("Permission Denial: can't dump ActivityManager from from pid="
10953                    + Binder.getCallingPid()
10954                    + ", uid=" + Binder.getCallingUid()
10955                    + " without permission "
10956                    + android.Manifest.permission.DUMP);
10957            return;
10958        }
10959
10960        DumpState dumpState = new DumpState();
10961        boolean fullPreferred = false;
10962        boolean checkin = false;
10963
10964        String packageName = null;
10965
10966        int opti = 0;
10967        while (opti < args.length) {
10968            String opt = args[opti];
10969            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10970                break;
10971            }
10972            opti++;
10973            if ("-a".equals(opt)) {
10974                // Right now we only know how to print all.
10975            } else if ("-h".equals(opt)) {
10976                pw.println("Package manager dump options:");
10977                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
10978                pw.println("    --checkin: dump for a checkin");
10979                pw.println("    -f: print details of intent filters");
10980                pw.println("    -h: print this help");
10981                pw.println("  cmd may be one of:");
10982                pw.println("    l[ibraries]: list known shared libraries");
10983                pw.println("    f[ibraries]: list device features");
10984                pw.println("    r[esolvers]: dump intent resolvers");
10985                pw.println("    perm[issions]: dump permissions");
10986                pw.println("    pref[erred]: print preferred package settings");
10987                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
10988                pw.println("    prov[iders]: dump content providers");
10989                pw.println("    p[ackages]: dump installed packages");
10990                pw.println("    s[hared-users]: dump shared user IDs");
10991                pw.println("    m[essages]: print collected runtime messages");
10992                pw.println("    v[erifiers]: print package verifier info");
10993                pw.println("    <package.name>: info about given package");
10994                pw.println("    k[eysets]: print known keysets");
10995                return;
10996            } else if ("--checkin".equals(opt)) {
10997                checkin = true;
10998            } else if ("-f".equals(opt)) {
10999                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11000            } else {
11001                pw.println("Unknown argument: " + opt + "; use -h for help");
11002            }
11003        }
11004
11005        // Is the caller requesting to dump a particular piece of data?
11006        if (opti < args.length) {
11007            String cmd = args[opti];
11008            opti++;
11009            // Is this a package name?
11010            if ("android".equals(cmd) || cmd.contains(".")) {
11011                packageName = cmd;
11012                // When dumping a single package, we always dump all of its
11013                // filter information since the amount of data will be reasonable.
11014                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11015            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
11016                dumpState.setDump(DumpState.DUMP_LIBS);
11017            } else if ("f".equals(cmd) || "features".equals(cmd)) {
11018                dumpState.setDump(DumpState.DUMP_FEATURES);
11019            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
11020                dumpState.setDump(DumpState.DUMP_RESOLVERS);
11021            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
11022                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
11023            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
11024                dumpState.setDump(DumpState.DUMP_PREFERRED);
11025            } else if ("preferred-xml".equals(cmd)) {
11026                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
11027                if (opti < args.length && "--full".equals(args[opti])) {
11028                    fullPreferred = true;
11029                    opti++;
11030                }
11031            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
11032                dumpState.setDump(DumpState.DUMP_PACKAGES);
11033            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
11034                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
11035            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
11036                dumpState.setDump(DumpState.DUMP_PROVIDERS);
11037            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
11038                dumpState.setDump(DumpState.DUMP_MESSAGES);
11039            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
11040                dumpState.setDump(DumpState.DUMP_VERIFIERS);
11041            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
11042                dumpState.setDump(DumpState.DUMP_KEYSETS);
11043            }
11044        }
11045
11046        if (checkin) {
11047            pw.println("vers,1");
11048        }
11049
11050        // reader
11051        synchronized (mPackages) {
11052            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
11053                if (!checkin) {
11054                    if (dumpState.onTitlePrinted())
11055                        pw.println();
11056                    pw.println("Verifiers:");
11057                    pw.print("  Required: ");
11058                    pw.print(mRequiredVerifierPackage);
11059                    pw.print(" (uid=");
11060                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
11061                    pw.println(")");
11062                } else if (mRequiredVerifierPackage != null) {
11063                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
11064                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
11065                }
11066            }
11067
11068            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
11069                boolean printedHeader = false;
11070                final Iterator<String> it = mSharedLibraries.keySet().iterator();
11071                while (it.hasNext()) {
11072                    String name = it.next();
11073                    SharedLibraryEntry ent = mSharedLibraries.get(name);
11074                    if (!checkin) {
11075                        if (!printedHeader) {
11076                            if (dumpState.onTitlePrinted())
11077                                pw.println();
11078                            pw.println("Libraries:");
11079                            printedHeader = true;
11080                        }
11081                        pw.print("  ");
11082                    } else {
11083                        pw.print("lib,");
11084                    }
11085                    pw.print(name);
11086                    if (!checkin) {
11087                        pw.print(" -> ");
11088                    }
11089                    if (ent.path != null) {
11090                        if (!checkin) {
11091                            pw.print("(jar) ");
11092                            pw.print(ent.path);
11093                        } else {
11094                            pw.print(",jar,");
11095                            pw.print(ent.path);
11096                        }
11097                    } else {
11098                        if (!checkin) {
11099                            pw.print("(apk) ");
11100                            pw.print(ent.apk);
11101                        } else {
11102                            pw.print(",apk,");
11103                            pw.print(ent.apk);
11104                        }
11105                    }
11106                    pw.println();
11107                }
11108            }
11109
11110            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
11111                if (dumpState.onTitlePrinted())
11112                    pw.println();
11113                if (!checkin) {
11114                    pw.println("Features:");
11115                }
11116                Iterator<String> it = mAvailableFeatures.keySet().iterator();
11117                while (it.hasNext()) {
11118                    String name = it.next();
11119                    if (!checkin) {
11120                        pw.print("  ");
11121                    } else {
11122                        pw.print("feat,");
11123                    }
11124                    pw.println(name);
11125                }
11126            }
11127
11128            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
11129                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
11130                        : "Activity Resolver Table:", "  ", packageName,
11131                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11132                    dumpState.setTitlePrinted(true);
11133                }
11134                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
11135                        : "Receiver Resolver Table:", "  ", packageName,
11136                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11137                    dumpState.setTitlePrinted(true);
11138                }
11139                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
11140                        : "Service Resolver Table:", "  ", packageName,
11141                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11142                    dumpState.setTitlePrinted(true);
11143                }
11144                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
11145                        : "Provider Resolver Table:", "  ", packageName,
11146                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11147                    dumpState.setTitlePrinted(true);
11148                }
11149            }
11150
11151            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
11152                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11153                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11154                    int user = mSettings.mPreferredActivities.keyAt(i);
11155                    if (pir.dump(pw,
11156                            dumpState.getTitlePrinted()
11157                                ? "\nPreferred Activities User " + user + ":"
11158                                : "Preferred Activities User " + user + ":", "  ",
11159                            packageName, true)) {
11160                        dumpState.setTitlePrinted(true);
11161                    }
11162                }
11163            }
11164
11165            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
11166                pw.flush();
11167                FileOutputStream fout = new FileOutputStream(fd);
11168                BufferedOutputStream str = new BufferedOutputStream(fout);
11169                XmlSerializer serializer = new FastXmlSerializer();
11170                try {
11171                    serializer.setOutput(str, "utf-8");
11172                    serializer.startDocument(null, true);
11173                    serializer.setFeature(
11174                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
11175                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
11176                    serializer.endDocument();
11177                    serializer.flush();
11178                } catch (IllegalArgumentException e) {
11179                    pw.println("Failed writing: " + e);
11180                } catch (IllegalStateException e) {
11181                    pw.println("Failed writing: " + e);
11182                } catch (IOException e) {
11183                    pw.println("Failed writing: " + e);
11184                }
11185            }
11186
11187            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
11188                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
11189            }
11190
11191            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
11192                boolean printedSomething = false;
11193                for (PackageParser.Provider p : mProviders.mProviders.values()) {
11194                    if (packageName != null && !packageName.equals(p.info.packageName)) {
11195                        continue;
11196                    }
11197                    if (!printedSomething) {
11198                        if (dumpState.onTitlePrinted())
11199                            pw.println();
11200                        pw.println("Registered ContentProviders:");
11201                        printedSomething = true;
11202                    }
11203                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
11204                    pw.print("    "); pw.println(p.toString());
11205                }
11206                printedSomething = false;
11207                for (Map.Entry<String, PackageParser.Provider> entry :
11208                        mProvidersByAuthority.entrySet()) {
11209                    PackageParser.Provider p = entry.getValue();
11210                    if (packageName != null && !packageName.equals(p.info.packageName)) {
11211                        continue;
11212                    }
11213                    if (!printedSomething) {
11214                        if (dumpState.onTitlePrinted())
11215                            pw.println();
11216                        pw.println("ContentProvider Authorities:");
11217                        printedSomething = true;
11218                    }
11219                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
11220                    pw.print("    "); pw.println(p.toString());
11221                    if (p.info != null && p.info.applicationInfo != null) {
11222                        final String appInfo = p.info.applicationInfo.toString();
11223                        pw.print("      applicationInfo="); pw.println(appInfo);
11224                    }
11225                }
11226            }
11227
11228            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
11229                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
11230            }
11231
11232            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
11233                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
11234            }
11235
11236            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
11237                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
11238            }
11239
11240            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
11241                if (dumpState.onTitlePrinted())
11242                    pw.println();
11243                mSettings.dumpReadMessagesLPr(pw, dumpState);
11244
11245                pw.println();
11246                pw.println("Package warning messages:");
11247                final File fname = getSettingsProblemFile();
11248                FileInputStream in = null;
11249                try {
11250                    in = new FileInputStream(fname);
11251                    final int avail = in.available();
11252                    final byte[] data = new byte[avail];
11253                    in.read(data);
11254                    pw.print(new String(data));
11255                } catch (FileNotFoundException e) {
11256                } catch (IOException e) {
11257                } finally {
11258                    if (in != null) {
11259                        try {
11260                            in.close();
11261                        } catch (IOException e) {
11262                        }
11263                    }
11264                }
11265            }
11266        }
11267    }
11268
11269    // ------- apps on sdcard specific code -------
11270    static final boolean DEBUG_SD_INSTALL = false;
11271
11272    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
11273
11274    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
11275
11276    private boolean mMediaMounted = false;
11277
11278    private String getEncryptKey() {
11279        try {
11280            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
11281                    SD_ENCRYPTION_KEYSTORE_NAME);
11282            if (sdEncKey == null) {
11283                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
11284                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
11285                if (sdEncKey == null) {
11286                    Slog.e(TAG, "Failed to create encryption keys");
11287                    return null;
11288                }
11289            }
11290            return sdEncKey;
11291        } catch (NoSuchAlgorithmException nsae) {
11292            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
11293            return null;
11294        } catch (IOException ioe) {
11295            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
11296            return null;
11297        }
11298
11299    }
11300
11301    /* package */static String getTempContainerId() {
11302        int tmpIdx = 1;
11303        String list[] = PackageHelper.getSecureContainerList();
11304        if (list != null) {
11305            for (final String name : list) {
11306                // Ignore null and non-temporary container entries
11307                if (name == null || !name.startsWith(mTempContainerPrefix)) {
11308                    continue;
11309                }
11310
11311                String subStr = name.substring(mTempContainerPrefix.length());
11312                try {
11313                    int cid = Integer.parseInt(subStr);
11314                    if (cid >= tmpIdx) {
11315                        tmpIdx = cid + 1;
11316                    }
11317                } catch (NumberFormatException e) {
11318                }
11319            }
11320        }
11321        return mTempContainerPrefix + tmpIdx;
11322    }
11323
11324    /*
11325     * Update media status on PackageManager.
11326     */
11327    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
11328        int callingUid = Binder.getCallingUid();
11329        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
11330            throw new SecurityException("Media status can only be updated by the system");
11331        }
11332        // reader; this apparently protects mMediaMounted, but should probably
11333        // be a different lock in that case.
11334        synchronized (mPackages) {
11335            Log.i(TAG, "Updating external media status from "
11336                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
11337                    + (mediaStatus ? "mounted" : "unmounted"));
11338            if (DEBUG_SD_INSTALL)
11339                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
11340                        + ", mMediaMounted=" + mMediaMounted);
11341            if (mediaStatus == mMediaMounted) {
11342                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
11343                        : 0, -1);
11344                mHandler.sendMessage(msg);
11345                return;
11346            }
11347            mMediaMounted = mediaStatus;
11348        }
11349        // Queue up an async operation since the package installation may take a
11350        // little while.
11351        mHandler.post(new Runnable() {
11352            public void run() {
11353                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
11354            }
11355        });
11356    }
11357
11358    /**
11359     * Called by MountService when the initial ASECs to scan are available.
11360     * Should block until all the ASEC containers are finished being scanned.
11361     */
11362    public void scanAvailableAsecs() {
11363        updateExternalMediaStatusInner(true, false, false);
11364        if (mShouldRestoreconData) {
11365            SELinuxMMAC.setRestoreconDone();
11366            mShouldRestoreconData = false;
11367        }
11368    }
11369
11370    /*
11371     * Collect information of applications on external media, map them against
11372     * existing containers and update information based on current mount status.
11373     * Please note that we always have to report status if reportStatus has been
11374     * set to true especially when unloading packages.
11375     */
11376    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
11377            boolean externalStorage) {
11378        // Collection of uids
11379        int uidArr[] = null;
11380        // Collection of stale containers
11381        HashSet<String> removeCids = new HashSet<String>();
11382        // Collection of packages on external media with valid containers.
11383        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
11384        // Get list of secure containers.
11385        final String list[] = PackageHelper.getSecureContainerList();
11386        if (list == null || list.length == 0) {
11387            Log.i(TAG, "No secure containers on sdcard");
11388        } else {
11389            // Process list of secure containers and categorize them
11390            // as active or stale based on their package internal state.
11391            int uidList[] = new int[list.length];
11392            int num = 0;
11393            // reader
11394            synchronized (mPackages) {
11395                for (String cid : list) {
11396                    if (DEBUG_SD_INSTALL)
11397                        Log.i(TAG, "Processing container " + cid);
11398                    String pkgName = getAsecPackageName(cid);
11399                    if (pkgName == null) {
11400                        if (DEBUG_SD_INSTALL)
11401                            Log.i(TAG, "Container : " + cid + " stale");
11402                        removeCids.add(cid);
11403                        continue;
11404                    }
11405                    if (DEBUG_SD_INSTALL)
11406                        Log.i(TAG, "Looking for pkg : " + pkgName);
11407
11408                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
11409                    if (ps == null) {
11410                        Log.i(TAG, "Deleting container with no matching settings " + cid);
11411                        removeCids.add(cid);
11412                        continue;
11413                    }
11414
11415                    /*
11416                     * Skip packages that are not external if we're unmounting
11417                     * external storage.
11418                     */
11419                    if (externalStorage && !isMounted && !isExternal(ps)) {
11420                        continue;
11421                    }
11422
11423                    final AsecInstallArgs args = new AsecInstallArgs(cid,
11424                            getAppInstructionSetFromSettings(ps),
11425                            isForwardLocked(ps));
11426                    // The package status is changed only if the code path
11427                    // matches between settings and the container id.
11428                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
11429                        if (DEBUG_SD_INSTALL) {
11430                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
11431                                    + " at code path: " + ps.codePathString);
11432                        }
11433
11434                        // We do have a valid package installed on sdcard
11435                        processCids.put(args, ps.codePathString);
11436                        final int uid = ps.appId;
11437                        if (uid != -1) {
11438                            uidList[num++] = uid;
11439                        }
11440                    } else {
11441                        Log.i(TAG, "Deleting stale container for " + cid);
11442                        removeCids.add(cid);
11443                    }
11444                }
11445            }
11446
11447            if (num > 0) {
11448                // Sort uid list
11449                Arrays.sort(uidList, 0, num);
11450                // Throw away duplicates
11451                uidArr = new int[num];
11452                uidArr[0] = uidList[0];
11453                int di = 0;
11454                for (int i = 1; i < num; i++) {
11455                    if (uidList[i - 1] != uidList[i]) {
11456                        uidArr[di++] = uidList[i];
11457                    }
11458                }
11459            }
11460        }
11461        // Process packages with valid entries.
11462        if (isMounted) {
11463            if (DEBUG_SD_INSTALL)
11464                Log.i(TAG, "Loading packages");
11465            loadMediaPackages(processCids, uidArr, removeCids);
11466            startCleaningPackages();
11467        } else {
11468            if (DEBUG_SD_INSTALL)
11469                Log.i(TAG, "Unloading packages");
11470            unloadMediaPackages(processCids, uidArr, reportStatus);
11471        }
11472    }
11473
11474   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
11475           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
11476        int size = pkgList.size();
11477        if (size > 0) {
11478            // Send broadcasts here
11479            Bundle extras = new Bundle();
11480            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
11481                    .toArray(new String[size]));
11482            if (uidArr != null) {
11483                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
11484            }
11485            if (replacing) {
11486                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
11487            }
11488            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
11489                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
11490            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
11491        }
11492    }
11493
11494   /*
11495     * Look at potentially valid container ids from processCids If package
11496     * information doesn't match the one on record or package scanning fails,
11497     * the cid is added to list of removeCids. We currently don't delete stale
11498     * containers.
11499     */
11500   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
11501            HashSet<String> removeCids) {
11502        ArrayList<String> pkgList = new ArrayList<String>();
11503        Set<AsecInstallArgs> keys = processCids.keySet();
11504        boolean doGc = false;
11505        for (AsecInstallArgs args : keys) {
11506            String codePath = processCids.get(args);
11507            if (DEBUG_SD_INSTALL)
11508                Log.i(TAG, "Loading container : " + args.cid);
11509            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11510            try {
11511                // Make sure there are no container errors first.
11512                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
11513                    Slog.e(TAG, "Failed to mount cid : " + args.cid
11514                            + " when installing from sdcard");
11515                    continue;
11516                }
11517                // Check code path here.
11518                if (codePath == null || !codePath.equals(args.getCodePath())) {
11519                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
11520                            + " does not match one in settings " + codePath);
11521                    continue;
11522                }
11523                // Parse package
11524                int parseFlags = mDefParseFlags;
11525                if (args.isExternal()) {
11526                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
11527                }
11528                if (args.isFwdLocked()) {
11529                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
11530                }
11531
11532                doGc = true;
11533                synchronized (mInstallLock) {
11534                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
11535                            0, 0, null);
11536                    // Scan the package
11537                    if (pkg != null) {
11538                        /*
11539                         * TODO why is the lock being held? doPostInstall is
11540                         * called in other places without the lock. This needs
11541                         * to be straightened out.
11542                         */
11543                        // writer
11544                        synchronized (mPackages) {
11545                            retCode = PackageManager.INSTALL_SUCCEEDED;
11546                            pkgList.add(pkg.packageName);
11547                            // Post process args
11548                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
11549                                    pkg.applicationInfo.uid);
11550                        }
11551                    } else {
11552                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
11553                    }
11554                }
11555
11556            } finally {
11557                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
11558                    // Don't destroy container here. Wait till gc clears things
11559                    // up.
11560                    removeCids.add(args.cid);
11561                }
11562            }
11563        }
11564        // writer
11565        synchronized (mPackages) {
11566            // If the platform SDK has changed since the last time we booted,
11567            // we need to re-grant app permission to catch any new ones that
11568            // appear. This is really a hack, and means that apps can in some
11569            // cases get permissions that the user didn't initially explicitly
11570            // allow... it would be nice to have some better way to handle
11571            // this situation.
11572            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
11573            if (regrantPermissions)
11574                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
11575                        + mSdkVersion + "; regranting permissions for external storage");
11576            mSettings.mExternalSdkPlatform = mSdkVersion;
11577
11578            // Make sure group IDs have been assigned, and any permission
11579            // changes in other apps are accounted for
11580            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
11581                    | (regrantPermissions
11582                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
11583                            : 0));
11584            // can downgrade to reader
11585            // Persist settings
11586            mSettings.writeLPr();
11587        }
11588        // Send a broadcast to let everyone know we are done processing
11589        if (pkgList.size() > 0) {
11590            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
11591        }
11592        // Force gc to avoid any stale parser references that we might have.
11593        if (doGc) {
11594            Runtime.getRuntime().gc();
11595        }
11596        // List stale containers and destroy stale temporary containers.
11597        if (removeCids != null) {
11598            for (String cid : removeCids) {
11599                if (cid.startsWith(mTempContainerPrefix)) {
11600                    Log.i(TAG, "Destroying stale temporary container " + cid);
11601                    PackageHelper.destroySdDir(cid);
11602                } else {
11603                    Log.w(TAG, "Container " + cid + " is stale");
11604               }
11605           }
11606        }
11607    }
11608
11609   /*
11610     * Utility method to unload a list of specified containers
11611     */
11612    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
11613        // Just unmount all valid containers.
11614        for (AsecInstallArgs arg : cidArgs) {
11615            synchronized (mInstallLock) {
11616                arg.doPostDeleteLI(false);
11617           }
11618       }
11619   }
11620
11621    /*
11622     * Unload packages mounted on external media. This involves deleting package
11623     * data from internal structures, sending broadcasts about diabled packages,
11624     * gc'ing to free up references, unmounting all secure containers
11625     * corresponding to packages on external media, and posting a
11626     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
11627     * that we always have to post this message if status has been requested no
11628     * matter what.
11629     */
11630    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
11631            final boolean reportStatus) {
11632        if (DEBUG_SD_INSTALL)
11633            Log.i(TAG, "unloading media packages");
11634        ArrayList<String> pkgList = new ArrayList<String>();
11635        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
11636        final Set<AsecInstallArgs> keys = processCids.keySet();
11637        for (AsecInstallArgs args : keys) {
11638            String pkgName = args.getPackageName();
11639            if (DEBUG_SD_INSTALL)
11640                Log.i(TAG, "Trying to unload pkg : " + pkgName);
11641            // Delete package internally
11642            PackageRemovedInfo outInfo = new PackageRemovedInfo();
11643            synchronized (mInstallLock) {
11644                boolean res = deletePackageLI(pkgName, null, false, null, null,
11645                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
11646                if (res) {
11647                    pkgList.add(pkgName);
11648                } else {
11649                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
11650                    failedList.add(args);
11651                }
11652            }
11653        }
11654
11655        // reader
11656        synchronized (mPackages) {
11657            // We didn't update the settings after removing each package;
11658            // write them now for all packages.
11659            mSettings.writeLPr();
11660        }
11661
11662        // We have to absolutely send UPDATED_MEDIA_STATUS only
11663        // after confirming that all the receivers processed the ordered
11664        // broadcast when packages get disabled, force a gc to clean things up.
11665        // and unload all the containers.
11666        if (pkgList.size() > 0) {
11667            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
11668                    new IIntentReceiver.Stub() {
11669                public void performReceive(Intent intent, int resultCode, String data,
11670                        Bundle extras, boolean ordered, boolean sticky,
11671                        int sendingUser) throws RemoteException {
11672                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
11673                            reportStatus ? 1 : 0, 1, keys);
11674                    mHandler.sendMessage(msg);
11675                }
11676            });
11677        } else {
11678            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
11679                    keys);
11680            mHandler.sendMessage(msg);
11681        }
11682    }
11683
11684    /** Binder call */
11685    @Override
11686    public void movePackage(final String packageName, final IPackageMoveObserver observer,
11687            final int flags) {
11688        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
11689        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
11690        int returnCode = PackageManager.MOVE_SUCCEEDED;
11691        int currFlags = 0;
11692        int newFlags = 0;
11693        // reader
11694        synchronized (mPackages) {
11695            PackageParser.Package pkg = mPackages.get(packageName);
11696            if (pkg == null) {
11697                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
11698            } else {
11699                // Disable moving fwd locked apps and system packages
11700                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
11701                    Slog.w(TAG, "Cannot move system application");
11702                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
11703                } else if (pkg.mOperationPending) {
11704                    Slog.w(TAG, "Attempt to move package which has pending operations");
11705                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
11706                } else {
11707                    // Find install location first
11708                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
11709                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
11710                        Slog.w(TAG, "Ambigous flags specified for move location.");
11711                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
11712                    } else {
11713                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
11714                                : PackageManager.INSTALL_INTERNAL;
11715                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
11716                                : PackageManager.INSTALL_INTERNAL;
11717
11718                        if (newFlags == currFlags) {
11719                            Slog.w(TAG, "No move required. Trying to move to same location");
11720                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
11721                        } else {
11722                            if (isForwardLocked(pkg)) {
11723                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11724                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11725                            }
11726                        }
11727                    }
11728                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
11729                        pkg.mOperationPending = true;
11730                    }
11731                }
11732            }
11733
11734            /*
11735             * TODO this next block probably shouldn't be inside the lock. We
11736             * can't guarantee these won't change after this is fired off
11737             * anyway.
11738             */
11739            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
11740                processPendingMove(new MoveParams(null, observer, 0, packageName, null,
11741                        null, -1, user),
11742                        returnCode);
11743            } else {
11744                Message msg = mHandler.obtainMessage(INIT_COPY);
11745                final String instructionSet = getAppInstructionSet(pkg.applicationInfo);
11746                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
11747                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir,
11748                        instructionSet);
11749                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
11750                        pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user);
11751                msg.obj = mp;
11752                mHandler.sendMessage(msg);
11753            }
11754        }
11755    }
11756
11757    private void processPendingMove(final MoveParams mp, final int currentStatus) {
11758        // Queue up an async operation since the package deletion may take a
11759        // little while.
11760        mHandler.post(new Runnable() {
11761            public void run() {
11762                // TODO fix this; this does nothing.
11763                mHandler.removeCallbacks(this);
11764                int returnCode = currentStatus;
11765                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
11766                    int uidArr[] = null;
11767                    ArrayList<String> pkgList = null;
11768                    synchronized (mPackages) {
11769                        PackageParser.Package pkg = mPackages.get(mp.packageName);
11770                        if (pkg == null) {
11771                            Slog.w(TAG, " Package " + mp.packageName
11772                                    + " doesn't exist. Aborting move");
11773                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
11774                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
11775                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
11776                                    + mp.srcArgs.getCodePath() + " to "
11777                                    + pkg.applicationInfo.sourceDir
11778                                    + " Aborting move and returning error");
11779                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
11780                        } else {
11781                            uidArr = new int[] {
11782                                pkg.applicationInfo.uid
11783                            };
11784                            pkgList = new ArrayList<String>();
11785                            pkgList.add(mp.packageName);
11786                        }
11787                    }
11788                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
11789                        // Send resources unavailable broadcast
11790                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
11791                        // Update package code and resource paths
11792                        synchronized (mInstallLock) {
11793                            synchronized (mPackages) {
11794                                PackageParser.Package pkg = mPackages.get(mp.packageName);
11795                                // Recheck for package again.
11796                                if (pkg == null) {
11797                                    Slog.w(TAG, " Package " + mp.packageName
11798                                            + " doesn't exist. Aborting move");
11799                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
11800                                } else if (!mp.srcArgs.getCodePath().equals(
11801                                        pkg.applicationInfo.sourceDir)) {
11802                                    Slog.w(TAG, "Package " + mp.packageName
11803                                            + " code path changed from " + mp.srcArgs.getCodePath()
11804                                            + " to " + pkg.applicationInfo.sourceDir
11805                                            + " Aborting move and returning error");
11806                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
11807                                } else {
11808                                    final String oldCodePath = pkg.mPath;
11809                                    final String newCodePath = mp.targetArgs.getCodePath();
11810                                    final String newResPath = mp.targetArgs.getResourcePath();
11811                                    final String newNativePath = mp.targetArgs
11812                                            .getNativeLibraryPath();
11813
11814                                    final File newNativeDir = new File(newNativePath);
11815
11816                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
11817                                        // NOTE: We do not report any errors from the APK scan and library
11818                                        // copy at this point.
11819                                        NativeLibraryHelper.ApkHandle handle =
11820                                                new NativeLibraryHelper.ApkHandle(newCodePath);
11821                                        final int abi = NativeLibraryHelper.findSupportedAbi(
11822                                                handle, Build.SUPPORTED_ABIS);
11823                                        if (abi >= 0) {
11824                                            NativeLibraryHelper.copyNativeBinariesIfNeededLI(
11825                                                    handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
11826                                        }
11827                                        handle.close();
11828                                    }
11829                                    final int[] users = sUserManager.getUserIds();
11830                                    for (int user : users) {
11831                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
11832                                                newNativePath, user) < 0) {
11833                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
11834                                        }
11835                                    }
11836
11837                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
11838                                        pkg.mPath = newCodePath;
11839                                        // Move dex files around
11840                                        if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
11841                                            // Moving of dex files failed. Set
11842                                            // error code and abort move.
11843                                            pkg.mPath = pkg.mScanPath;
11844                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
11845                                        }
11846                                    }
11847
11848                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
11849                                        pkg.mScanPath = newCodePath;
11850                                        pkg.applicationInfo.sourceDir = newCodePath;
11851                                        pkg.applicationInfo.publicSourceDir = newResPath;
11852                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
11853                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
11854                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
11855                                        ps.codePathString = ps.codePath.getPath();
11856                                        ps.resourcePath = new File(
11857                                                pkg.applicationInfo.publicSourceDir);
11858                                        ps.resourcePathString = ps.resourcePath.getPath();
11859                                        ps.nativeLibraryPathString = newNativePath;
11860                                        // Set the application info flag
11861                                        // correctly.
11862                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
11863                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
11864                                        } else {
11865                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
11866                                        }
11867                                        ps.setFlags(pkg.applicationInfo.flags);
11868                                        mAppDirs.remove(oldCodePath);
11869                                        mAppDirs.put(newCodePath, pkg);
11870                                        // Persist settings
11871                                        mSettings.writeLPr();
11872                                    }
11873                                }
11874                            }
11875                        }
11876                        // Send resources available broadcast
11877                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
11878                    }
11879                }
11880                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
11881                    // Clean up failed installation
11882                    if (mp.targetArgs != null) {
11883                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
11884                                -1);
11885                    }
11886                } else {
11887                    // Force a gc to clear things up.
11888                    Runtime.getRuntime().gc();
11889                    // Delete older code
11890                    synchronized (mInstallLock) {
11891                        mp.srcArgs.doPostDeleteLI(true);
11892                    }
11893                }
11894
11895                // Allow more operations on this file if we didn't fail because
11896                // an operation was already pending for this package.
11897                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
11898                    synchronized (mPackages) {
11899                        PackageParser.Package pkg = mPackages.get(mp.packageName);
11900                        if (pkg != null) {
11901                            pkg.mOperationPending = false;
11902                       }
11903                   }
11904                }
11905
11906                IPackageMoveObserver observer = mp.observer;
11907                if (observer != null) {
11908                    try {
11909                        observer.packageMoved(mp.packageName, returnCode);
11910                    } catch (RemoteException e) {
11911                        Log.i(TAG, "Observer no longer exists.");
11912                    }
11913                }
11914            }
11915        });
11916    }
11917
11918    public boolean setInstallLocation(int loc) {
11919        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
11920                null);
11921        if (getInstallLocation() == loc) {
11922            return true;
11923        }
11924        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
11925                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
11926            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
11927                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
11928            return true;
11929        }
11930        return false;
11931   }
11932
11933    public int getInstallLocation() {
11934        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11935                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
11936                PackageHelper.APP_INSTALL_AUTO);
11937    }
11938
11939    /** Called by UserManagerService */
11940    void cleanUpUserLILPw(int userHandle) {
11941        mDirtyUsers.remove(userHandle);
11942        mSettings.removeUserLPr(userHandle);
11943        mPendingBroadcasts.remove(userHandle);
11944        if (mInstaller != null) {
11945            // Technically, we shouldn't be doing this with the package lock
11946            // held.  However, this is very rare, and there is already so much
11947            // other disk I/O going on, that we'll let it slide for now.
11948            mInstaller.removeUserDataDirs(userHandle);
11949        }
11950    }
11951
11952    /** Called by UserManagerService */
11953    void createNewUserLILPw(int userHandle, File path) {
11954        if (mInstaller != null) {
11955            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
11956        }
11957    }
11958
11959    @Override
11960    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
11961        mContext.enforceCallingOrSelfPermission(
11962                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11963                "Only package verification agents can read the verifier device identity");
11964
11965        synchronized (mPackages) {
11966            return mSettings.getVerifierDeviceIdentityLPw();
11967        }
11968    }
11969
11970    @Override
11971    public void setPermissionEnforced(String permission, boolean enforced) {
11972        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
11973        if (READ_EXTERNAL_STORAGE.equals(permission)) {
11974            synchronized (mPackages) {
11975                if (mSettings.mReadExternalStorageEnforced == null
11976                        || mSettings.mReadExternalStorageEnforced != enforced) {
11977                    mSettings.mReadExternalStorageEnforced = enforced;
11978                    mSettings.writeLPr();
11979                }
11980            }
11981            // kill any non-foreground processes so we restart them and
11982            // grant/revoke the GID.
11983            final IActivityManager am = ActivityManagerNative.getDefault();
11984            if (am != null) {
11985                final long token = Binder.clearCallingIdentity();
11986                try {
11987                    am.killProcessesBelowForeground("setPermissionEnforcement");
11988                } catch (RemoteException e) {
11989                } finally {
11990                    Binder.restoreCallingIdentity(token);
11991                }
11992            }
11993        } else {
11994            throw new IllegalArgumentException("No selective enforcement for " + permission);
11995        }
11996    }
11997
11998    @Override
11999    @Deprecated
12000    public boolean isPermissionEnforced(String permission) {
12001        return true;
12002    }
12003
12004    @Override
12005    public boolean isStorageLow() {
12006        final long token = Binder.clearCallingIdentity();
12007        try {
12008            final DeviceStorageMonitorInternal
12009                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12010            if (dsm != null) {
12011                return dsm.isMemoryLow();
12012            } else {
12013                return false;
12014            }
12015        } finally {
12016            Binder.restoreCallingIdentity(token);
12017        }
12018    }
12019}
12020