blob: eadf19602f00c1cd76dd43cffb26e5c3374f6eb3 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
Kenny Rootcf0b38c2011-03-22 14:17:59 -070017package com.android.server.pm;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080018
Jeff Sharkey854b2b12012-04-13 16:03:40 -070019import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
Kenny Root27989422011-02-23 16:28:26 -080021import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
Dianne Hackbornfd7aded2013-01-22 17:10:23 -080023import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
Dianne Hackborn0ac30312011-06-17 14:49:23 -070024import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
Kenny Root27989422011-02-23 16:28:26 -080025import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
Jeff Sharkey854b2b12012-04-13 16:03:40 -070026import static com.android.internal.util.ArrayUtils.appendInt;
27import static com.android.internal.util.ArrayUtils.removeInt;
Nick Kralevich15069212013-01-09 15:54:56 -080028import static libcore.io.OsConstants.S_ISLNK;
Kenny Rootddbe50d2012-09-06 13:18:37 -070029import static libcore.io.OsConstants.S_IRWXU;
30import static libcore.io.OsConstants.S_IRGRP;
31import static libcore.io.OsConstants.S_IXGRP;
32import static libcore.io.OsConstants.S_IROTH;
33import static libcore.io.OsConstants.S_IXOTH;
Kenny Root27989422011-02-23 16:28:26 -080034
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080035import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import com.android.internal.app.ResolverActivity;
Kenny Root85387d72010-08-26 10:13:11 -070037import com.android.internal.content.NativeLibraryHelper;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080038import com.android.internal.content.PackageHelper;
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -070039import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080040import com.android.internal.util.XmlUtils;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070041import com.android.server.DeviceStorageMonitorService;
42import com.android.server.EventLogTags;
43import com.android.server.IntentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044
Jason parksa3cdaa52011-01-13 14:15:43 -060045import org.xmlpull.v1.XmlPullParser;
46import org.xmlpull.v1.XmlPullParserException;
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -070047import org.xmlpull.v1.XmlSerializer;
Jason parksa3cdaa52011-01-13 14:15:43 -060048
rich canningsa2064df2012-09-30 14:52:41 -070049import android.app.ActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.app.ActivityManagerNative;
51import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080052import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080053import android.app.backup.IBackupManager;
Kenny Root5ab21572011-07-27 11:11:19 -070054import android.content.BroadcastReceiver;
Jason parksa3cdaa52011-01-13 14:15:43 -060055import android.content.ComponentName;
Kenny Root27989422011-02-23 16:28:26 -080056import android.content.Context;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070057import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.content.Intent;
59import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070060import android.content.IntentSender;
Jason parks1125d782011-01-12 09:47:26 -060061import android.content.ServiceConnection;
Jason parksa3cdaa52011-01-13 14:15:43 -060062import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.content.pm.ActivityInfo;
64import android.content.pm.ApplicationInfo;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -070065import android.content.pm.ContainerEncryptionParams;
Dianne Hackborn49237342009-08-27 20:08:01 -070066import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.content.pm.IPackageDataObserver;
68import android.content.pm.IPackageDeleteObserver;
69import android.content.pm.IPackageInstallObserver;
70import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080071import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.content.pm.IPackageStatsObserver;
73import android.content.pm.InstrumentationInfo;
Dianne Hackborn7767eac2012-08-23 18:25:40 -070074import android.content.pm.PackageCleanItem;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080076import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.content.pm.PackageManager;
Jason parksa3cdaa52011-01-13 14:15:43 -060078import android.content.pm.PackageParser;
Dianne Hackborn7767eac2012-08-23 18:25:40 -070079import android.content.pm.PackageUserState;
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -070080import android.content.pm.PackageParser.ActivityIntentInfo;
Kenny Root27989422011-02-23 16:28:26 -080081import android.content.pm.PackageStats;
Kenny Root0e2c0f32011-04-15 17:50:10 -070082import android.content.pm.ParceledListSlice;
Jason parksa3cdaa52011-01-13 14:15:43 -060083import android.content.pm.PermissionGroupInfo;
Kenny Root27989422011-02-23 16:28:26 -080084import android.content.pm.PermissionInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.content.pm.ProviderInfo;
86import android.content.pm.ResolveInfo;
87import android.content.pm.ServiceInfo;
88import android.content.pm.Signature;
Kenny Root5ab21572011-07-27 11:11:19 -070089import android.content.pm.ManifestDigest;
rich cannings706e8ba2012-08-20 13:20:14 -070090import android.content.pm.VerificationParams;
Kenny Root0aaa0d92011-09-12 16:42:55 -070091import android.content.pm.VerifierDeviceIdentity;
Kenny Root05ca4c92011-09-15 10:36:25 -070092import android.content.pm.VerifierInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import android.net.Uri;
94import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070095import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import android.os.Bundle;
Kenny Root27989422011-02-23 16:28:26 -080097import android.os.Environment;
98import android.os.FileObserver;
99import android.os.FileUtils;
100import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800102import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700103import android.os.Looper;
104import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import android.os.Parcel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import android.os.ParcelFileDescriptor;
107import android.os.Process;
Kenny Root27989422011-02-23 16:28:26 -0800108import android.os.RemoteException;
rpcraig554cb0c2012-07-05 06:41:43 -0400109import android.os.SELinux;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.os.ServiceManager;
111import android.os.SystemClock;
112import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700113import android.os.UserHandle;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700114import android.os.Environment.UserEnvironment;
Nick Kralevich15069212013-01-09 15:54:56 -0800115import android.provider.Settings.Secure;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800116import android.security.SystemKeyStore;
Kenny Root27989422011-02-23 16:28:26 -0800117import android.util.DisplayMetrics;
118import android.util.EventLog;
119import android.util.Log;
120import android.util.LogPrinter;
121import android.util.Slog;
122import android.util.SparseArray;
123import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import android.view.Display;
125import android.view.WindowManager;
126
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -0700127import java.io.BufferedOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128import java.io.File;
129import java.io.FileDescriptor;
130import java.io.FileInputStream;
131import java.io.FileNotFoundException;
132import java.io.FileOutputStream;
133import java.io.FileReader;
134import java.io.FilenameFilter;
135import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800137import java.security.NoSuchAlgorithmException;
Kenny Root05ca4c92011-09-15 10:36:25 -0700138import java.security.PublicKey;
139import java.security.cert.CertificateException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800140import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import java.util.ArrayList;
142import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700143import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144import java.util.Collections;
145import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800146import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147import java.util.HashMap;
148import java.util.HashSet;
149import java.util.Iterator;
150import java.util.List;
151import java.util.Map;
Nick Kralevich15069212013-01-09 15:54:56 -0800152import java.util.Map.Entry;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154
Kenny Root66269ea2011-07-12 14:14:01 -0700155import libcore.io.ErrnoException;
Kenny Root3f99afc2012-04-14 10:13:10 -0700156import libcore.io.IoUtils;
Kenny Root66269ea2011-07-12 14:14:01 -0700157import libcore.io.Libcore;
Nick Kralevich15069212013-01-09 15:54:56 -0800158import libcore.io.OsConstants;
Kenny Root786cbca2012-08-16 11:10:58 -0700159import libcore.io.StructStat;
Kenny Root66269ea2011-07-12 14:14:01 -0700160
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700161/**
162 * Keep track of all those .apks everywhere.
163 *
164 * This is very central to the platform's security; please run the unit
165 * tests whenever making modifications here:
166 *
167mmm frameworks/base/tests/AndroidTests
168adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
169adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700170 *
171 * {@hide}
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700172 */
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700173public class PackageManagerService extends IPackageManager.Stub {
174 static final String TAG = "PackageManager";
175 static final boolean DEBUG_SETTINGS = false;
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -0800176 static final boolean DEBUG_PREFERRED = true;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700177 static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800178 private static final boolean DEBUG_INSTALL = false;
Kenny Root9718cf52011-02-23 16:45:26 -0800179 private static final boolean DEBUG_REMOVE = false;
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700180 private static final boolean DEBUG_BROADCASTS = false;
Kenny Root9718cf52011-02-23 16:45:26 -0800181 private static final boolean DEBUG_SHOW_INFO = false;
182 private static final boolean DEBUG_PACKAGE_INFO = false;
183 private static final boolean DEBUG_INTENT_MATCHING = false;
184 private static final boolean DEBUG_PACKAGE_SCANNING = false;
185 private static final boolean DEBUG_APP_DIR_OBSERVER = false;
Kenny Root05ca4c92011-09-15 10:36:25 -0700186 private static final boolean DEBUG_VERIFY = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400189 private static final int LOG_UID = Process.LOG_UID;
Nick Pellycd0e8392010-10-13 17:25:24 -0700190 private static final int NFC_UID = Process.NFC_UID;
Jaikumar Ganesh1abb1cb2012-01-25 16:14:50 -0800191 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 private static final boolean GET_CERTIFICATES = true;
194
195 private static final int REMOVE_EVENTS =
196 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
197 private static final int ADD_EVENTS =
198 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
199
200 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800201 // Suffix used during package installation when copying/moving
202 // package apks to install directory.
203 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
205 static final int SCAN_MONITOR = 1<<0;
206 static final int SCAN_NO_DEX = 1<<1;
207 static final int SCAN_FORCE_DEX = 1<<2;
208 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800209 static final int SCAN_NEW_INSTALL = 1<<4;
210 static final int SCAN_NO_PATHS = 1<<5;
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700211 static final int SCAN_UPDATE_TIME = 1<<6;
Dianne Hackborn661cd522011-08-22 00:26:20 -0700212 static final int SCAN_DEFER_DEX = 1<<7;
Dianne Hackbornd0c5f512012-06-07 16:53:59 -0700213 static final int SCAN_BOOTING = 1<<8;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700215 static final int REMOVE_CHATTY = 1<<16;
Kenny Root11128572010-10-11 10:51:32 -0700216
Kenny Root5ab21572011-07-27 11:11:19 -0700217 /**
218 * Whether verification is enabled by default.
219 */
rich cannings36c67c22012-09-16 16:20:23 -0700220 private static final boolean DEFAULT_VERIFY_ENABLE = true;
Kenny Root5ab21572011-07-27 11:11:19 -0700221
222 /**
223 * The default maximum time to wait for the verification agent to return in
224 * milliseconds.
225 */
rich canningsaa8513e2012-05-21 16:15:23 -0700226 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
Kenny Root5ab21572011-07-27 11:11:19 -0700227
rich canningsa6cfe522012-05-21 15:50:56 -0700228 /**
229 * The default response for package verification timeout.
230 *
231 * This can be either PackageManager.VERIFICATION_ALLOW or
232 * PackageManager.VERIFICATION_REJECT.
233 */
234 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
235
Kenny Root11128572010-10-11 10:51:32 -0700236 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
237
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800238 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
Kenny Root11128572010-10-11 10:51:32 -0700239 DEFAULT_CONTAINER_PACKAGE,
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800240 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700241
Kenny Root05ca4c92011-09-15 10:36:25 -0700242 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
243
Kenny Root85387d72010-08-26 10:13:11 -0700244 private static final String LIB_DIR_NAME = "lib";
245
Kenny Rootc78a8072010-07-27 15:18:38 -0700246 static final String mTempContainerPrefix = "smdl2tmp";
247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
249 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700250 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251
Dianne Hackborn851a5412009-05-08 12:06:44 -0700252 final int mSdkVersion = Build.VERSION.SDK_INT;
253 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
254 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 final Context mContext;
257 final boolean mFactoryTest;
Dianne Hackbornd2509fd2011-09-12 12:29:43 -0700258 final boolean mOnlyCore;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700259 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 final DisplayMetrics mMetrics;
261 final int mDefParseFlags;
262 final String[] mSeparateProcesses;
263
264 // This is where all application persistent data goes.
265 final File mAppDataDir;
266
Amith Yamasani0b285492011-04-14 17:35:23 -0700267 // This is where all application persistent data goes for secondary users.
268 final File mUserAppDataDir;
269
Kenny Root51a573c2012-05-17 13:30:28 -0700270 /** The location for ASEC container files on internal storage. */
271 final String mAsecInternalPath;
272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 // This is the object monitoring the framework dir.
274 final FileObserver mFrameworkInstallObserver;
275
276 // This is the object monitoring the system app dir.
277 final FileObserver mSystemInstallObserver;
278
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700279 // This is the object monitoring the system app dir.
280 final FileObserver mVendorInstallObserver;
281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 // This is the object monitoring mAppInstallDir.
283 final FileObserver mAppInstallObserver;
284
285 // This is the object monitoring mDrmAppPrivateInstallDir.
286 final FileObserver mDrmAppInstallObserver;
287
Kenny Rootddbe50d2012-09-06 13:18:37 -0700288 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 // LOCK HELD. Can be called with mInstallLock held.
290 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 final File mFrameworkDir;
293 final File mSystemAppDir;
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700294 final File mVendorAppDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700296 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297
Kenny Rootddbe50d2012-09-06 13:18:37 -0700298 /**
299 * Directory to which applications installed internally have native
300 * libraries copied.
301 */
302 private File mAppLibInstallDir;
303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
305 // apps.
306 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 // Lock for state used when installing and doing other long running
311 // operations. Methods that must be called with this lock held have
312 // the prefix "LI".
313 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 // These are the directories in the 3rd party applications installed dir
316 // that we have currently loaded packages from. Keys are the application's
317 // installed zip file (absolute codePath), and values are Package.
318 final HashMap<String, PackageParser.Package> mAppDirs =
319 new HashMap<String, PackageParser.Package>();
320
321 // Information for the parser to write more useful error messages.
322 File mScanningPath;
323 int mLastScanError;
324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 // Keys are String (package name), values are Package. This also serves
328 // as the lock for the global state. Methods that must be called with
329 // this lock held have the prefix "LP".
330 final HashMap<String, PackageParser.Package> mPackages =
331 new HashMap<String, PackageParser.Package>();
332
333 final Settings mSettings;
334 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335
336 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
337 int[] mGlobalGids;
338
339 // These are the built-in uid -> permission mappings that were read from the
340 // etc/permissions.xml file.
341 final SparseArray<HashSet<String>> mSystemPermissions =
342 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 // These are the built-in shared libraries that were read from the
345 // etc/permissions.xml file.
346 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800347
Dianne Hackborn49237342009-08-27 20:08:01 -0700348 // Temporary for building the final shared libraries for an .apk.
349 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800350
Dianne Hackborn49237342009-08-27 20:08:01 -0700351 // These are the features this devices supports that were read from the
352 // etc/permissions.xml file.
353 final HashMap<String, FeatureInfo> mAvailableFeatures =
354 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 // All available activities, for your resolving pleasure.
357 final ActivityIntentResolver mActivities =
358 new ActivityIntentResolver();
359
360 // All available receivers, for your resolving pleasure.
361 final ActivityIntentResolver mReceivers =
362 new ActivityIntentResolver();
363
364 // All available services, for your resolving pleasure.
365 final ServiceIntentResolver mServices = new ServiceIntentResolver();
366
367 // Keys are String (provider class name), values are Provider.
368 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
369 new HashMap<ComponentName, PackageParser.Provider>();
370
371 // Mapping from provider base names (first directory in content URI codePath)
372 // to the provider information.
373 final HashMap<String, PackageParser.Provider> mProviders =
374 new HashMap<String, PackageParser.Provider>();
375
376 // Mapping from instrumentation class names to info about them.
377 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
378 new HashMap<ComponentName, PackageParser.Instrumentation>();
379
380 // Mapping from permission names to info about them.
381 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
382 new HashMap<String, PackageParser.PermissionGroup>();
383
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800384 // Packages whose data we have transfered into another package, thus
385 // should no longer exist.
386 final HashSet<String> mTransferedPackages = new HashSet<String>();
387
Dianne Hackborn854060af2009-07-09 18:14:31 -0700388 // Broadcast actions that are only available to the system.
389 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800390
Kenny Root5ab21572011-07-27 11:11:19 -0700391 /** List of packages waiting for verification. */
Kenny Root05ca4c92011-09-15 10:36:25 -0700392 final SparseArray<PackageVerificationState> mPendingVerification
393 = new SparseArray<PackageVerificationState>();
Kenny Root5ab21572011-07-27 11:11:19 -0700394
Dianne Hackborn661cd522011-08-22 00:26:20 -0700395 final ArrayList<PackageParser.Package> mDeferredDexOpt =
396 new ArrayList<PackageParser.Package>();
397
Kenny Root5ab21572011-07-27 11:11:19 -0700398 /** Token for keys in mPendingVerification. */
399 private int mPendingVerificationToken = 0;
400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 boolean mSystemReady;
402 boolean mSafeMode;
403 boolean mHasSystemUidErrors;
404
405 ApplicationInfo mAndroidApplication;
406 final ActivityInfo mResolveActivity = new ActivityInfo();
407 final ResolveInfo mResolveInfo = new ResolveInfo();
408 ComponentName mResolveComponentName;
409 PackageParser.Package mPlatformPackage;
410
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700411 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800412 final HashMap<String, ArrayList<String>> mPendingBroadcasts
413 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800414 // Service Connection to remote media container service to copy
415 // package uri's from external media onto secure containers
416 // or internal storage.
417 private IMediaContainerService mContainerService = null;
418
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700419 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800420 static final int MCS_BOUND = 3;
421 static final int END_COPY = 4;
422 static final int INIT_COPY = 5;
423 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800424 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800425 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800426 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800427 static final int MCS_RECONNECT = 10;
428 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700429 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700430 static final int WRITE_SETTINGS = 13;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700431 static final int WRITE_PACKAGE_RESTRICTIONS = 14;
Kenny Root5ab21572011-07-27 11:11:19 -0700432 static final int PACKAGE_VERIFIED = 15;
433 static final int CHECK_PENDING_VERIFICATION = 16;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700434
435 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800436
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700437 // Delay time in millisecs
438 static final int BROADCAST_DELAY = 10 * 1000;
Kenny Root9718cf52011-02-23 16:45:26 -0800439
Amith Yamasani258848d2012-08-10 17:06:33 -0700440 static UserManagerService sUserManager;
Amith Yamasani0b285492011-04-14 17:35:23 -0700441
Amith Yamasani483f3b02012-03-13 16:08:00 -0700442 // Stores a list of users whose package restrictions file needs to be updated
443 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
444
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800445 final private DefaultContainerConnection mDefContainerConn =
446 new DefaultContainerConnection();
447 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800448 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800449 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800450 IMediaContainerService imcs =
451 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800452 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800453 }
454
455 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800456 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800457 }
458 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700459
Christopher Tate1bb69062010-02-19 17:02:12 -0800460 // Recordkeeping of restore-after-install operations that are currently in flight
461 // between the Package Manager and the Backup Manager
462 class PostInstallData {
463 public InstallArgs args;
464 public PackageInstalledInfo res;
465
466 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
467 args = _a;
468 res = _r;
469 }
470 };
471 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
472 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
473
Kenny Root05ca4c92011-09-15 10:36:25 -0700474 private final String mRequiredVerifierPackage;
475
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700476 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800477 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800478 final ArrayList<HandlerParams> mPendingInstalls =
479 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800480
481 private boolean connectToService() {
482 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
483 " DefaultContainerService");
484 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700485 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Amith Yamasani27b89e62013-01-16 12:30:11 -0800486 if (mContext.bindServiceAsUser(service, mDefContainerConn,
487 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700488 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800489 mBound = true;
490 return true;
491 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700492 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800493 return false;
494 }
495
496 private void disconnectService() {
497 mContainerService = null;
498 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700499 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800500 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700501 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800502 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800503
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700504 PackageHandler(Looper looper) {
505 super(looper);
506 }
Dianne Hackborn7d608422011-08-07 16:24:18 -0700507
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700508 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700509 try {
510 doHandleMessage(msg);
511 } finally {
512 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
513 }
514 }
515
516 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700517 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800518 case INIT_COPY: {
Kenny Root5ab21572011-07-27 11:11:19 -0700519 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800520 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800521 int idx = mPendingInstalls.size();
Kenny Root5ab21572011-07-27 11:11:19 -0700522 if (DEBUG_INSTALL) Slog.i(TAG, "idx=" + idx);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800523 // If a bind was already initiated we dont really
524 // need to do anything. The pending install
525 // will be processed later on.
526 if (!mBound) {
527 // If this is the only one pending we might
528 // have to bind to the service again.
529 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800530 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800531 params.serviceError();
532 return;
533 } else {
534 // Once we bind to the service, the first
535 // pending request will be processed.
536 mPendingInstalls.add(idx, params);
537 }
538 } else {
539 mPendingInstalls.add(idx, params);
540 // Already bound to the service. Just make
541 // sure we trigger off processing the first request.
542 if (idx == 0) {
543 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800544 }
545 }
546 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800547 }
548 case MCS_BOUND: {
Kenny Root5ab21572011-07-27 11:11:19 -0700549 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800550 if (msg.obj != null) {
551 mContainerService = (IMediaContainerService) msg.obj;
552 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800553 if (mContainerService == null) {
554 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800555 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800556 for (HandlerParams params : mPendingInstalls) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800557 // Indicate service bind error
558 params.serviceError();
559 }
560 mPendingInstalls.clear();
561 } else if (mPendingInstalls.size() > 0) {
562 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800563 if (params != null) {
Dianne Hackborn7d608422011-08-07 16:24:18 -0700564 if (params.startCopy()) {
565 // We are done... look for more work or to
566 // go idle.
567 if (DEBUG_SD_INSTALL) Log.i(TAG,
568 "Checking for more work or unbind...");
569 // Delete pending install
570 if (mPendingInstalls.size() > 0) {
571 mPendingInstalls.remove(0);
572 }
573 if (mPendingInstalls.size() == 0) {
574 if (mBound) {
575 if (DEBUG_SD_INSTALL) Log.i(TAG,
576 "Posting delayed MCS_UNBIND");
577 removeMessages(MCS_UNBIND);
578 Message ubmsg = obtainMessage(MCS_UNBIND);
579 // Unbind after a little delay, to avoid
580 // continual thrashing.
581 sendMessageDelayed(ubmsg, 10000);
582 }
583 } else {
584 // There are more pending requests in queue.
585 // Just post MCS_BOUND message to trigger processing
586 // of next pending install.
587 if (DEBUG_SD_INSTALL) Log.i(TAG,
588 "Posting MCS_BOUND for next woek");
589 mHandler.sendEmptyMessage(MCS_BOUND);
590 }
591 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800592 }
593 } else {
594 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800595 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800596 }
597 break;
598 }
Kenny Root5ab21572011-07-27 11:11:19 -0700599 case MCS_RECONNECT: {
600 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800601 if (mPendingInstalls.size() > 0) {
602 if (mBound) {
603 disconnectService();
604 }
605 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800606 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800607 for (HandlerParams params : mPendingInstalls) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800608 // Indicate service bind error
609 params.serviceError();
610 }
611 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800612 }
613 }
614 break;
615 }
Kenny Root5ab21572011-07-27 11:11:19 -0700616 case MCS_UNBIND: {
Dianne Hackborn7d608422011-08-07 16:24:18 -0700617 // If there is no actual work left, then time to unbind.
Kenny Root5ab21572011-07-27 11:11:19 -0700618 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
619
620 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800621 if (mBound) {
Kenny Root5ab21572011-07-27 11:11:19 -0700622 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
623
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800624 disconnectService();
625 }
Kenny Root5ab21572011-07-27 11:11:19 -0700626 } else if (mPendingInstalls.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800627 // There are more pending requests in queue.
628 // Just post MCS_BOUND message to trigger processing
629 // of next pending install.
630 mHandler.sendEmptyMessage(MCS_BOUND);
631 }
Kenny Root5ab21572011-07-27 11:11:19 -0700632
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800633 break;
634 }
635 case MCS_GIVE_UP: {
Kenny Root5ab21572011-07-27 11:11:19 -0700636 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
Kenny Root60f7ad82011-03-22 12:49:06 -0700637 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800638 break;
639 }
Kenny Root5ab21572011-07-27 11:11:19 -0700640 case SEND_PENDING_BROADCAST: {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800641 String packages[];
Kenny Root60f7ad82011-03-22 12:49:06 -0700642 ArrayList<String> components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700643 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700644 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700645 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700646 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800647 if (mPendingBroadcasts == null) {
648 return;
649 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700650 size = mPendingBroadcasts.size();
651 if (size <= 0) {
652 // Nothing to be done. Just return
653 return;
654 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800655 packages = new String[size];
656 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700657 uids = new int[size];
Andy McFadden2f362292012-01-20 14:43:38 -0800658 Iterator<Map.Entry<String, ArrayList<String>>>
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800659 it = mPendingBroadcasts.entrySet().iterator();
660 int i = 0;
661 while (it.hasNext() && i < size) {
Andy McFadden2f362292012-01-20 14:43:38 -0800662 Map.Entry<String, ArrayList<String>> ent = it.next();
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800663 packages[i] = ent.getKey();
664 components[i] = ent.getValue();
665 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Amith Yamasani13593602012-03-22 16:16:17 -0700666 uids[i] = (ps != null) ? ps.appId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800667 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700668 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800669 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700670 mPendingBroadcasts.clear();
671 }
672 // Send broadcasts
673 for (int i = 0; i < size; i++) {
Kenny Root60f7ad82011-03-22 12:49:06 -0700674 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700675 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700676 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700677 break;
678 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800679 case START_CLEANING_PACKAGE: {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700680 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Jeff Sharkey752cd922012-09-23 16:25:12 -0700681 final String packageName = (String)msg.obj;
682 final int userId = msg.arg1;
683 final boolean andCode = msg.arg2 != 0;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800684 synchronized (mPackages) {
Jeff Sharkey752cd922012-09-23 16:25:12 -0700685 if (userId == UserHandle.USER_ALL) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700686 int[] users = sUserManager.getUserIds();
687 for (int user : users) {
Jeff Sharkey752cd922012-09-23 16:25:12 -0700688 mSettings.addPackageToCleanLPw(
689 new PackageCleanItem(user, packageName, andCode));
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700690 }
691 } else {
Jeff Sharkey752cd922012-09-23 16:25:12 -0700692 mSettings.addPackageToCleanLPw(
693 new PackageCleanItem(userId, packageName, andCode));
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800694 }
695 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700696 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Jeff Sharkey752cd922012-09-23 16:25:12 -0700697 startCleaningPackages();
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800698 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800699 case POST_INSTALL: {
700 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
701 PostInstallData data = mRunningInstalls.get(msg.arg1);
702 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700703 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800704
705 if (data != null) {
706 InstallArgs args = data.args;
707 PackageInstalledInfo res = data.res;
708
709 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700710 res.removedInfo.sendBroadcast(false, true, false);
Christopher Tate1bb69062010-02-19 17:02:12 -0800711 Bundle extras = new Bundle(1);
712 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackborn786b4402012-08-27 15:14:02 -0700713 // Determine the set of users who are adding this
714 // package for the first time vs. those who are seeing
715 // an update.
716 int[] firstUsers;
717 int[] updateUsers = new int[0];
718 if (res.origUsers == null || res.origUsers.length == 0) {
719 firstUsers = res.newUsers;
720 } else {
721 firstUsers = new int[0];
722 for (int i=0; i<res.newUsers.length; i++) {
723 int user = res.newUsers[i];
724 boolean isNew = true;
725 for (int j=0; j<res.origUsers.length; j++) {
726 if (res.origUsers[j] == user) {
727 isNew = false;
728 break;
729 }
730 }
731 if (isNew) {
732 int[] newFirst = new int[firstUsers.length+1];
733 System.arraycopy(firstUsers, 0, newFirst, 0,
734 firstUsers.length);
735 newFirst[firstUsers.length] = user;
736 firstUsers = newFirst;
737 } else {
738 int[] newUpdate = new int[updateUsers.length+1];
739 System.arraycopy(updateUsers, 0, newUpdate, 0,
740 updateUsers.length);
741 newUpdate[updateUsers.length] = user;
742 updateUsers = newUpdate;
743 }
744 }
745 }
746 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
747 res.pkg.applicationInfo.packageName,
748 extras, null, null, firstUsers);
Christopher Tate1bb69062010-02-19 17:02:12 -0800749 final boolean update = res.removedInfo.removedPackage != null;
750 if (update) {
751 extras.putBoolean(Intent.EXTRA_REPLACING, true);
752 }
753 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
754 res.pkg.applicationInfo.packageName,
Dianne Hackborn786b4402012-08-27 15:14:02 -0700755 extras, null, null, updateUsers);
Christopher Tate1bb69062010-02-19 17:02:12 -0800756 if (update) {
757 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
758 res.pkg.applicationInfo.packageName,
Dianne Hackborn786b4402012-08-27 15:14:02 -0700759 extras, null, null, updateUsers);
Dianne Hackborne7f97212011-02-24 14:40:20 -0800760 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
761 null, null,
Dianne Hackborn786b4402012-08-27 15:14:02 -0700762 res.pkg.applicationInfo.packageName, null, updateUsers);
Christopher Tate1bb69062010-02-19 17:02:12 -0800763 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700764 if (res.removedInfo.args != null) {
765 // Remove the replaced package's older resources safely now
766 deleteOld = true;
767 }
Matt Finifterf8a98ed2012-05-14 15:43:34 -0700768
769 // Log current value of "unknown sources" setting
770 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
771 getUnknownSourcesSettings());
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700772 }
773 // Force a gc to clear up things
774 Runtime.getRuntime().gc();
775 // We delete after a gc for applications on sdcard.
776 if (deleteOld) {
777 synchronized (mInstallLock) {
778 res.removedInfo.args.doPostDeleteLI(true);
779 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800780 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800781 if (args.observer != null) {
782 try {
783 args.observer.packageInstalled(res.name, res.returnCode);
784 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800785 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800786 }
787 }
788 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800789 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800790 }
791 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700792 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700793 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
794 boolean reportStatus = msg.arg1 == 1;
795 boolean doGc = msg.arg2 == 1;
796 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
797 if (doGc) {
798 // Force a gc to clear up stale containers.
799 Runtime.getRuntime().gc();
800 }
801 if (msg.obj != null) {
Dianne Hackbornba24e4d2011-09-01 11:17:06 -0700802 @SuppressWarnings("unchecked")
Kenny Root6dceb882012-04-12 14:23:49 -0700803 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700804 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
805 // Unload containers
806 unloadAllContainers(args);
807 }
808 if (reportStatus) {
809 try {
810 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
811 PackageHelper.getMountService().finishMediaUpdate();
812 } catch (RemoteException e) {
813 Log.e(TAG, "MountService not running?");
814 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700815 }
816 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700817 case WRITE_SETTINGS: {
818 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
819 synchronized (mPackages) {
820 removeMessages(WRITE_SETTINGS);
Amith Yamasani483f3b02012-03-13 16:08:00 -0700821 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
Kenny Root447106f2011-03-23 11:00:15 -0700822 mSettings.writeLPr();
Amith Yamasani483f3b02012-03-13 16:08:00 -0700823 mDirtyUsers.clear();
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700824 }
825 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
826 } break;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700827 case WRITE_PACKAGE_RESTRICTIONS: {
Dianne Hackborne7f97212011-02-24 14:40:20 -0800828 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
829 synchronized (mPackages) {
Amith Yamasani483f3b02012-03-13 16:08:00 -0700830 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
831 for (int userId : mDirtyUsers) {
832 mSettings.writePackageRestrictionsLPr(userId);
833 }
834 mDirtyUsers.clear();
Dianne Hackborne7f97212011-02-24 14:40:20 -0800835 }
836 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
837 } break;
Kenny Root5ab21572011-07-27 11:11:19 -0700838 case CHECK_PENDING_VERIFICATION: {
839 final int verificationId = msg.arg1;
Kenny Root05ca4c92011-09-15 10:36:25 -0700840 final PackageVerificationState state = mPendingVerification.get(verificationId);
Kenny Root5ab21572011-07-27 11:11:19 -0700841
rich canningsd9ef3e52012-08-22 14:28:05 -0700842 if ((state != null) && !state.timeoutExtended()) {
Kenny Root05ca4c92011-09-15 10:36:25 -0700843 final InstallArgs args = state.getInstallArgs();
Kenny Roota503a0f2011-10-03 14:45:28 -0700844 Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
Kenny Root5ab21572011-07-27 11:11:19 -0700845 mPendingVerification.remove(verificationId);
846
rich canningsa6cfe522012-05-21 15:50:56 -0700847 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
848
849 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
rich canningsd9ef3e52012-08-22 14:28:05 -0700850 Slog.i(TAG, "Continuing with installation of "
851 + args.packageURI.toString());
852 state.setVerifierResponse(Binder.getCallingUid(),
853 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
rich canningsd1b5cfc2012-08-29 14:49:51 -0700854 broadcastPackageVerified(verificationId, args.packageURI,
rich canningsd55deb02012-10-02 14:53:08 -0700855 PackageManager.VERIFICATION_ALLOW,
856 state.getInstallArgs().getUser());
rich canningsd9ef3e52012-08-22 14:28:05 -0700857 try {
858 ret = args.copyApk(mContainerService, true);
859 } catch (RemoteException e) {
860 Slog.e(TAG, "Could not contact the ContainerService");
861 }
rich canningsd1b5cfc2012-08-29 14:49:51 -0700862 } else {
863 broadcastPackageVerified(verificationId, args.packageURI,
rich canningsd55deb02012-10-02 14:53:08 -0700864 PackageManager.VERIFICATION_REJECT,
865 state.getInstallArgs().getUser());
rich canningsa6cfe522012-05-21 15:50:56 -0700866 }
867
Kenny Root5ab21572011-07-27 11:11:19 -0700868 processPendingInstall(args, ret);
Kenny Root5ab21572011-07-27 11:11:19 -0700869 mHandler.sendEmptyMessage(MCS_UNBIND);
870 }
Kenny Root5ab21572011-07-27 11:11:19 -0700871 break;
872 }
873 case PACKAGE_VERIFIED: {
874 final int verificationId = msg.arg1;
Kenny Root5ab21572011-07-27 11:11:19 -0700875
Kenny Root05ca4c92011-09-15 10:36:25 -0700876 final PackageVerificationState state = mPendingVerification.get(verificationId);
877 if (state == null) {
Kenny Roota503a0f2011-10-03 14:45:28 -0700878 Slog.w(TAG, "Invalid verification token " + verificationId + " received");
Kenny Root5ab21572011-07-27 11:11:19 -0700879 break;
880 }
881
Kenny Root05ca4c92011-09-15 10:36:25 -0700882 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
Kenny Root5ab21572011-07-27 11:11:19 -0700883
Kenny Root05ca4c92011-09-15 10:36:25 -0700884 state.setVerifierResponse(response.callerUid, response.code);
885
886 if (state.isVerificationComplete()) {
887 mPendingVerification.remove(verificationId);
888
889 final InstallArgs args = state.getInstallArgs();
890
891 int ret;
892 if (state.isInstallAllowed()) {
893 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
rich canningsd1b5cfc2012-08-29 14:49:51 -0700894 broadcastPackageVerified(verificationId, args.packageURI,
rich canningsd55deb02012-10-02 14:53:08 -0700895 response.code, state.getInstallArgs().getUser());
Kenny Root05ca4c92011-09-15 10:36:25 -0700896 try {
897 ret = args.copyApk(mContainerService, true);
898 } catch (RemoteException e) {
899 Slog.e(TAG, "Could not contact the ContainerService");
900 }
901 } else {
902 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
Kenny Root5ab21572011-07-27 11:11:19 -0700903 }
Kenny Root05ca4c92011-09-15 10:36:25 -0700904
905 processPendingInstall(args, ret);
906
907 mHandler.sendEmptyMessage(MCS_UNBIND);
Kenny Root5ab21572011-07-27 11:11:19 -0700908 }
909
Kenny Root5ab21572011-07-27 11:11:19 -0700910 break;
911 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700912 }
913 }
914 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800915
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700916 void scheduleWriteSettingsLocked() {
917 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
918 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
919 }
920 }
Amith Yamasani483f3b02012-03-13 16:08:00 -0700921
922 void scheduleWritePackageRestrictionsLocked(int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -0700923 if (!sUserManager.exists(userId)) return;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700924 mDirtyUsers.add(userId);
925 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
926 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
Dianne Hackborne7f97212011-02-24 14:40:20 -0800927 }
928 }
929
Jeff Brownf69c8122012-09-12 17:00:34 -0700930 public static final IPackageManager main(Context context, Installer installer,
931 boolean factoryTest, boolean onlyCore) {
932 PackageManagerService m = new PackageManagerService(context, installer,
933 factoryTest, onlyCore);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 ServiceManager.addService("package", m);
935 return m;
936 }
937
938 static String[] splitString(String str, char sep) {
939 int count = 1;
940 int i = 0;
941 while ((i=str.indexOf(sep, i)) >= 0) {
942 count++;
943 i++;
944 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 String[] res = new String[count];
947 i=0;
948 count = 0;
949 int lastI=0;
950 while ((i=str.indexOf(sep, i)) >= 0) {
951 res[count] = str.substring(lastI, i);
952 count++;
953 i++;
954 lastI = i;
955 }
956 res[count] = str.substring(lastI, str.length());
957 return res;
958 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800959
Jeff Brownf69c8122012-09-12 17:00:34 -0700960 public PackageManagerService(Context context, Installer installer,
961 boolean factoryTest, boolean onlyCore) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800962 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800966 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 mContext = context;
970 mFactoryTest = factoryTest;
Dianne Hackbornd2509fd2011-09-12 12:29:43 -0700971 mOnlyCore = onlyCore;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700972 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 mMetrics = new DisplayMetrics();
Amith Yamasani258848d2012-08-10 17:06:33 -0700974 mSettings = new Settings(context);
Kenny Root447106f2011-03-23 11:00:15 -0700975 mSettings.addSharedUserLPw("android.uid.system",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800977 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, ApplicationInfo.FLAG_SYSTEM);
978 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, ApplicationInfo.FLAG_SYSTEM);
979 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, ApplicationInfo.FLAG_SYSTEM);
Jaikumar Ganesh1abb1cb2012-01-25 16:14:50 -0800980 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981
982 String separateProcesses = SystemProperties.get("debug.separate_processes");
983 if (separateProcesses != null && separateProcesses.length() > 0) {
984 if ("*".equals(separateProcesses)) {
985 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
986 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800987 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 } else {
989 mDefParseFlags = 0;
990 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800991 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 + separateProcesses);
993 }
994 } else {
995 mDefParseFlags = 0;
996 mSeparateProcesses = null;
997 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800998
Jeff Brownf69c8122012-09-12 17:00:34 -0700999 mInstaller = installer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000
1001 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
1002 Display d = wm.getDefaultDisplay();
1003 d.getMetrics(mMetrics);
1004
1005 synchronized (mInstallLock) {
Kenny Root447106f2011-03-23 11:00:15 -07001006 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 synchronized (mPackages) {
1008 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07001009 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 File dataDir = Environment.getDataDirectory();
1012 mAppDataDir = new File(dataDir, "data");
Kenny Root584c4cd2012-10-29 10:46:42 -07001013 mAppInstallDir = new File(dataDir, "app");
1014 mAppLibInstallDir = new File(dataDir, "app-lib");
Kenny Root51a573c2012-05-17 13:30:28 -07001015 mAsecInternalPath = new File(dataDir, "app-asec").getPath();
Amith Yamasani0b285492011-04-14 17:35:23 -07001016 mUserAppDataDir = new File(dataDir, "user");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1018
Dianne Hackborn4428e172012-08-24 17:43:05 -07001019 sUserManager = new UserManagerService(context, this,
1020 mInstallLock, mPackages);
Amith Yamasani0b285492011-04-14 17:35:23 -07001021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 readPermissions();
1023
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08001024 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
Dianne Hackborn13579ed2012-11-28 18:05:36 -08001025 mSdkVersion, mOnlyCore);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001027
1028 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001030
Suchi Amalapurapudaec1722010-01-14 21:25:16 -08001031 // Set flag to monitor and not change apk file paths when
1032 // scanning install directories.
Dianne Hackbornd0c5f512012-06-07 16:53:59 -07001033 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001034 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001035 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001036 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001037 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001042 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001043
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001044 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001045
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001046 /**
1047 * Out of paranoia, ensure that everything in the boot class
1048 * path has been dexed.
1049 */
1050 String bootClassPath = System.getProperty("java.boot.class.path");
1051 if (bootClassPath != null) {
1052 String[] paths = splitString(bootClassPath, ':');
1053 for (int i=0; i<paths.length; i++) {
1054 try {
1055 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
1056 libFiles.add(paths[i]);
1057 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
1058 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001060 } catch (FileNotFoundException e) {
1061 Slog.w(TAG, "Boot class path not found: " + paths[i]);
1062 } catch (IOException e) {
Kenny Rootfec5e752011-09-23 10:09:58 -07001063 Slog.w(TAG, "Cannot dexopt " + paths[i] + "; is it an APK or JAR? "
1064 + e.getMessage());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 }
1066 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001067 } else {
1068 Slog.w(TAG, "No BOOTCLASSPATH found!");
1069 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001070
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001071 /**
1072 * Also ensure all external libraries have had dexopt run on them.
1073 */
1074 if (mSharedLibraries.size() > 0) {
1075 Iterator<String> libs = mSharedLibraries.values().iterator();
1076 while (libs.hasNext()) {
1077 String lib = libs.next();
1078 try {
1079 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
1080 libFiles.add(lib);
1081 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
1082 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001084 } catch (FileNotFoundException e) {
1085 Slog.w(TAG, "Library not found: " + lib);
1086 } catch (IOException e) {
Kenny Rootfec5e752011-09-23 10:09:58 -07001087 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1088 + e.getMessage());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 }
1090 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001091 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001092
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001093 // Gross hack for now: we know this file doesn't contain any
1094 // code, so don't dexopt it to avoid the resulting log spew.
1095 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
1096
1097 /**
1098 * And there are a number of commands implemented in Java, which
1099 * we currently need to do the dexopt on so that they can be
1100 * run from a non-root shell.
1101 */
1102 String[] frameworkFiles = mFrameworkDir.list();
1103 if (frameworkFiles != null) {
1104 for (int i=0; i<frameworkFiles.length; i++) {
1105 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
1106 String path = libPath.getPath();
1107 // Skip the file if we alrady did it.
1108 if (libFiles.contains(path)) {
1109 continue;
1110 }
1111 // Skip the file if it is not a type we want to dexopt.
1112 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1113 continue;
1114 }
1115 try {
1116 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
1117 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
1118 didDexOpt = true;
1119 }
1120 } catch (FileNotFoundException e) {
1121 Slog.w(TAG, "Jar not found: " + path);
1122 } catch (IOException e) {
1123 Slog.w(TAG, "Exception reading jar: " + path, e);
1124 }
1125 }
1126 }
1127
1128 if (didDexOpt) {
1129 // If we had to do a dexopt of one of the previous
1130 // things, then something on the system has changed.
1131 // Consider this significant, and wipe away all other
1132 // existing dexopt files to ensure we don't leave any
1133 // dangling around.
1134 String[] files = mDalvikCacheDir.list();
1135 if (files != null) {
1136 for (int i=0; i<files.length; i++) {
1137 String fn = files[i];
1138 if (fn.startsWith("data@app@")
1139 || fn.startsWith("data@app-private@")) {
1140 Slog.i(TAG, "Pruning dalvik file: " + fn);
1141 (new File(mDalvikCacheDir, fn)).delete();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001142 }
1143 }
1144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001146
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001147 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 mFrameworkInstallObserver = new AppDirObserver(
1149 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
1150 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -07001151 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
1152 | PackageParser.PARSE_IS_SYSTEM_DIR,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001153 scanMode | SCAN_NO_DEX, 0);
Kenny Root51a573c2012-05-17 13:30:28 -07001154
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001155 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
1157 mSystemInstallObserver = new AppDirObserver(
1158 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
1159 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -07001160 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001161 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Kenny Root208d3412012-05-07 19:42:35 -07001162
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07001163 // Collect all vendor packages.
1164 mVendorAppDir = new File("/vendor/app");
1165 mVendorInstallObserver = new AppDirObserver(
1166 mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
1167 mVendorInstallObserver.startWatching();
1168 scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001169 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07001170
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001171 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1172 mInstaller.moveFiles();
1173
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001174 // Prune any system packages that no longer exist.
Kenny Root87b5d7b2012-05-16 13:36:18 -07001175 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001176 if (!mOnlyCore) {
1177 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1178 while (psit.hasNext()) {
1179 PackageSetting ps = psit.next();
Kenny Root208d3412012-05-07 19:42:35 -07001180
1181 /*
1182 * If this is not a system app, it can't be a
1183 * disable system app.
1184 */
1185 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1186 continue;
1187 }
1188
1189 /*
1190 * If the package is scanned, it's not erased.
1191 */
Kenny Rooteca64b32012-06-25 16:37:32 -07001192 final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1193 if (scannedPkg != null) {
Kenny Root208d3412012-05-07 19:42:35 -07001194 /*
1195 * If the system app is both scanned and in the
1196 * disabled packages list, then it must have been
1197 * added via OTA. Remove it from the currently
1198 * scanned package so the previously user-installed
1199 * application can be scanned.
1200 */
1201 if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
Kenny Rooteca64b32012-06-25 16:37:32 -07001202 Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1203 + "; removing system app");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001204 removePackageLI(ps, true);
Kenny Root208d3412012-05-07 19:42:35 -07001205 }
1206
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001207 continue;
1208 }
1209
1210 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001211 psit.remove();
1212 String msg = "System package " + ps.name
1213 + " no longer exists; wiping its data";
1214 reportSettingsProblem(Log.WARN, msg);
Dianne Hackborn4428e172012-08-24 17:43:05 -07001215 removeDataDirsLI(ps.name);
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001216 } else {
Kenny Root87b5d7b2012-05-16 13:36:18 -07001217 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1218 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1219 possiblyDeletedUpdatedSystemApps.add(ps.name);
1220 }
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001221 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001222 }
1223 }
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 //look for any incomplete package installations
Kenny Root447106f2011-03-23 11:00:15 -07001226 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 //clean up list
1228 for(int i = 0; i < deletePkgsList.size(); i++) {
1229 //clean up here
1230 cleanupInstallFailedPackage(deletePkgsList.get(i));
1231 }
1232 //delete tmp files
1233 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001234
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001235 if (!mOnlyCore) {
1236 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1237 SystemClock.uptimeMillis());
1238 mAppInstallObserver = new AppDirObserver(
1239 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
1240 mAppInstallObserver.startWatching();
1241 scanDirLI(mAppInstallDir, 0, scanMode, 0);
1242
1243 mDrmAppInstallObserver = new AppDirObserver(
1244 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
1245 mDrmAppInstallObserver.startWatching();
1246 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1247 scanMode, 0);
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001248
1249 /**
Kenny Root87b5d7b2012-05-16 13:36:18 -07001250 * Remove disable package settings for any updated system
1251 * apps that were removed via an OTA. If they're not a
1252 * previously-updated app, remove them completely.
1253 * Otherwise, just revoke their system-level permissions.
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001254 */
Kenny Root87b5d7b2012-05-16 13:36:18 -07001255 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001256 PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
Kenny Root87b5d7b2012-05-16 13:36:18 -07001257 mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1258
1259 String msg;
1260 if (deletedPkg == null) {
1261 msg = "Updated system package " + deletedAppName
1262 + " no longer exists; wiping its data";
Dianne Hackborn4428e172012-08-24 17:43:05 -07001263 removeDataDirsLI(deletedAppName);
Kenny Root87b5d7b2012-05-16 13:36:18 -07001264 } else {
1265 msg = "Updated system app + " + deletedAppName
1266 + " no longer present; removing system privileges for "
1267 + deletedAppName;
1268
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001269 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1270
1271 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1272 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1273 }
Kenny Root87b5d7b2012-05-16 13:36:18 -07001274 reportSettingsProblem(Log.WARN, msg);
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001275 }
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001276 } else {
1277 mAppInstallObserver = null;
1278 mDrmAppInstallObserver = null;
1279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001281 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001283 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 + ((SystemClock.uptimeMillis()-startTime)/1000f)
1285 + " seconds");
1286
Dianne Hackbornf22221f2010-04-05 18:35:42 -07001287 // If the platform SDK has changed since the last time we booted,
1288 // we need to re-grant app permission to catch any new ones that
1289 // appear. This is really a hack, and means that apps can in some
1290 // cases get permissions that the user didn't initially explicitly
1291 // allow... it would be nice to have some better way to handle
1292 // this situation.
1293 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1294 != mSdkVersion;
1295 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1296 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1297 + "; regranting permissions for internal storage");
1298 mSettings.mInternalSdkPlatform = mSdkVersion;
1299
Dianne Hackborne639da72012-02-21 15:11:13 -08001300 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1301 | (regrantPermissions
1302 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1303 : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304
Kenny Root447106f2011-03-23 11:00:15 -07001305 // can downgrade to reader
1306 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001308 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 // Now after opening every single application zip, make sure they
1312 // are all flushed. Not really needed, but keeps things nice and
1313 // tidy.
1314 Runtime.getRuntime().gc();
Kenny Root05ca4c92011-09-15 10:36:25 -07001315
1316 mRequiredVerifierPackage = getRequiredVerifierLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 } // synchronized (mPackages)
1318 } // synchronized (mInstallLock)
1319 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001320
Dianne Hackborn58f42a52011-10-10 13:46:34 -07001321 public boolean isFirstBoot() {
1322 return !mRestoredSettings;
1323 }
1324
Dianne Hackborn13579ed2012-11-28 18:05:36 -08001325 public boolean isOnlyCoreApps() {
1326 return mOnlyCore;
1327 }
1328
Kenny Root05ca4c92011-09-15 10:36:25 -07001329 private String getRequiredVerifierLPr() {
1330 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1331 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
Amith Yamasani483f3b02012-03-13 16:08:00 -07001332 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
Kenny Root05ca4c92011-09-15 10:36:25 -07001333
1334 String requiredVerifier = null;
1335
1336 final int N = receivers.size();
1337 for (int i = 0; i < N; i++) {
1338 final ResolveInfo info = receivers.get(i);
1339
1340 if (info.activityInfo == null) {
1341 continue;
1342 }
1343
1344 final String packageName = info.activityInfo.packageName;
1345
1346 final PackageSetting ps = mSettings.mPackages.get(packageName);
1347 if (ps == null) {
1348 continue;
1349 }
1350
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001351 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1352 if (!gp.grantedPermissions
Kenny Root05ca4c92011-09-15 10:36:25 -07001353 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1354 continue;
1355 }
1356
1357 if (requiredVerifier != null) {
1358 throw new RuntimeException("There can be only one required verifier");
1359 }
1360
1361 requiredVerifier = packageName;
1362 }
1363
1364 return requiredVerifier;
1365 }
1366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 @Override
1368 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1369 throws RemoteException {
1370 try {
1371 return super.onTransact(code, data, reply, flags);
1372 } catch (RuntimeException e) {
1373 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001374 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 }
1376 throw e;
1377 }
1378 }
1379
Dianne Hackborne6620b22010-01-22 14:46:21 -08001380 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001381 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
Dianne Hackborn4428e172012-08-24 17:43:05 -07001382 removeDataDirsLI(ps.name);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001383 if (ps.codePath != null) {
1384 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001385 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001386 }
1387 }
1388 if (ps.resourcePath != null) {
1389 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001390 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001391 }
1392 }
Kenny Root447106f2011-03-23 11:00:15 -07001393 mSettings.removePackageLPw(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 }
1395
1396 void readPermissions() {
1397 // Read permissions from .../etc/permission directory.
1398 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1399 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001400 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 return;
1402 }
1403 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001404 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 return;
1406 }
1407
1408 // Iterate over the files in the directory and scan .xml files
1409 for (File f : libraryDir.listFiles()) {
1410 // We'll read platform.xml last
1411 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1412 continue;
1413 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001416 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 continue;
1418 }
1419 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001420 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 continue;
1422 }
1423
1424 readPermissionsFromXml(f);
1425 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1428 final File permFile = new File(Environment.getRootDirectory(),
1429 "etc/permissions/platform.xml");
1430 readPermissionsFromXml(permFile);
1431 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001432
1433 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 FileReader permReader = null;
1435 try {
1436 permReader = new FileReader(permFile);
1437 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001438 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 return;
1440 }
1441
1442 try {
1443 XmlPullParser parser = Xml.newPullParser();
1444 parser.setInput(permReader);
1445
1446 XmlUtils.beginDocument(parser, "permissions");
1447
1448 while (true) {
1449 XmlUtils.nextElement(parser);
1450 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1451 break;
1452 }
1453
1454 String name = parser.getName();
1455 if ("group".equals(name)) {
1456 String gidStr = parser.getAttributeValue(null, "gid");
1457 if (gidStr != null) {
1458 int gid = Integer.parseInt(gidStr);
1459 mGlobalGids = appendInt(mGlobalGids, gid);
1460 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001461 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 + parser.getPositionDescription());
1463 }
1464
1465 XmlUtils.skipCurrentTag(parser);
1466 continue;
1467 } else if ("permission".equals(name)) {
1468 String perm = parser.getAttributeValue(null, "name");
1469 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001470 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 + parser.getPositionDescription());
1472 XmlUtils.skipCurrentTag(parser);
1473 continue;
1474 }
1475 perm = perm.intern();
1476 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 } else if ("assign-permission".equals(name)) {
1479 String perm = parser.getAttributeValue(null, "name");
1480 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001481 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 + parser.getPositionDescription());
1483 XmlUtils.skipCurrentTag(parser);
1484 continue;
1485 }
1486 String uidStr = parser.getAttributeValue(null, "uid");
1487 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001488 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 + parser.getPositionDescription());
1490 XmlUtils.skipCurrentTag(parser);
1491 continue;
1492 }
1493 int uid = Process.getUidForName(uidStr);
1494 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001495 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 + uidStr + "\" at "
1497 + parser.getPositionDescription());
1498 XmlUtils.skipCurrentTag(parser);
1499 continue;
1500 }
1501 perm = perm.intern();
1502 HashSet<String> perms = mSystemPermissions.get(uid);
1503 if (perms == null) {
1504 perms = new HashSet<String>();
1505 mSystemPermissions.put(uid, perms);
1506 }
1507 perms.add(perm);
1508 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 } else if ("library".equals(name)) {
1511 String lname = parser.getAttributeValue(null, "name");
1512 String lfile = parser.getAttributeValue(null, "file");
1513 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001514 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 + parser.getPositionDescription());
1516 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001517 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 + parser.getPositionDescription());
1519 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001520 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001521 mSharedLibraries.put(lname, lfile);
1522 }
1523 XmlUtils.skipCurrentTag(parser);
1524 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001525
Dianne Hackborn49237342009-08-27 20:08:01 -07001526 } else if ("feature".equals(name)) {
1527 String fname = parser.getAttributeValue(null, "name");
1528 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001529 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001530 + parser.getPositionDescription());
1531 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001532 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001533 FeatureInfo fi = new FeatureInfo();
1534 fi.name = fname;
1535 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 }
1537 XmlUtils.skipCurrentTag(parser);
1538 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 } else {
1541 XmlUtils.skipCurrentTag(parser);
1542 continue;
1543 }
1544
1545 }
Brian Carlstromfd9ddd12010-11-04 11:24:58 -07001546 permReader.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001548 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001550 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 }
1552 }
1553
1554 void readPermission(XmlPullParser parser, String name)
1555 throws IOException, XmlPullParserException {
1556
1557 name = name.intern();
1558
1559 BasePermission bp = mSettings.mPermissions.get(name);
1560 if (bp == null) {
1561 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1562 mSettings.mPermissions.put(name, bp);
1563 }
1564 int outerDepth = parser.getDepth();
1565 int type;
1566 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1567 && (type != XmlPullParser.END_TAG
1568 || parser.getDepth() > outerDepth)) {
1569 if (type == XmlPullParser.END_TAG
1570 || type == XmlPullParser.TEXT) {
1571 continue;
1572 }
1573
1574 String tagName = parser.getName();
1575 if ("group".equals(tagName)) {
1576 String gidStr = parser.getAttributeValue(null, "gid");
1577 if (gidStr != null) {
1578 int gid = Process.getGidForName(gidStr);
1579 bp.gids = appendInt(bp.gids, gid);
1580 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001581 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 + parser.getPositionDescription());
1583 }
1584 }
1585 XmlUtils.skipCurrentTag(parser);
1586 }
1587 }
1588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 static int[] appendInts(int[] cur, int[] add) {
1590 if (add == null) return cur;
1591 if (cur == null) return add;
1592 final int N = add.length;
1593 for (int i=0; i<N; i++) {
1594 cur = appendInt(cur, add[i]);
1595 }
1596 return cur;
1597 }
1598
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001599 static int[] removeInts(int[] cur, int[] rem) {
1600 if (rem == null) return cur;
1601 if (cur == null) return cur;
1602 final int N = rem.length;
1603 for (int i=0; i<N; i++) {
1604 cur = removeInt(cur, rem[i]);
1605 }
1606 return cur;
1607 }
1608
Amith Yamasani13593602012-03-22 16:16:17 -07001609 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1610 if (!sUserManager.exists(userId)) return null;
1611 PackageInfo pi;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001612 final PackageSetting ps = (PackageSetting) p.mExtras;
1613 if (ps == null) {
1614 return null;
1615 }
1616 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1617 final PackageUserState state = ps.readUserState(userId);
1618 pi = PackageParser.generatePackageInfo(p, gp.gids, flags,
1619 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1620 state, userId);
1621 if (pi != null) {
1622 pi.applicationInfo.enabledSetting = state.enabled;
Amith Yamasani13593602012-03-22 16:16:17 -07001623 pi.applicationInfo.enabled =
1624 pi.applicationInfo.enabledSetting == COMPONENT_ENABLED_STATE_DEFAULT
1625 || pi.applicationInfo.enabledSetting == COMPONENT_ENABLED_STATE_ENABLED;
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001626 }
Amith Yamasani13593602012-03-22 16:16:17 -07001627 return pi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 }
1629
Amith Yamasani483f3b02012-03-13 16:08:00 -07001630 @Override
1631 public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001632 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07001633 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
Kenny Root447106f2011-03-23 11:00:15 -07001634 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 synchronized (mPackages) {
1636 PackageParser.Package p = mPackages.get(packageName);
Kenny Root9718cf52011-02-23 16:45:26 -08001637 if (DEBUG_PACKAGE_INFO)
1638 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 if (p != null) {
Amith Yamasani13593602012-03-22 16:16:17 -07001640 return generatePackageInfo(p, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 }
1642 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001643 return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 }
1645 }
1646 return null;
1647 }
1648
Dianne Hackborn47096932010-02-11 15:57:09 -08001649 public String[] currentToCanonicalPackageNames(String[] names) {
1650 String[] out = new String[names.length];
Kenny Root447106f2011-03-23 11:00:15 -07001651 // reader
Dianne Hackborn47096932010-02-11 15:57:09 -08001652 synchronized (mPackages) {
1653 for (int i=names.length-1; i>=0; i--) {
1654 PackageSetting ps = mSettings.mPackages.get(names[i]);
1655 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1656 }
1657 }
1658 return out;
1659 }
1660
1661 public String[] canonicalToCurrentPackageNames(String[] names) {
1662 String[] out = new String[names.length];
Kenny Root447106f2011-03-23 11:00:15 -07001663 // reader
Dianne Hackborn47096932010-02-11 15:57:09 -08001664 synchronized (mPackages) {
1665 for (int i=names.length-1; i>=0; i--) {
1666 String cur = mSettings.mRenamedPackages.get(names[i]);
1667 out[i] = cur != null ? cur : names[i];
1668 }
1669 }
1670 return out;
1671 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07001672
1673 @Override
1674 public int getPackageUid(String packageName, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001675 if (!sUserManager.exists(userId)) return -1;
Amith Yamasanif203aee2012-08-29 18:41:53 -07001676 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
Kenny Root447106f2011-03-23 11:00:15 -07001677 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 synchronized (mPackages) {
1679 PackageParser.Package p = mPackages.get(packageName);
1680 if(p != null) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001681 return UserHandle.getUid(userId, p.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 }
1683 PackageSetting ps = mSettings.mPackages.get(packageName);
1684 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1685 return -1;
1686 }
1687 p = ps.pkg;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001688 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 }
1690 }
1691
1692 public int[] getPackageGids(String packageName) {
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -07001693 final boolean enforcedDefault = isPermissionEnforcedDefault(READ_EXTERNAL_STORAGE);
Kenny Root447106f2011-03-23 11:00:15 -07001694 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 synchronized (mPackages) {
1696 PackageParser.Package p = mPackages.get(packageName);
Kenny Root9718cf52011-02-23 16:45:26 -08001697 if (DEBUG_PACKAGE_INFO)
1698 Log.v(TAG, "getPackageGids" + packageName + ": " + p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 if (p != null) {
1700 final PackageSetting ps = (PackageSetting)p.mExtras;
1701 final SharedUserSetting suid = ps.sharedUser;
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07001702 int[] gids = suid != null ? suid.gids : ps.gids;
1703
1704 // include GIDs for any unenforced permissions
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -07001705 if (!isPermissionEnforcedLocked(READ_EXTERNAL_STORAGE, enforcedDefault)) {
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07001706 final BasePermission basePerm = mSettings.mPermissions.get(
1707 READ_EXTERNAL_STORAGE);
1708 gids = appendInts(gids, basePerm.gids);
1709 }
1710
1711 return gids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 }
1713 }
1714 // stupid thing to indicate an error.
1715 return new int[0];
1716 }
1717
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001718 static final PermissionInfo generatePermissionInfo(
1719 BasePermission bp, int flags) {
1720 if (bp.perm != null) {
1721 return PackageParser.generatePermissionInfo(bp.perm, flags);
1722 }
1723 PermissionInfo pi = new PermissionInfo();
1724 pi.name = bp.name;
1725 pi.packageName = bp.sourcePackage;
1726 pi.nonLocalizedLabel = bp.name;
1727 pi.protectionLevel = bp.protectionLevel;
1728 return pi;
1729 }
1730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 public PermissionInfo getPermissionInfo(String name, int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001732 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 synchronized (mPackages) {
1734 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001735 if (p != null) {
1736 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 }
1738 return null;
1739 }
1740 }
1741
1742 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001743 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 synchronized (mPackages) {
1745 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1746 for (BasePermission p : mSettings.mPermissions.values()) {
1747 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001748 if (p.perm == null || p.perm.info.group == null) {
1749 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 }
1751 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001752 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1754 }
1755 }
1756 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 if (out.size() > 0) {
1759 return out;
1760 }
1761 return mPermissionGroups.containsKey(group) ? out : null;
1762 }
1763 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001766 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 synchronized (mPackages) {
1768 return PackageParser.generatePermissionGroupInfo(
1769 mPermissionGroups.get(name), flags);
1770 }
1771 }
1772
1773 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001774 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 synchronized (mPackages) {
1776 final int N = mPermissionGroups.size();
1777 ArrayList<PermissionGroupInfo> out
1778 = new ArrayList<PermissionGroupInfo>(N);
1779 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1780 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1781 }
1782 return out;
1783 }
1784 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001785
Amith Yamasani483f3b02012-03-13 16:08:00 -07001786 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
1787 int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001788 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 PackageSetting ps = mSettings.mPackages.get(packageName);
Kenny Root447106f2011-03-23 11:00:15 -07001790 if (ps != null) {
1791 if (ps.pkg == null) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001792 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
1793 flags, userId);
Kenny Root447106f2011-03-23 11:00:15 -07001794 if (pInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 return pInfo.applicationInfo;
1796 }
1797 return null;
1798 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001799 return PackageParser.generateApplicationInfo(ps.pkg, flags,
1800 ps.readUserState(userId), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 }
1802 return null;
1803 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001804
Amith Yamasani483f3b02012-03-13 16:08:00 -07001805 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
1806 int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001807 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 PackageSetting ps = mSettings.mPackages.get(packageName);
Kenny Root447106f2011-03-23 11:00:15 -07001809 if (ps != null) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001810 PackageParser.Package pkg = ps.pkg;
1811 if (pkg == null) {
1812 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
1813 return null;
1814 }
1815 pkg = new PackageParser.Package(packageName);
1816 pkg.applicationInfo.packageName = packageName;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001817 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001818 pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1819 pkg.applicationInfo.sourceDir = ps.codePathString;
1820 pkg.applicationInfo.dataDir =
Amith Yamasani317046a2012-08-29 18:48:08 -07001821 getDataPathForPackage(packageName, 0).getPath();
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001822 pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001824 // pkg.mSetEnabled = ps.getEnabled(userId);
1825 // pkg.mSetStopped = ps.getStopped(userId);
1826 return generatePackageInfo(pkg, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 }
1828 return null;
1829 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001830
Amith Yamasani483f3b02012-03-13 16:08:00 -07001831 @Override
1832 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001833 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07001834 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
Kenny Root447106f2011-03-23 11:00:15 -07001835 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 synchronized (mPackages) {
1837 PackageParser.Package p = mPackages.get(packageName);
Kenny Root9718cf52011-02-23 16:45:26 -08001838 if (DEBUG_PACKAGE_INFO) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 TAG, "getApplicationInfo " + packageName
1840 + ": " + p);
1841 if (p != null) {
Amith Yamasani13593602012-03-22 16:16:17 -07001842 PackageSetting ps = mSettings.mPackages.get(packageName);
1843 if (ps == null) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 // Note: isEnabledLP() does not apply here - always return info
Jeff Sharkey38f86882012-10-11 16:10:23 -07001845 return PackageParser.generateApplicationInfo(
1846 p, flags, ps.readUserState(userId), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847 }
1848 if ("android".equals(packageName)||"system".equals(packageName)) {
1849 return mAndroidApplication;
1850 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001851 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001852 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 }
1854 }
1855 return null;
1856 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001857
1858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1860 mContext.enforceCallingOrSelfPermission(
1861 android.Manifest.permission.CLEAR_APP_CACHE, null);
1862 // Queue up an async operation since clearing cache may take a little while.
1863 mHandler.post(new Runnable() {
1864 public void run() {
1865 mHandler.removeCallbacks(this);
1866 int retCode = -1;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001867 synchronized (mInstallLock) {
1868 retCode = mInstaller.freeCache(freeStorageSize);
1869 if (retCode < 0) {
1870 Slog.w(TAG, "Couldn't clear application caches");
1871 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 if (observer != null) {
1874 try {
1875 observer.onRemoveCompleted(null, (retCode >= 0));
1876 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001877 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 }
1879 }
1880 }
1881 });
1882 }
1883
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001884 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001885 mContext.enforceCallingOrSelfPermission(
1886 android.Manifest.permission.CLEAR_APP_CACHE, null);
1887 // Queue up an async operation since clearing cache may take a little while.
1888 mHandler.post(new Runnable() {
1889 public void run() {
1890 mHandler.removeCallbacks(this);
1891 int retCode = -1;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001892 synchronized (mInstallLock) {
1893 retCode = mInstaller.freeCache(freeStorageSize);
1894 if (retCode < 0) {
1895 Slog.w(TAG, "Couldn't clear application caches");
1896 }
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001897 }
1898 if(pi != null) {
1899 try {
1900 // Callback via pending intent
1901 int code = (retCode >= 0) ? 1 : 0;
1902 pi.sendIntent(null, code, null,
1903 null, null);
1904 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001905 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001906 }
1907 }
1908 }
1909 });
1910 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001911
Amith Yamasani483f3b02012-03-13 16:08:00 -07001912 @Override
1913 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001914 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07001915 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 synchronized (mPackages) {
1917 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001918
Kenny Root9718cf52011-02-23 16:45:26 -08001919 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001920 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
Amith Yamasani13593602012-03-22 16:16:17 -07001921 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
1922 if (ps == null) return null;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001923 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
1924 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 }
1926 if (mResolveComponentName.equals(component)) {
1927 return mResolveActivity;
1928 }
1929 }
1930 return null;
1931 }
1932
Amith Yamasani483f3b02012-03-13 16:08:00 -07001933 @Override
1934 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001935 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07001936 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 synchronized (mPackages) {
1938 PackageParser.Activity a = mReceivers.mActivities.get(component);
Kenny Root9718cf52011-02-23 16:45:26 -08001939 if (DEBUG_PACKAGE_INFO) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 TAG, "getReceiverInfo " + component + ": " + a);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001941 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
Amith Yamasani13593602012-03-22 16:16:17 -07001942 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
1943 if (ps == null) return null;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001944 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
1945 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 }
1947 }
1948 return null;
1949 }
1950
Amith Yamasani483f3b02012-03-13 16:08:00 -07001951 @Override
1952 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001953 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07001954 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 synchronized (mPackages) {
1956 PackageParser.Service s = mServices.mServices.get(component);
Kenny Root9718cf52011-02-23 16:45:26 -08001957 if (DEBUG_PACKAGE_INFO) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 TAG, "getServiceInfo " + component + ": " + s);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001959 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
Amith Yamasani13593602012-03-22 16:16:17 -07001960 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
1961 if (ps == null) return null;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001962 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
1963 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 }
1965 }
1966 return null;
1967 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001968
Amith Yamasani483f3b02012-03-13 16:08:00 -07001969 @Override
1970 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001971 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07001972 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
Dianne Hackborn361199b2010-08-30 17:42:07 -07001973 synchronized (mPackages) {
1974 PackageParser.Provider p = mProvidersByComponent.get(component);
Kenny Root9718cf52011-02-23 16:45:26 -08001975 if (DEBUG_PACKAGE_INFO) Log.v(
Dianne Hackborn361199b2010-08-30 17:42:07 -07001976 TAG, "getProviderInfo " + component + ": " + p);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001977 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
Amith Yamasani13593602012-03-22 16:16:17 -07001978 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
1979 if (ps == null) return null;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001980 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
1981 userId);
Dianne Hackborn361199b2010-08-30 17:42:07 -07001982 }
1983 }
1984 return null;
1985 }
1986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 public String[] getSystemSharedLibraryNames() {
1988 Set<String> libSet;
1989 synchronized (mPackages) {
1990 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001991 int size = libSet.size();
1992 if (size > 0) {
1993 String[] libs = new String[size];
1994 libSet.toArray(libs);
1995 return libs;
1996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001998 return null;
1999 }
2000
2001 public FeatureInfo[] getSystemAvailableFeatures() {
2002 Collection<FeatureInfo> featSet;
2003 synchronized (mPackages) {
2004 featSet = mAvailableFeatures.values();
2005 int size = featSet.size();
2006 if (size > 0) {
2007 FeatureInfo[] features = new FeatureInfo[size+1];
2008 featSet.toArray(features);
2009 FeatureInfo fi = new FeatureInfo();
2010 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2011 FeatureInfo.GL_ES_VERSION_UNDEFINED);
2012 features[size] = fi;
2013 return features;
2014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 }
2016 return null;
2017 }
2018
Dianne Hackborn039c68e2009-09-26 16:39:23 -07002019 public boolean hasSystemFeature(String name) {
2020 synchronized (mPackages) {
2021 return mAvailableFeatures.containsKey(name);
2022 }
2023 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002024
Amith Yamasani483f3b02012-03-13 16:08:00 -07002025 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002026 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
Amith Yamasani483f3b02012-03-13 16:08:00 -07002027 return;
2028
2029 throw new SecurityException("Caller uid=" + uid
2030 + " is not privileged to communicate with user=" + userId);
2031 }
2032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 public int checkPermission(String permName, String pkgName) {
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -07002034 final boolean enforcedDefault = isPermissionEnforcedDefault(permName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 synchronized (mPackages) {
2036 PackageParser.Package p = mPackages.get(pkgName);
2037 if (p != null && p.mExtras != null) {
2038 PackageSetting ps = (PackageSetting)p.mExtras;
2039 if (ps.sharedUser != null) {
2040 if (ps.sharedUser.grantedPermissions.contains(permName)) {
2041 return PackageManager.PERMISSION_GRANTED;
2042 }
2043 } else if (ps.grantedPermissions.contains(permName)) {
2044 return PackageManager.PERMISSION_GRANTED;
2045 }
2046 }
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -07002047 if (!isPermissionEnforcedLocked(permName, enforcedDefault)) {
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07002048 return PackageManager.PERMISSION_GRANTED;
2049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 }
2051 return PackageManager.PERMISSION_DENIED;
2052 }
2053
2054 public int checkUidPermission(String permName, int uid) {
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -07002055 final boolean enforcedDefault = isPermissionEnforcedDefault(permName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 synchronized (mPackages) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002057 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002059 GrantedPermissions gp = (GrantedPermissions)obj;
2060 if (gp.grantedPermissions.contains(permName)) {
2061 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 }
2063 } else {
2064 HashSet<String> perms = mSystemPermissions.get(uid);
2065 if (perms != null && perms.contains(permName)) {
2066 return PackageManager.PERMISSION_GRANTED;
2067 }
2068 }
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -07002069 if (!isPermissionEnforcedLocked(permName, enforcedDefault)) {
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07002070 return PackageManager.PERMISSION_GRANTED;
2071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 }
2073 return PackageManager.PERMISSION_DENIED;
2074 }
2075
Amith Yamasanif203aee2012-08-29 18:41:53 -07002076 /**
2077 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2078 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2079 * @param message the message to log on security exception
2080 * @return
2081 */
2082 private void enforceCrossUserPermission(int callingUid, int userId,
2083 boolean requireFullPermission, String message) {
2084 if (userId < 0) {
2085 throw new IllegalArgumentException("Invalid userId " + userId);
2086 }
2087 if (userId == UserHandle.getUserId(callingUid)) return;
2088 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2089 if (requireFullPermission) {
2090 mContext.enforceCallingOrSelfPermission(
2091 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2092 } else {
2093 try {
2094 mContext.enforceCallingOrSelfPermission(
2095 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2096 } catch (SecurityException se) {
2097 mContext.enforceCallingOrSelfPermission(
2098 android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2099 }
2100 }
2101 }
2102 }
2103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 private BasePermission findPermissionTreeLP(String permName) {
2105 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2106 if (permName.startsWith(bp.name) &&
2107 permName.length() > bp.name.length() &&
2108 permName.charAt(bp.name.length()) == '.') {
2109 return bp;
2110 }
2111 }
2112 return null;
2113 }
2114
2115 private BasePermission checkPermissionTreeLP(String permName) {
2116 if (permName != null) {
2117 BasePermission bp = findPermissionTreeLP(permName);
2118 if (bp != null) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002119 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 return bp;
2121 }
2122 throw new SecurityException("Calling uid "
2123 + Binder.getCallingUid()
2124 + " is not allowed to add to permission tree "
2125 + bp.name + " owned by uid " + bp.uid);
2126 }
2127 }
2128 throw new SecurityException("No permission tree found for " + permName);
2129 }
2130
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002131 static boolean compareStrings(CharSequence s1, CharSequence s2) {
2132 if (s1 == null) {
2133 return s2 == null;
2134 }
2135 if (s2 == null) {
2136 return false;
2137 }
2138 if (s1.getClass() != s2.getClass()) {
2139 return false;
2140 }
2141 return s1.equals(s2);
2142 }
2143
2144 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2145 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07002146 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002147 if (pi1.protectionLevel != pi2.protectionLevel) return false;
2148 if (!compareStrings(pi1.name, pi2.name)) return false;
2149 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2150 // We'll take care of setting this one.
2151 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2152 // These are not currently stored in settings.
2153 //if (!compareStrings(pi1.group, pi2.group)) return false;
2154 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2155 //if (pi1.labelRes != pi2.labelRes) return false;
2156 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2157 return true;
2158 }
2159
2160 boolean addPermissionLocked(PermissionInfo info, boolean async) {
2161 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2162 throw new SecurityException("Label must be specified in permission");
2163 }
2164 BasePermission tree = checkPermissionTreeLP(info.name);
2165 BasePermission bp = mSettings.mPermissions.get(info.name);
2166 boolean added = bp == null;
2167 boolean changed = true;
Dianne Hackborne639da72012-02-21 15:11:13 -08002168 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002169 if (added) {
2170 bp = new BasePermission(info.name, tree.sourcePackage,
2171 BasePermission.TYPE_DYNAMIC);
2172 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2173 throw new SecurityException(
2174 "Not allowed to modify non-dynamic permission "
2175 + info.name);
2176 } else {
Dianne Hackborne639da72012-02-21 15:11:13 -08002177 if (bp.protectionLevel == fixedLevel
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002178 && bp.perm.owner.equals(tree.perm.owner)
2179 && bp.uid == tree.uid
2180 && comparePermissionInfos(bp.perm.info, info)) {
2181 changed = false;
2182 }
2183 }
Dianne Hackborne639da72012-02-21 15:11:13 -08002184 bp.protectionLevel = fixedLevel;
2185 info = new PermissionInfo(info);
2186 info.protectionLevel = fixedLevel;
2187 bp.perm = new PackageParser.Permission(tree.perm.owner, info);
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002188 bp.perm.info.packageName = tree.perm.info.packageName;
2189 bp.uid = tree.uid;
2190 if (added) {
2191 mSettings.mPermissions.put(info.name, bp);
2192 }
2193 if (changed) {
2194 if (!async) {
Kenny Root447106f2011-03-23 11:00:15 -07002195 mSettings.writeLPr();
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002196 } else {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002197 scheduleWriteSettingsLocked();
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002198 }
2199 }
2200 return added;
2201 }
2202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002203 public boolean addPermission(PermissionInfo info) {
2204 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002205 return addPermissionLocked(info, false);
2206 }
2207 }
2208
2209 public boolean addPermissionAsync(PermissionInfo info) {
2210 synchronized (mPackages) {
2211 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 }
2213 }
2214
2215 public void removePermission(String name) {
2216 synchronized (mPackages) {
2217 checkPermissionTreeLP(name);
2218 BasePermission bp = mSettings.mPermissions.get(name);
2219 if (bp != null) {
2220 if (bp.type != BasePermission.TYPE_DYNAMIC) {
2221 throw new SecurityException(
2222 "Not allowed to modify non-dynamic permission "
2223 + name);
2224 }
2225 mSettings.mPermissions.remove(name);
Kenny Root447106f2011-03-23 11:00:15 -07002226 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002227 }
2228 }
2229 }
2230
Dianne Hackborne639da72012-02-21 15:11:13 -08002231 public void grantPermission(String packageName, String permissionName) {
2232 mContext.enforceCallingOrSelfPermission(
2233 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2234 synchronized (mPackages) {
2235 final PackageParser.Package pkg = mPackages.get(packageName);
2236 if (pkg == null) {
2237 throw new IllegalArgumentException("Unknown package: " + packageName);
2238 }
2239 final BasePermission bp = mSettings.mPermissions.get(permissionName);
2240 if (bp == null) {
2241 throw new IllegalArgumentException("Unknown permission: " + packageName);
2242 }
2243 if (!pkg.requestedPermissions.contains(permissionName)) {
2244 throw new SecurityException("Package " + packageName
2245 + " has not requested permission " + permissionName);
2246 }
2247 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) == 0) {
2248 throw new SecurityException("Permission " + permissionName
2249 + " is not a development permission");
2250 }
2251 final PackageSetting ps = (PackageSetting) pkg.mExtras;
2252 if (ps == null) {
2253 return;
2254 }
2255 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2256 if (gp.grantedPermissions.add(permissionName)) {
2257 if (ps.haveGids) {
2258 gp.gids = appendInts(gp.gids, bp.gids);
2259 }
2260 mSettings.writeLPr();
2261 }
2262 }
2263 }
2264
2265 public void revokePermission(String packageName, String permissionName) {
2266 synchronized (mPackages) {
2267 final PackageParser.Package pkg = mPackages.get(packageName);
2268 if (pkg == null) {
2269 throw new IllegalArgumentException("Unknown package: " + packageName);
2270 }
2271 if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2272 mContext.enforceCallingOrSelfPermission(
2273 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2274 }
2275 final BasePermission bp = mSettings.mPermissions.get(permissionName);
2276 if (bp == null) {
2277 throw new IllegalArgumentException("Unknown permission: " + packageName);
2278 }
2279 if (!pkg.requestedPermissions.contains(permissionName)) {
2280 throw new SecurityException("Package " + packageName
2281 + " has not requested permission " + permissionName);
2282 }
2283 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) == 0) {
2284 throw new SecurityException("Permission " + permissionName
2285 + " is not a development permission");
2286 }
2287 final PackageSetting ps = (PackageSetting) pkg.mExtras;
2288 if (ps == null) {
2289 return;
2290 }
2291 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2292 if (gp.grantedPermissions.remove(permissionName)) {
2293 gp.grantedPermissions.remove(permissionName);
2294 if (ps.haveGids) {
2295 gp.gids = removeInts(gp.gids, bp.gids);
2296 }
2297 mSettings.writeLPr();
2298 }
2299 }
2300 }
2301
Dianne Hackborn854060af2009-07-09 18:14:31 -07002302 public boolean isProtectedBroadcast(String actionName) {
2303 synchronized (mPackages) {
2304 return mProtectedBroadcasts.contains(actionName);
2305 }
2306 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 public int checkSignatures(String pkg1, String pkg2) {
2309 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002310 final PackageParser.Package p1 = mPackages.get(pkg1);
2311 final PackageParser.Package p2 = mPackages.get(pkg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002312 if (p1 == null || p1.mExtras == null
2313 || p2 == null || p2.mExtras == null) {
2314 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2315 }
Kenny Root447106f2011-03-23 11:00:15 -07002316 return compareSignatures(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 }
2318 }
2319
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002320 public int checkUidSignatures(int uid1, int uid2) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002321 // Map to base uids.
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002322 uid1 = UserHandle.getAppId(uid1);
2323 uid2 = UserHandle.getAppId(uid2);
Kenny Root447106f2011-03-23 11:00:15 -07002324 // reader
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002325 synchronized (mPackages) {
2326 Signature[] s1;
2327 Signature[] s2;
Kenny Root447106f2011-03-23 11:00:15 -07002328 Object obj = mSettings.getUserIdLPr(uid1);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002329 if (obj != null) {
2330 if (obj instanceof SharedUserSetting) {
2331 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2332 } else if (obj instanceof PackageSetting) {
2333 s1 = ((PackageSetting)obj).signatures.mSignatures;
2334 } else {
2335 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2336 }
2337 } else {
2338 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2339 }
Kenny Root447106f2011-03-23 11:00:15 -07002340 obj = mSettings.getUserIdLPr(uid2);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002341 if (obj != null) {
2342 if (obj instanceof SharedUserSetting) {
2343 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2344 } else if (obj instanceof PackageSetting) {
2345 s2 = ((PackageSetting)obj).signatures.mSignatures;
2346 } else {
2347 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2348 }
2349 } else {
2350 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2351 }
Kenny Root447106f2011-03-23 11:00:15 -07002352 return compareSignatures(s1, s2);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002353 }
2354 }
2355
Kenny Root447106f2011-03-23 11:00:15 -07002356 static int compareSignatures(Signature[] s1, Signature[] s2) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002357 if (s1 == null) {
2358 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 ? PackageManager.SIGNATURE_NEITHER_SIGNED
2360 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2361 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002362 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2364 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002365 HashSet<Signature> set1 = new HashSet<Signature>();
2366 for (Signature sig : s1) {
2367 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002369 HashSet<Signature> set2 = new HashSet<Signature>();
2370 for (Signature sig : s2) {
2371 set2.add(sig);
2372 }
2373 // Make sure s2 contains all signatures in s1.
2374 if (set1.equals(set2)) {
2375 return PackageManager.SIGNATURE_MATCH;
2376 }
2377 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 }
2379
2380 public String[] getPackagesForUid(int uid) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002381 uid = UserHandle.getAppId(uid);
Kenny Root447106f2011-03-23 11:00:15 -07002382 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002383 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002384 Object obj = mSettings.getUserIdLPr(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 if (obj instanceof SharedUserSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002386 final SharedUserSetting sus = (SharedUserSetting) obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002387 final int N = sus.packages.size();
Kenny Root447106f2011-03-23 11:00:15 -07002388 final String[] res = new String[N];
2389 final Iterator<PackageSetting> it = sus.packages.iterator();
2390 int i = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 while (it.hasNext()) {
2392 res[i++] = it.next().name;
2393 }
2394 return res;
2395 } else if (obj instanceof PackageSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002396 final PackageSetting ps = (PackageSetting) obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 return new String[] { ps.name };
2398 }
2399 }
2400 return null;
2401 }
2402
2403 public String getNameForUid(int uid) {
Kenny Root447106f2011-03-23 11:00:15 -07002404 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002405 synchronized (mPackages) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002406 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002407 if (obj instanceof SharedUserSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002408 final SharedUserSetting sus = (SharedUserSetting) obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 return sus.name + ":" + sus.userId;
2410 } else if (obj instanceof PackageSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002411 final PackageSetting ps = (PackageSetting) obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 return ps.name;
2413 }
2414 }
2415 return null;
2416 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 public int getUidForSharedUser(String sharedUserName) {
2419 if(sharedUserName == null) {
2420 return -1;
2421 }
Kenny Root447106f2011-03-23 11:00:15 -07002422 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002423 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002424 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
Amith Yamasani742a6712011-05-04 14:49:28 -07002425 if (suid == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002426 return -1;
2427 }
2428 return suid.userId;
2429 }
2430 }
2431
Amith Yamasani483f3b02012-03-13 16:08:00 -07002432 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002434 int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002435 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07002436 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
Amith Yamasani483f3b02012-03-13 16:08:00 -07002437 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2438 return chooseBestActivity(intent, resolvedType, flags, query, userId);
Mihai Predaeae850c2009-05-13 10:13:48 +02002439 }
2440
Mihai Predaeae850c2009-05-13 10:13:48 +02002441 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002442 int flags, List<ResolveInfo> query, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 if (query != null) {
2444 final int N = query.size();
2445 if (N == 1) {
2446 return query.get(0);
2447 } else if (N > 1) {
2448 // If there is more than one activity with the same priority,
2449 // then let the user decide between them.
2450 ResolveInfo r0 = query.get(0);
2451 ResolveInfo r1 = query.get(1);
Kenny Root4dfe6ff2011-02-23 17:00:43 -08002452 if (DEBUG_INTENT_MATCHING) {
2453 Log.d(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2454 + r1.activityInfo.name + "=" + r1.priority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 }
2456 // If the first activity has a higher priority, or a different
2457 // default, then it is always desireable to pick it.
2458 if (r0.priority != r1.priority
2459 || r0.preferredOrder != r1.preferredOrder
2460 || r0.isDefault != r1.isDefault) {
2461 return query.get(0);
2462 }
2463 // If we have saved a preference for a preferred activity for
2464 // this Intent, use that.
2465 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002466 flags, query, r0.priority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 if (ri != null) {
2468 return ri;
2469 }
Dianne Hackborn8da429e2012-09-23 12:52:19 -07002470 if (userId != 0) {
2471 ri = new ResolveInfo(mResolveInfo);
2472 ri.activityInfo = new ActivityInfo(ri.activityInfo);
2473 ri.activityInfo.applicationInfo = new ApplicationInfo(
2474 ri.activityInfo.applicationInfo);
2475 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2476 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2477 return ri;
2478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 return mResolveInfo;
2480 }
2481 }
2482 return null;
2483 }
2484
2485 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002486 int flags, List<ResolveInfo> query, int priority, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002487 if (!sUserManager.exists(userId)) return null;
Kenny Root447106f2011-03-23 11:00:15 -07002488 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 synchronized (mPackages) {
Dianne Hackbornf5b86712011-12-05 17:42:41 -08002490 if (intent.getSelector() != null) {
2491 intent = intent.getSelector();
2492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
Dianne Hackborn63092712012-10-07 14:45:35 -07002494 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
2495 List<PreferredActivity> prefs = pir != null
2496 ? pir.queryIntent(intent, resolvedType,
2497 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2498 : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 if (prefs != null && prefs.size() > 0) {
2500 // First figure out how good the original match set is.
2501 // We will only allow preferred activities that came
2502 // from the same match quality.
2503 int match = 0;
Kenny Root447106f2011-03-23 11:00:15 -07002504
2505 if (DEBUG_PREFERRED) {
2506 Log.v(TAG, "Figuring out best match...");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507 }
Kenny Root447106f2011-03-23 11:00:15 -07002508
2509 final int N = query.size();
2510 for (int j=0; j<N; j++) {
2511 final ResolveInfo ri = query.get(j);
2512 if (DEBUG_PREFERRED) {
2513 Log.v(TAG, "Match for " + ri.activityInfo + ": 0x"
2514 + Integer.toHexString(match));
2515 }
2516 if (ri.match > match) {
2517 match = ri.match;
2518 }
2519 }
2520
2521 if (DEBUG_PREFERRED) {
2522 Log.v(TAG, "Best match: 0x" + Integer.toHexString(match));
2523 }
2524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 match &= IntentFilter.MATCH_CATEGORY_MASK;
2526 final int M = prefs.size();
2527 for (int i=0; i<M; i++) {
Kenny Root447106f2011-03-23 11:00:15 -07002528 final PreferredActivity pa = prefs.get(i);
Dianne Hackbornf8b8a3f2011-03-04 00:05:31 -08002529 if (pa.mPref.mMatch != match) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 continue;
2531 }
Dianne Hackborn77119bc2012-10-23 14:32:48 -07002532 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
2533 flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 if (DEBUG_PREFERRED) {
2535 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002536 if (ai != null) {
2537 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2538 } else {
2539 Log.v(TAG, " null");
2540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 }
Dianne Hackborn04505102012-02-29 12:34:04 -08002542 if (ai == null) {
2543 // This previously registered preferred activity
2544 // component is no longer known. Most likely an update
2545 // to the app was installed and in the new version this
2546 // component no longer exists. Clean it up by removing
2547 // it from the preferred activities list, and skip it.
2548 Slog.w(TAG, "Removing dangling preferred activity: "
2549 + pa.mPref.mComponent);
Dianne Hackborn63092712012-10-07 14:45:35 -07002550 pir.removeFilter(pa);
Dianne Hackborn04505102012-02-29 12:34:04 -08002551 continue;
2552 }
2553 for (int j=0; j<N; j++) {
2554 final ResolveInfo ri = query.get(j);
2555 if (!ri.activityInfo.applicationInfo.packageName
2556 .equals(ai.applicationInfo.packageName)) {
2557 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 }
Dianne Hackborn04505102012-02-29 12:34:04 -08002559 if (!ri.activityInfo.name.equals(ai.name)) {
2560 continue;
2561 }
2562
2563 // Okay we found a previously set preferred app.
2564 // If the result set is different from when this
2565 // was created, we need to clear it and re-ask the
2566 // user their preference.
2567 if (!pa.mPref.sameSet(query, priority)) {
2568 Slog.i(TAG, "Result set changed, dropping preferred activity for "
2569 + intent + " type " + resolvedType);
Dianne Hackborn63092712012-10-07 14:45:35 -07002570 pir.removeFilter(pa);
Dianne Hackborn04505102012-02-29 12:34:04 -08002571 return null;
2572 }
2573
2574 // Yay!
2575 return ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 }
2577 }
2578 }
2579 }
2580 return null;
2581 }
2582
Amith Yamasani483f3b02012-03-13 16:08:00 -07002583 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 public List<ResolveInfo> queryIntentActivities(Intent intent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002585 String resolvedType, int flags, int userId) {
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002586 if (!sUserManager.exists(userId)) return Collections.emptyList();
Amith Yamasanif203aee2012-08-29 18:41:53 -07002587 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
Dianne Hackbornf5b86712011-12-05 17:42:41 -08002588 ComponentName comp = intent.getComponent();
2589 if (comp == null) {
2590 if (intent.getSelector() != null) {
2591 intent = intent.getSelector();
2592 comp = intent.getComponent();
2593 }
2594 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 if (comp != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002597 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
Amith Yamasani483f3b02012-03-13 16:08:00 -07002598 final ActivityInfo ai = getActivityInfo(comp, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 if (ai != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002600 final ResolveInfo ri = new ResolveInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 ri.activityInfo = ai;
2602 list.add(ri);
2603 }
2604 return list;
2605 }
2606
Kenny Root447106f2011-03-23 11:00:15 -07002607 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002609 final String pkgName = intent.getPackage();
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002610 if (pkgName == null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002611 return mActivities.queryIntent(intent, resolvedType, flags, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002612 }
Kenny Root447106f2011-03-23 11:00:15 -07002613 final PackageParser.Package pkg = mPackages.get(pkgName);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002614 if (pkg != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002615 return mActivities.queryIntentForPackage(intent, resolvedType, flags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002616 pkg.activities, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002617 }
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002618 return new ArrayList<ResolveInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 }
2620 }
2621
Amith Yamasani483f3b02012-03-13 16:08:00 -07002622 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2624 Intent[] specifics, String[] specificTypes, Intent intent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002625 String resolvedType, int flags, int userId) {
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002626 if (!sUserManager.exists(userId)) return Collections.emptyList();
Amith Yamasanif203aee2012-08-29 18:41:53 -07002627 enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
2628 "query intent activity options");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 final String resultsAction = intent.getAction();
2630
Kenny Root447106f2011-03-23 11:00:15 -07002631 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
Amith Yamasani483f3b02012-03-13 16:08:00 -07002632 | PackageManager.GET_RESOLVED_FILTER, userId);
Kenny Root447106f2011-03-23 11:00:15 -07002633
2634 if (DEBUG_INTENT_MATCHING) {
2635 Log.v(TAG, "Query " + intent + ": " + results);
2636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637
2638 int specificsPos = 0;
2639 int N;
2640
2641 // todo: note that the algorithm used here is O(N^2). This
2642 // isn't a problem in our current environment, but if we start running
2643 // into situations where we have more than 5 or 10 matches then this
2644 // should probably be changed to something smarter...
2645
2646 // First we go through and resolve each of the specific items
2647 // that were supplied, taking care of removing any corresponding
2648 // duplicate items in the generic resolve list.
2649 if (specifics != null) {
2650 for (int i=0; i<specifics.length; i++) {
2651 final Intent sintent = specifics[i];
2652 if (sintent == null) {
2653 continue;
2654 }
2655
Kenny Root447106f2011-03-23 11:00:15 -07002656 if (DEBUG_INTENT_MATCHING) {
2657 Log.v(TAG, "Specific #" + i + ": " + sintent);
2658 }
2659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 String action = sintent.getAction();
2661 if (resultsAction != null && resultsAction.equals(action)) {
2662 // If this action was explicitly requested, then don't
2663 // remove things that have it.
2664 action = null;
2665 }
Kenny Root447106f2011-03-23 11:00:15 -07002666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 ResolveInfo ri = null;
2668 ActivityInfo ai = null;
Kenny Root447106f2011-03-23 11:00:15 -07002669
2670 ComponentName comp = sintent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 if (comp == null) {
2672 ri = resolveIntent(
2673 sintent,
2674 specificTypes != null ? specificTypes[i] : null,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002675 flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 if (ri == null) {
2677 continue;
2678 }
2679 if (ri == mResolveInfo) {
2680 // ACK! Must do something better with this.
2681 }
2682 ai = ri.activityInfo;
2683 comp = new ComponentName(ai.applicationInfo.packageName,
2684 ai.name);
2685 } else {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002686 ai = getActivityInfo(comp, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687 if (ai == null) {
2688 continue;
2689 }
2690 }
2691
2692 // Look for any generic query activities that are duplicates
2693 // of this specific one, and remove them from the results.
Kenny Root9718cf52011-02-23 16:45:26 -08002694 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002695 N = results.size();
2696 int j;
2697 for (j=specificsPos; j<N; j++) {
2698 ResolveInfo sri = results.get(j);
2699 if ((sri.activityInfo.name.equals(comp.getClassName())
2700 && sri.activityInfo.applicationInfo.packageName.equals(
2701 comp.getPackageName()))
2702 || (action != null && sri.filter.matchAction(action))) {
2703 results.remove(j);
Kenny Root9718cf52011-02-23 16:45:26 -08002704 if (DEBUG_INTENT_MATCHING) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002705 TAG, "Removing duplicate item from " + j
2706 + " due to specific " + specificsPos);
2707 if (ri == null) {
2708 ri = sri;
2709 }
2710 j--;
2711 N--;
2712 }
2713 }
2714
2715 // Add this specific item to its proper place.
2716 if (ri == null) {
2717 ri = new ResolveInfo();
2718 ri.activityInfo = ai;
2719 }
2720 results.add(specificsPos, ri);
2721 ri.specificIndex = i;
2722 specificsPos++;
2723 }
2724 }
2725
2726 // Now we go through the remaining generic results and remove any
2727 // duplicate actions that are found here.
2728 N = results.size();
2729 for (int i=specificsPos; i<N-1; i++) {
2730 final ResolveInfo rii = results.get(i);
2731 if (rii.filter == null) {
2732 continue;
2733 }
2734
2735 // Iterate over all of the actions of this result's intent
2736 // filter... typically this should be just one.
2737 final Iterator<String> it = rii.filter.actionsIterator();
2738 if (it == null) {
2739 continue;
2740 }
2741 while (it.hasNext()) {
2742 final String action = it.next();
2743 if (resultsAction != null && resultsAction.equals(action)) {
2744 // If this action was explicitly requested, then don't
2745 // remove things that have it.
2746 continue;
2747 }
2748 for (int j=i+1; j<N; j++) {
2749 final ResolveInfo rij = results.get(j);
2750 if (rij.filter != null && rij.filter.hasAction(action)) {
2751 results.remove(j);
Kenny Root9718cf52011-02-23 16:45:26 -08002752 if (DEBUG_INTENT_MATCHING) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002753 TAG, "Removing duplicate item from " + j
2754 + " due to action " + action + " at " + i);
2755 j--;
2756 N--;
2757 }
2758 }
2759 }
2760
2761 // If the caller didn't request filter information, drop it now
2762 // so we don't have to marshall/unmarshall it.
2763 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2764 rii.filter = null;
2765 }
2766 }
2767
2768 // Filter out the caller activity if so requested.
2769 if (caller != null) {
2770 N = results.size();
2771 for (int i=0; i<N; i++) {
2772 ActivityInfo ainfo = results.get(i).activityInfo;
2773 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2774 && caller.getClassName().equals(ainfo.name)) {
2775 results.remove(i);
2776 break;
2777 }
2778 }
2779 }
2780
2781 // If the caller didn't request filter information,
2782 // drop them now so we don't have to
2783 // marshall/unmarshall it.
2784 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2785 N = results.size();
2786 for (int i=0; i<N; i++) {
2787 results.get(i).filter = null;
2788 }
2789 }
2790
Kenny Root9718cf52011-02-23 16:45:26 -08002791 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002792 return results;
2793 }
2794
Amith Yamasani483f3b02012-03-13 16:08:00 -07002795 @Override
2796 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
2797 int userId) {
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002798 if (!sUserManager.exists(userId)) return Collections.emptyList();
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002799 ComponentName comp = intent.getComponent();
Dianne Hackbornf5b86712011-12-05 17:42:41 -08002800 if (comp == null) {
2801 if (intent.getSelector() != null) {
2802 intent = intent.getSelector();
2803 comp = intent.getComponent();
2804 }
2805 }
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002806 if (comp != null) {
2807 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
Amith Yamasani483f3b02012-03-13 16:08:00 -07002808 ActivityInfo ai = getReceiverInfo(comp, flags, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002809 if (ai != null) {
2810 ResolveInfo ri = new ResolveInfo();
2811 ri.activityInfo = ai;
2812 list.add(ri);
2813 }
2814 return list;
2815 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002816
Kenny Root447106f2011-03-23 11:00:15 -07002817 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 synchronized (mPackages) {
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002819 String pkgName = intent.getPackage();
2820 if (pkgName == null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002821 return mReceivers.queryIntent(intent, resolvedType, flags, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002822 }
Kenny Root447106f2011-03-23 11:00:15 -07002823 final PackageParser.Package pkg = mPackages.get(pkgName);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002824 if (pkg != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002825 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
2826 userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002827 }
2828 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 }
2830 }
2831
Amith Yamasani483f3b02012-03-13 16:08:00 -07002832 @Override
2833 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
2834 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
Amith Yamasani13593602012-03-22 16:16:17 -07002835 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 if (query != null) {
2837 if (query.size() >= 1) {
2838 // If there is more than one service with the same priority,
2839 // just arbitrarily pick the first one.
2840 return query.get(0);
2841 }
2842 }
2843 return null;
2844 }
2845
Amith Yamasani483f3b02012-03-13 16:08:00 -07002846 @Override
2847 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
2848 int userId) {
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002849 if (!sUserManager.exists(userId)) return Collections.emptyList();
Dianne Hackbornf5b86712011-12-05 17:42:41 -08002850 ComponentName comp = intent.getComponent();
2851 if (comp == null) {
2852 if (intent.getSelector() != null) {
2853 intent = intent.getSelector();
2854 comp = intent.getComponent();
2855 }
2856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 if (comp != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002858 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
Amith Yamasani483f3b02012-03-13 16:08:00 -07002859 final ServiceInfo si = getServiceInfo(comp, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 if (si != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002861 final ResolveInfo ri = new ResolveInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 ri.serviceInfo = si;
2863 list.add(ri);
2864 }
2865 return list;
2866 }
2867
Kenny Root447106f2011-03-23 11:00:15 -07002868 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869 synchronized (mPackages) {
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002870 String pkgName = intent.getPackage();
2871 if (pkgName == null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002872 return mServices.queryIntent(intent, resolvedType, flags, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002873 }
Kenny Root447106f2011-03-23 11:00:15 -07002874 final PackageParser.Package pkg = mPackages.get(pkgName);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002875 if (pkg != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002876 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
2877 userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002878 }
2879 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 }
2881 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002882
Amith Yamasani151ec4c2012-09-07 19:25:16 -07002883 @Override
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08002884 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
Kenny Root0e2c0f32011-04-15 17:50:10 -07002885 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
Amith Yamasani151ec4c2012-09-07 19:25:16 -07002886
2887 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888
Kenny Root447106f2011-03-23 11:00:15 -07002889 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 synchronized (mPackages) {
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08002891 ArrayList<PackageInfo> list;
Kenny Root0e2c0f32011-04-15 17:50:10 -07002892 if (listUninstalled) {
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08002893 list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
2894 for (PackageSetting ps : mSettings.mPackages.values()) {
2895 PackageInfo pi;
2896 if (ps.pkg != null) {
2897 pi = generatePackageInfo(ps.pkg, flags, userId);
2898 } else {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002899 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 }
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08002901 if (pi != null) {
2902 list.add(pi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 }
2904 }
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08002905 } else {
2906 list = new ArrayList<PackageInfo>(mPackages.size());
2907 for (PackageParser.Package p : mPackages.values()) {
2908 PackageInfo pi = generatePackageInfo(p, flags, userId);
2909 if (pi != null) {
2910 list.add(pi);
2911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002912 }
2913 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002914
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08002915 return new ParceledListSlice<PackageInfo>(list);
2916 }
2917 }
2918
2919 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
2920 String[] permissions, boolean[] tmp, int flags, int userId) {
2921 int numMatch = 0;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002922 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08002923 for (int i=0; i<permissions.length; i++) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002924 if (gp.grantedPermissions.contains(permissions[i])) {
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08002925 tmp[i] = true;
2926 numMatch++;
2927 } else {
2928 tmp[i] = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 }
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08002931 if (numMatch == 0) {
2932 return;
2933 }
2934 PackageInfo pi;
2935 if (ps.pkg != null) {
2936 pi = generatePackageInfo(ps.pkg, flags, userId);
2937 } else {
2938 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
2939 }
2940 if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
2941 if (numMatch == permissions.length) {
2942 pi.requestedPermissions = permissions;
2943 } else {
2944 pi.requestedPermissions = new String[numMatch];
2945 numMatch = 0;
2946 for (int i=0; i<permissions.length; i++) {
2947 if (tmp[i]) {
2948 pi.requestedPermissions[numMatch] = permissions[i];
2949 numMatch++;
2950 }
2951 }
2952 }
2953 }
2954 list.add(pi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002955 }
2956
Amith Yamasani483f3b02012-03-13 16:08:00 -07002957 @Override
Dianne Hackborne7991752013-01-16 17:56:46 -08002958 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08002959 String[] permissions, int flags, int userId) {
Dianne Hackborne7991752013-01-16 17:56:46 -08002960 if (!sUserManager.exists(userId)) return null;
Dianne Hackborne7991752013-01-16 17:56:46 -08002961 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
2962
2963 // writer
2964 synchronized (mPackages) {
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08002965 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
2966 boolean[] tmpBools = new boolean[permissions.length];
Dianne Hackborne7991752013-01-16 17:56:46 -08002967 if (listUninstalled) {
2968 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08002969 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
Dianne Hackborne7991752013-01-16 17:56:46 -08002970 }
2971 } else {
2972 for (PackageParser.Package pkg : mPackages.values()) {
2973 PackageSetting ps = (PackageSetting)pkg.mExtras;
2974 if (ps != null) {
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08002975 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
2976 userId);
2977 }
2978 }
2979 }
2980
2981 return new ParceledListSlice<PackageInfo>(list);
2982 }
2983 }
2984
2985 @Override
2986 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
2987 if (!sUserManager.exists(userId)) return null;
2988 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
2989
2990 // writer
2991 synchronized (mPackages) {
2992 ArrayList<ApplicationInfo> list;
2993 if (listUninstalled) {
2994 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
2995 for (PackageSetting ps : mSettings.mPackages.values()) {
2996 ApplicationInfo ai;
2997 if (ps.pkg != null) {
2998 ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
2999 ps.readUserState(userId), userId);
3000 } else {
3001 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3002 }
3003 if (ai != null) {
3004 list.add(ai);
3005 }
3006 }
3007 } else {
3008 list = new ArrayList<ApplicationInfo>(mPackages.size());
3009 for (PackageParser.Package p : mPackages.values()) {
3010 if (p.mExtras != null) {
3011 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3012 ((PackageSetting)p.mExtras).readUserState(userId), userId);
3013 if (ai != null) {
3014 list.add(ai);
Dianne Hackborne7991752013-01-16 17:56:46 -08003015 }
3016 }
3017 }
3018 }
3019
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08003020 return new ParceledListSlice<ApplicationInfo>(list);
Dianne Hackborne7991752013-01-16 17:56:46 -08003021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003022 }
3023
3024 public List<ApplicationInfo> getPersistentApplications(int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07003025 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026
Kenny Root447106f2011-03-23 11:00:15 -07003027 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003028 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07003029 final Iterator<PackageParser.Package> i = mPackages.values().iterator();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003030 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 while (i.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07003032 final PackageParser.Package p = i.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 if (p.applicationInfo != null
3034 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07003035 && (!mSafeMode || isSystemApp(p))) {
Amith Yamasani13593602012-03-22 16:16:17 -07003036 PackageSetting ps = mSettings.mPackages.get(p.packageName);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003037 if (ps != null) {
3038 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3039 ps.readUserState(userId), userId);
3040 if (ai != null) {
3041 finalList.add(ai);
3042 }
3043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003044 }
3045 }
3046 }
3047
3048 return finalList;
3049 }
3050
Amith Yamasani483f3b02012-03-13 16:08:00 -07003051 @Override
3052 public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07003053 if (!sUserManager.exists(userId)) return null;
Kenny Root447106f2011-03-23 11:00:15 -07003054 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003055 synchronized (mPackages) {
3056 final PackageParser.Provider provider = mProviders.get(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003057 PackageSetting ps = provider != null
3058 ? mSettings.mPackages.get(provider.owner.packageName)
3059 : null;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003060 return ps != null
Amith Yamasani483f3b02012-03-13 16:08:00 -07003061 && mSettings.isEnabledLPr(provider.info, flags, userId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003062 && (!mSafeMode || (provider.info.applicationInfo.flags
3063 &ApplicationInfo.FLAG_SYSTEM) != 0)
Amith Yamasani13593602012-03-22 16:16:17 -07003064 ? PackageParser.generateProviderInfo(provider, flags,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003065 ps.readUserState(userId), userId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003066 : null;
3067 }
3068 }
3069
Fred Quintana718d8a22009-04-29 17:53:20 -07003070 /**
3071 * @deprecated
3072 */
Kenny Root60f7ad82011-03-22 12:49:06 -07003073 @Deprecated
3074 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
Kenny Root447106f2011-03-23 11:00:15 -07003075 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07003077 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProviders.entrySet()
3078 .iterator();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003079 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003080 while (i.hasNext()) {
3081 Map.Entry<String, PackageParser.Provider> entry = i.next();
3082 PackageParser.Provider p = entry.getValue();
Amith Yamasani13593602012-03-22 16:16:17 -07003083 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003085 if (ps != null && p.syncable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003086 && (!mSafeMode || (p.info.applicationInfo.flags
3087 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003088 ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3089 ps.readUserState(userId), userId);
3090 if (info != null) {
3091 outNames.add(entry.getKey());
3092 outInfo.add(info);
3093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003094 }
3095 }
3096 }
3097 }
3098
3099 public List<ProviderInfo> queryContentProviders(String processName,
3100 int uid, int flags) {
3101 ArrayList<ProviderInfo> finalList = null;
3102
Kenny Root447106f2011-03-23 11:00:15 -07003103 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07003105 final Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
Amith Yamasani483f3b02012-03-13 16:08:00 -07003106 final int userId = processName != null ?
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003107 UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003108 while (i.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07003109 final PackageParser.Provider p = i.next();
Amith Yamasani13593602012-03-22 16:16:17 -07003110 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003111 if (ps != null && p.info.authority != null
Kenny Root447106f2011-03-23 11:00:15 -07003112 && (processName == null
3113 || (p.info.processName.equals(processName)
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003114 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
Amith Yamasani483f3b02012-03-13 16:08:00 -07003115 && mSettings.isEnabledLPr(p.info, flags, userId)
Kenny Root447106f2011-03-23 11:00:15 -07003116 && (!mSafeMode
3117 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003118 if (finalList == null) {
3119 finalList = new ArrayList<ProviderInfo>(3);
3120 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003121 ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3122 ps.readUserState(userId), userId);
Dianne Hackborn4428e172012-08-24 17:43:05 -07003123 if (info != null) {
3124 finalList.add(info);
3125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 }
3127 }
3128 }
3129
3130 if (finalList != null) {
3131 Collections.sort(finalList, mProviderInitOrderSorter);
3132 }
3133
3134 return finalList;
3135 }
3136
3137 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3138 int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07003139 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003140 synchronized (mPackages) {
3141 final PackageParser.Instrumentation i = mInstrumentation.get(name);
3142 return PackageParser.generateInstrumentationInfo(i, flags);
3143 }
3144 }
3145
3146 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3147 int flags) {
3148 ArrayList<InstrumentationInfo> finalList =
3149 new ArrayList<InstrumentationInfo>();
3150
Kenny Root447106f2011-03-23 11:00:15 -07003151 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003152 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07003153 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003154 while (i.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07003155 final PackageParser.Instrumentation p = i.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 if (targetPackage == null
3157 || targetPackage.equals(p.info.targetPackage)) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07003158 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3159 flags);
3160 if (ii != null) {
3161 finalList.add(ii);
3162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003163 }
3164 }
3165 }
3166
3167 return finalList;
3168 }
3169
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003170 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003171 String[] files = dir.list();
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07003172 if (files == null) {
3173 Log.d(TAG, "No files in app dir " + dir);
3174 return;
3175 }
3176
Kenny Root4dfe6ff2011-02-23 17:00:43 -08003177 if (DEBUG_PACKAGE_SCANNING) {
Joe Onorato431bb222010-10-18 19:13:23 -04003178 Log.d(TAG, "Scanning app dir " + dir);
3179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180
3181 int i;
3182 for (i=0; i<files.length; i++) {
3183 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003184 if (!isPackageFilename(files[i])) {
3185 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08003186 continue;
3187 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003188 PackageParser.Package pkg = scanPackageLI(file,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003189 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003190 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08003191 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
3192 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003193 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003194 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003195 file.delete();
3196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197 }
3198 }
3199
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003200 private static File getSettingsProblemFile() {
3201 File dataDir = Environment.getDataDirectory();
3202 File systemDir = new File(dataDir, "system");
3203 File fname = new File(systemDir, "uiderrors.txt");
3204 return fname;
3205 }
3206
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003207 static void reportSettingsProblem(int priority, String msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003209 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 FileOutputStream out = new FileOutputStream(fname, true);
3211 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003212 SimpleDateFormat formatter = new SimpleDateFormat();
3213 String dateString = formatter.format(new Date(System.currentTimeMillis()));
3214 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003215 pw.close();
3216 FileUtils.setPermissions(
3217 fname.toString(),
3218 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
3219 -1, -1);
3220 } catch (java.io.IOException e) {
3221 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003222 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 }
3224
3225 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
3226 PackageParser.Package pkg, File srcFile, int parseFlags) {
3227 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07003228 if (ps != null
3229 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07003230 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07003231 if (ps.signatures.mSignatures != null
3232 && ps.signatures.mSignatures.length != 0) {
3233 // Optimization: reuse the existing cached certificates
3234 // if the package appears to be unchanged.
3235 pkg.mSignatures = ps.signatures.mSignatures;
3236 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003237 }
Jeff Browne7600722010-04-07 18:28:23 -07003238
3239 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003240 } else {
Jeff Browne7600722010-04-07 18:28:23 -07003241 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
3242 }
3243
3244 if (!pp.collectCertificates(pkg, parseFlags)) {
3245 mLastScanError = pp.getParseError();
3246 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247 }
3248 }
3249 return true;
3250 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003252 /*
3253 * Scan a package and return the newly parsed package.
3254 * Returns null in case of errors and the error code is stored in mLastScanError
3255 */
3256 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003257 int parseFlags, int scanMode, long currentTime, UserHandle user) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003259 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003261 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003262 pp.setSeparateProcesses(mSeparateProcesses);
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07003263 pp.setOnlyCoreApps(mOnlyCore);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003265 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003266 if (pkg == null) {
3267 mLastScanError = pp.getParseError();
3268 return null;
3269 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003270 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003271 PackageSetting updatedPkg;
Kenny Root447106f2011-03-23 11:00:15 -07003272 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003273 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003274 // Look to see if we already know about this package.
3275 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08003276 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003277 // This package has been renamed to its original name. Let's
3278 // use that.
Kenny Root447106f2011-03-23 11:00:15 -07003279 ps = mSettings.peekPackageLPr(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003280 }
3281 // If there was no original package, see one for the real package name.
3282 if (ps == null) {
Kenny Root447106f2011-03-23 11:00:15 -07003283 ps = mSettings.peekPackageLPr(pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003284 }
3285 // Check to see if this package could be hiding/updating a system
3286 // package. Must look for it either under the original or real
3287 // package name depending on our state.
Kenny Rootc52d6fd2012-05-07 23:04:52 -07003288 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003290 // First check if this is a system package that may involve an update
3291 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07003292 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003293 // The path has changed from what was last scanned... check the
3294 // version of the new path against what we have stored to determine
3295 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003296 if (pkg.mVersionCode < ps.versionCode) {
3297 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003298 // Ignore entry. Skip it.
3299 Log.i(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborncef65ee2010-09-30 18:27:22 -07003300 + " ignored: updated version " + ps.versionCode
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003301 + " better than this " + pkg.mVersionCode);
Dianne Hackbornc4d27a72013-01-22 18:30:17 -08003302 if (!updatedPkg.codePath.equals(scanFile)) {
3303 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
3304 + ps.name + " changing from " + updatedPkg.codePathString
3305 + " to " + scanFile);
3306 updatedPkg.codePath = scanFile;
3307 updatedPkg.codePathString = scanFile.toString();
3308 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003309 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3310 return null;
3311 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003312 // The current app on the system partion is better than
3313 // what we have updated to on the data partition; switch
3314 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003315 // At this point, its safely assumed that package installation for
3316 // apps in system partition will go through. If not there won't be a working
3317 // version of the app
Kenny Root447106f2011-03-23 11:00:15 -07003318 // writer
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003319 synchronized (mPackages) {
3320 // Just remove the loaded entries from package lists.
3321 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003322 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003323 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003324 + "reverting from " + ps.codePathString
3325 + ": new version " + pkg.mVersionCode
3326 + " better than installed " + ps.versionCode);
Kenny Root88670d82012-05-09 15:47:35 -07003327
3328 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3329 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
Dianne Hackborn4428e172012-08-24 17:43:05 -07003330 synchronized (mInstallLock) {
Kenny Root208d3412012-05-07 19:42:35 -07003331 args.cleanUpResourcesLI();
3332 }
3333 synchronized (mPackages) {
3334 mSettings.enableSystemPackageLPw(ps.name);
3335 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337 }
3338 }
Kenny Root208d3412012-05-07 19:42:35 -07003339
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003340 if (updatedPkg != null) {
Kenny Root208d3412012-05-07 19:42:35 -07003341 // An updated system app will not have the PARSE_IS_SYSTEM flag set
3342 // initially
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003343 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
3344 }
3345 // Verify certificates against what was last scanned
3346 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003347 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003348 return null;
3349 }
Kenny Root208d3412012-05-07 19:42:35 -07003350
3351 /*
3352 * A new system app appeared, but we already had a non-system one of the
3353 * same name installed earlier.
3354 */
3355 boolean shouldHideSystemApp = false;
3356 if (updatedPkg == null && ps != null
3357 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
3358 /*
3359 * Check to make sure the signatures match first. If they don't,
3360 * wipe the installed application and its data.
3361 */
3362 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
3363 != PackageManager.SIGNATURE_MATCH) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003364 deletePackageLI(pkg.packageName, null, true, 0, null, false);
Kenny Root208d3412012-05-07 19:42:35 -07003365 ps = null;
3366 } else {
3367 /*
3368 * If the newly-added system app is an older version than the
3369 * already installed version, hide it. It will be scanned later
3370 * and re-added like an update.
3371 */
3372 if (pkg.mVersionCode < ps.versionCode) {
3373 shouldHideSystemApp = true;
3374 } else {
3375 /*
3376 * The newly found system app is a newer version that the
3377 * one previously installed. Simply remove the
3378 * already-installed application and replace it with our own
3379 * while keeping the application data.
3380 */
3381 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
3382 + ps.codePathString + ": new version " + pkg.mVersionCode
3383 + " better than installed " + ps.versionCode);
Kenny Root88670d82012-05-09 15:47:35 -07003384 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3385 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
Dianne Hackborn4428e172012-08-24 17:43:05 -07003386 synchronized (mInstallLock) {
Kenny Root208d3412012-05-07 19:42:35 -07003387 args.cleanUpResourcesLI();
3388 }
3389 }
3390 }
3391 }
3392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 // The apk is forward locked (not public) if its code and resources
3394 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003395 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003396 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003397 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07003398 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003399
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003400 String codePath = null;
3401 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003402 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
3403 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003404 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003405 } else {
3406 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003407 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003408 }
3409 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003410 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003411 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003412 codePath = pkg.mScanPath;
3413 // Set application objects path explicitly.
3414 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003415 // Note that we invoke the following method only if we are about to unpack an application
Kenny Root208d3412012-05-07 19:42:35 -07003416 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003417 | SCAN_UPDATE_SIGNATURE, currentTime, user);
Kenny Root208d3412012-05-07 19:42:35 -07003418
3419 /*
3420 * If the system app should be overridden by a previously installed
3421 * data, hide the system app now and let the /data/app scan pick it up
3422 * again.
3423 */
3424 if (shouldHideSystemApp) {
3425 synchronized (mPackages) {
3426 /*
3427 * We have to grant systems permissions before we hide, because
3428 * grantPermissions will assume the package update is trying to
3429 * expand its permissions.
3430 */
3431 grantPermissionsLPw(pkg, true);
3432 mSettings.disableSystemPackageLPw(pkg.packageName);
3433 }
3434 }
3435
3436 return scannedPkg;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 }
3438
Kenny Root85387d72010-08-26 10:13:11 -07003439 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
3440 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003441 pkg.mPath = pkg.mScanPath = destCodePath;
3442 pkg.applicationInfo.sourceDir = destCodePath;
3443 pkg.applicationInfo.publicSourceDir = destResPath;
3444 }
3445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446 private static String fixProcessName(String defProcessName,
3447 String processName, int uid) {
3448 if (processName == null) {
3449 return defProcessName;
3450 }
3451 return processName;
3452 }
3453
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003454 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003455 PackageParser.Package pkg) {
3456 if (pkgSetting.signatures.mSignatures != null) {
3457 // Already existing package. Make sure signatures match
Kenny Root447106f2011-03-23 11:00:15 -07003458 if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003459 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003460 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003461 + " signatures do not match the previously installed version; ignoring!");
3462 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 return false;
3464 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003465 }
3466 // Check for shared user signatures
3467 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
Kenny Root447106f2011-03-23 11:00:15 -07003468 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003469 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3470 Slog.e(TAG, "Package " + pkg.packageName
3471 + " has no signatures that match those in shared user "
3472 + pkgSetting.sharedUser.name + "; ignoring!");
3473 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
3474 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 }
3477 return true;
3478 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003479
Kenny Root461ff1f2011-08-09 09:43:03 -07003480 /**
3481 * Enforces that only the system UID or root's UID can call a method exposed
3482 * via Binder.
3483 *
3484 * @param message used as message if SecurityException is thrown
3485 * @throws SecurityException if the caller is not system or root
3486 */
3487 private static final void enforceSystemOrRoot(String message) {
3488 final int uid = Binder.getCallingUid();
3489 if (uid != Process.SYSTEM_UID && uid != 0) {
3490 throw new SecurityException(message);
3491 }
3492 }
3493
Dianne Hackborn661cd522011-08-22 00:26:20 -07003494 public void performBootDexOpt() {
3495 ArrayList<PackageParser.Package> pkgs = null;
3496 synchronized (mPackages) {
3497 if (mDeferredDexOpt.size() > 0) {
3498 pkgs = new ArrayList<PackageParser.Package>(mDeferredDexOpt);
3499 mDeferredDexOpt.clear();
3500 }
3501 }
3502 if (pkgs != null) {
3503 for (int i=0; i<pkgs.size(); i++) {
Dianne Hackborn58f42a52011-10-10 13:46:34 -07003504 if (!isFirstBoot()) {
3505 try {
3506 ActivityManagerNative.getDefault().showBootMessage(
3507 mContext.getResources().getString(
3508 com.android.internal.R.string.android_upgrading_apk,
3509 i+1, pkgs.size()), true);
3510 } catch (RemoteException e) {
3511 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07003512 }
3513 PackageParser.Package p = pkgs.get(i);
3514 synchronized (mInstallLock) {
3515 if (!p.mDidDexOpt) {
3516 performDexOptLI(p, false, false);
3517 }
3518 }
3519 }
3520 }
3521 }
3522
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003523 public boolean performDexOpt(String packageName) {
Kenny Root461ff1f2011-08-09 09:43:03 -07003524 enforceSystemOrRoot("Only the system can request dexopt be performed");
3525
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003526 if (!mNoDexOpt) {
3527 return false;
3528 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003529
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003530 PackageParser.Package p;
3531 synchronized (mPackages) {
3532 p = mPackages.get(packageName);
3533 if (p == null || p.mDidDexOpt) {
3534 return false;
3535 }
3536 }
3537 synchronized (mInstallLock) {
Dianne Hackborn661cd522011-08-22 00:26:20 -07003538 return performDexOptLI(p, false, false) == DEX_OPT_PERFORMED;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003539 }
3540 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003541
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003542 static final int DEX_OPT_SKIPPED = 0;
3543 static final int DEX_OPT_PERFORMED = 1;
Dianne Hackborn661cd522011-08-22 00:26:20 -07003544 static final int DEX_OPT_DEFERRED = 2;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003545 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003546
Dianne Hackborn661cd522011-08-22 00:26:20 -07003547 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003548 boolean performed = false;
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003549 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003550 String path = pkg.mScanPath;
3551 int ret = 0;
3552 try {
3553 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Dianne Hackborn661cd522011-08-22 00:26:20 -07003554 if (!forceDex && defer) {
3555 mDeferredDexOpt.add(pkg);
3556 return DEX_OPT_DEFERRED;
3557 } else {
3558 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
Kenny Root6a9b2cb2012-09-17 14:02:39 -07003559 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
3560 ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg));
Dianne Hackborn661cd522011-08-22 00:26:20 -07003561 pkg.mDidDexOpt = true;
3562 performed = true;
3563 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003564 }
3565 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003566 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003567 ret = -1;
3568 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07003569 Slog.w(TAG, "IOException reading apk: " + path, e);
3570 ret = -1;
3571 } catch (dalvik.system.StaleDexCacheError e) {
3572 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
3573 ret = -1;
3574 } catch (Exception e) {
3575 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003576 ret = -1;
3577 }
3578 if (ret < 0) {
3579 //error from installer
3580 return DEX_OPT_FAILED;
3581 }
3582 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003583
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003584 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
3585 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08003586
Kenny Root447106f2011-03-23 11:00:15 -07003587 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003588 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003589 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003590 + " to " + newPkg.packageName
3591 + ": old package not in system partition");
3592 return false;
3593 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003594 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003595 + " to " + newPkg.packageName
3596 + ": old package still exists");
3597 return false;
3598 }
3599 return true;
3600 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003601
Amith Yamasani0b285492011-04-14 17:35:23 -07003602 File getDataPathForUser(int userId) {
3603 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003604 }
Amith Yamasani0b285492011-04-14 17:35:23 -07003605
3606 private File getDataPathForPackage(String packageName, int userId) {
Kenny Root9c8625e2011-07-25 09:42:22 -07003607 /*
3608 * Until we fully support multiple users, return the directory we
3609 * previously would have. The PackageManagerTests will need to be
3610 * revised when this is changed back..
3611 */
3612 if (userId == 0) {
3613 return new File(mAppDataDir, packageName);
3614 } else {
3615 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
Amith Yamasani0f3f29b2011-05-09 14:17:14 -07003616 + File.separator + packageName);
Kenny Root9c8625e2011-07-25 09:42:22 -07003617 }
Amith Yamasani0b285492011-04-14 17:35:23 -07003618 }
3619
Nick Kralevich15069212013-01-09 15:54:56 -08003620 private int createDataDirsLI(String packageName, int uid) {
Dave Burke383fa182012-10-23 23:12:19 -07003621 int[] users = sUserManager.getUserIds();
Nick Kralevich15069212013-01-09 15:54:56 -08003622 int res = mInstaller.install(packageName, uid, uid);
Dave Burke383fa182012-10-23 23:12:19 -07003623 if (res < 0) {
3624 return res;
3625 }
3626 for (int user : users) {
3627 if (user != 0) {
3628 res = mInstaller.createUserData(packageName,
Nick Kralevich15069212013-01-09 15:54:56 -08003629 UserHandle.getUid(user, uid), user);
Dave Burke383fa182012-10-23 23:12:19 -07003630 if (res < 0) {
3631 return res;
3632 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07003633 }
3634 }
Dave Burke383fa182012-10-23 23:12:19 -07003635 return res;
Dianne Hackborn4428e172012-08-24 17:43:05 -07003636 }
3637
3638 private int removeDataDirsLI(String packageName) {
3639 int[] users = sUserManager.getUserIds();
3640 int res = 0;
3641 for (int user : users) {
3642 int resInner = mInstaller.remove(packageName, user);
3643 if (resInner < 0) {
3644 res = resInner;
3645 }
3646 }
Kenny Rootddbe50d2012-09-06 13:18:37 -07003647
3648 final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
3649 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
3650 if (!nativeLibraryFile.delete()) {
3651 Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
3652 }
3653
Dianne Hackborn4428e172012-08-24 17:43:05 -07003654 return res;
3655 }
3656
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003657 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003658 int parseFlags, int scanMode, long currentTime, UserHandle user) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003659 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08003660 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
3661 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003662 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003663 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003664 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
3665 return null;
3666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 mScanningPath = scanFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3670 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
3671 }
3672
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003673 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003674 synchronized (mPackages) {
3675 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003676 Slog.w(TAG, "*************************************************");
3677 Slog.w(TAG, "Core android package being redefined. Skipping.");
3678 Slog.w(TAG, " file=" + mScanningPath);
3679 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003680 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3681 return null;
3682 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003684 // Set up information for our fall-back user intent resolution
3685 // activity.
3686 mPlatformPackage = pkg;
3687 pkg.mVersionCode = mSdkVersion;
3688 mAndroidApplication = pkg.applicationInfo;
3689 mResolveActivity.applicationInfo = mAndroidApplication;
3690 mResolveActivity.name = ResolverActivity.class.getName();
3691 mResolveActivity.packageName = mAndroidApplication.packageName;
Dianne Hackborn8da429e2012-09-23 12:52:19 -07003692 mResolveActivity.processName = "system:ui";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003693 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
3694 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
Joe Onorato646f46e2010-11-08 15:08:56 -08003695 mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003696 mResolveActivity.exported = true;
3697 mResolveActivity.enabled = true;
3698 mResolveInfo.activityInfo = mResolveActivity;
3699 mResolveInfo.priority = 0;
3700 mResolveInfo.preferredOrder = 0;
3701 mResolveInfo.match = 0;
3702 mResolveComponentName = new ComponentName(
3703 mAndroidApplication.packageName, mResolveActivity.name);
3704 }
3705 }
3706
Kenny Root4dfe6ff2011-02-23 17:00:43 -08003707 if (DEBUG_PACKAGE_SCANNING) {
3708 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
3709 Log.d(TAG, "Scanning package " + pkg.packageName);
3710 }
3711
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003712 if (mPackages.containsKey(pkg.packageName)
3713 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003714 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 + " already installed. Skipping duplicate.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003716 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3717 return null;
3718 }
3719
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003720 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003721 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
3722 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 SharedUserSetting suid = null;
3725 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003726
Kenny Root502e9a42011-01-10 13:48:15 -08003727 if (!isSystemApp(pkg)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003728 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08003729 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003730 pkg.mRealPackage = null;
3731 pkg.mAdoptPermissions = null;
3732 }
Kenny Root502e9a42011-01-10 13:48:15 -08003733
Kenny Root447106f2011-03-23 11:00:15 -07003734 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 synchronized (mPackages) {
3736 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07003737 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
3738 if (mTmpSharedLibraries == null ||
3739 mTmpSharedLibraries.length < mSharedLibraries.size()) {
3740 mTmpSharedLibraries = new String[mSharedLibraries.size()];
3741 }
3742 int num = 0;
3743 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
3744 for (int i=0; i<N; i++) {
Kenny Root447106f2011-03-23 11:00:15 -07003745 final String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003747 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07003749 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003750 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
3751 return null;
3752 }
Dianne Hackborn49237342009-08-27 20:08:01 -07003753 mTmpSharedLibraries[num] = file;
3754 num++;
3755 }
3756 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
3757 for (int i=0; i<N; i++) {
Kenny Root447106f2011-03-23 11:00:15 -07003758 final String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
Dianne Hackborn49237342009-08-27 20:08:01 -07003759 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003760 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07003761 + " desires unavailable shared library "
3762 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
3763 } else {
3764 mTmpSharedLibraries[num] = file;
3765 num++;
3766 }
3767 }
3768 if (num > 0) {
3769 pkg.usesLibraryFiles = new String[num];
3770 System.arraycopy(mTmpSharedLibraries, 0,
3771 pkg.usesLibraryFiles, 0, num);
3772 }
Kenny Root1683afa2011-01-07 14:27:50 -08003773 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003775 if (pkg.mSharedUserId != null) {
Kenny Root447106f2011-03-23 11:00:15 -07003776 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003777 pkg.applicationInfo.flags, true);
3778 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003779 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003780 + " for shared user failed");
3781 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3782 return null;
3783 }
Kenny Root4dfe6ff2011-02-23 17:00:43 -08003784 if (DEBUG_PACKAGE_SCANNING) {
3785 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
3786 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
3787 + "): packages=" + suid.packages);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003788 }
3789 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003790
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003791 // Check if we are renaming from an original package name.
3792 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003793 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08003794 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003795 // This package may need to be renamed to a previously
3796 // installed name. Let's check on that...
Kenny Root447106f2011-03-23 11:00:15 -07003797 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08003798 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003799 // This package had originally been installed as the
3800 // original name, and we have already taken care of
3801 // transitioning to the new one. Just update the new
3802 // one to continue using the old name.
3803 realName = pkg.mRealPackage;
3804 if (!pkg.packageName.equals(renamed)) {
3805 // Callers into this function may have already taken
3806 // care of renaming the package; only do it here if
3807 // it is not already done.
3808 pkg.setPackageName(renamed);
3809 }
3810
Dianne Hackbornc1552392010-03-03 16:19:01 -08003811 } else {
3812 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
Kenny Root447106f2011-03-23 11:00:15 -07003813 if ((origPackage = mSettings.peekPackageLPr(
Dianne Hackbornc1552392010-03-03 16:19:01 -08003814 pkg.mOriginalPackages.get(i))) != null) {
3815 // We do have the package already installed under its
3816 // original name... should we use it?
Kenny Root447106f2011-03-23 11:00:15 -07003817 if (!verifyPackageUpdateLPr(origPackage, pkg)) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08003818 // New package is not compatible with original.
3819 origPackage = null;
3820 continue;
3821 } else if (origPackage.sharedUser != null) {
3822 // Make sure uid is compatible between packages.
3823 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003824 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003825 + " to " + pkg.packageName + ": old uid "
3826 + origPackage.sharedUser.name
3827 + " differs from " + pkg.mSharedUserId);
3828 origPackage = null;
3829 continue;
3830 }
3831 } else {
3832 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3833 + pkg.packageName + " to old name " + origPackage.name);
3834 }
3835 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003836 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003837 }
3838 }
3839 }
3840
3841 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003842 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003843 + " was transferred to another, but its .apk remains");
3844 }
3845
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003846 // Just create the setting, don't add it yet. For already existing packages
3847 // the PkgSetting exists already and doesn't have to be created.
Kenny Root447106f2011-03-23 11:00:15 -07003848 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07003849 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003850 pkg.applicationInfo.flags, user, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003852 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003853 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3854 return null;
3855 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003856
3857 if (pkgSetting.origPackage != null) {
3858 // If we are first transitioning from an original package,
3859 // fix up the new package's name now. We need to do this after
3860 // looking up the package under its new name, so getPackageLP
3861 // can take care of fiddling things correctly.
3862 pkg.setPackageName(origPackage.name);
3863
3864 // File a report about this.
3865 String msg = "New package " + pkgSetting.realName
3866 + " renamed to replace old package " + pkgSetting.name;
3867 reportSettingsProblem(Log.WARN, msg);
3868
3869 // Make a note of it.
3870 mTransferedPackages.add(origPackage.name);
3871
3872 // No longer need to retain this.
3873 pkgSetting.origPackage = null;
3874 }
3875
3876 if (realName != null) {
3877 // Make a note of it.
3878 mTransferedPackages.add(pkg.packageName);
3879 }
3880
Kenny Rootc52d6fd2012-05-07 23:04:52 -07003881 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3883 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003884
Amith Yamasani13593602012-03-22 16:16:17 -07003885 pkg.applicationInfo.uid = pkgSetting.appId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003887
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003888 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003889 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003890 return null;
3891 }
3892 // The signature has changed, but this package is in the system
3893 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003894 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895 // However... if this package is part of a shared user, but it
3896 // doesn't match the signature of the shared user, let's fail.
3897 // What this means is that you can't change the signatures
3898 // associated with an overall shared user, which doesn't seem all
3899 // that unreasonable.
3900 if (pkgSetting.sharedUser != null) {
Kenny Root447106f2011-03-23 11:00:15 -07003901 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003902 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3903 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3905 return null;
3906 }
3907 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003908 // File a report about this.
3909 String msg = "System package " + pkg.packageName
3910 + " signature changed; retaining data.";
3911 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003913
The Android Open Source Project10592532009-03-18 17:39:46 -07003914 // Verify that this new package doesn't have any content providers
3915 // that conflict with existing packages. Only do this if the
3916 // package isn't already installed, since we don't want to break
3917 // things that are installed.
3918 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
Kenny Root62cc6902011-02-23 16:49:21 -08003919 final int N = pkg.providers.size();
The Android Open Source Project10592532009-03-18 17:39:46 -07003920 int i;
3921 for (i=0; i<N; i++) {
3922 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003923 if (p.info.authority != null) {
3924 String names[] = p.info.authority.split(";");
3925 for (int j = 0; j < names.length; j++) {
3926 if (mProviders.containsKey(names[j])) {
3927 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003928 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003929 " (in package " + pkg.applicationInfo.packageName +
3930 ") is already used by "
3931 + ((other != null && other.getComponentName() != null)
3932 ? other.getComponentName().getPackageName() : "?"));
3933 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3934 return null;
3935 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003936 }
3937 }
3938 }
3939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940
Kenny Root447106f2011-03-23 11:00:15 -07003941 if (pkg.mAdoptPermissions != null) {
3942 // This package wants to adopt ownership of permissions from
3943 // another package.
3944 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
3945 final String origName = pkg.mAdoptPermissions.get(i);
3946 final PackageSetting orig = mSettings.peekPackageLPr(origName);
3947 if (orig != null) {
3948 if (verifyPackageUpdateLPr(orig, pkg)) {
3949 Slog.i(TAG, "Adopting permissions from " + origName + " to "
3950 + pkg.packageName);
3951 mSettings.transferPermissionsLPw(origName, pkg.packageName);
3952 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003953 }
3954 }
3955 }
3956 }
Kenny Root447106f2011-03-23 11:00:15 -07003957
3958 final String pkgName = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003959
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003960 final long scanFileTime = scanFile.lastModified();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003961 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 pkg.applicationInfo.processName = fixProcessName(
3963 pkg.applicationInfo.packageName,
3964 pkg.applicationInfo.processName,
3965 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003966
3967 File dataPath;
3968 if (mPlatformPackage == pkg) {
3969 // The system package is special.
3970 dataPath = new File (Environment.getDataDirectory(), "system");
3971 pkg.applicationInfo.dataDir = dataPath.getPath();
3972 } else {
3973 // This is a normal package, need to make its data directory.
Dave Burke383fa182012-10-23 23:12:19 -07003974 dataPath = getDataPathForPackage(pkg.packageName, 0);
Dianne Hackbornd0c5f512012-06-07 16:53:59 -07003975
Dave Burke383fa182012-10-23 23:12:19 -07003976 boolean uidError = false;
3977
3978 if (dataPath.exists()) {
3979 int currentUid = 0;
3980 try {
3981 StructStat stat = Libcore.os.stat(dataPath.getPath());
3982 currentUid = stat.st_uid;
3983 } catch (ErrnoException e) {
3984 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003985 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003986
Dave Burke383fa182012-10-23 23:12:19 -07003987 // If we have mismatched owners for the data path, we have a problem.
3988 if (currentUid != pkg.applicationInfo.uid) {
3989 boolean recovered = false;
3990 if (currentUid == 0) {
3991 // The directory somehow became owned by root. Wow.
3992 // This is probably because the system was stopped while
3993 // installd was in the middle of messing with its libs
3994 // directory. Ask installd to fix that.
3995 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
3996 pkg.applicationInfo.uid);
3997 if (ret >= 0) {
3998 recovered = true;
3999 String msg = "Package " + pkg.packageName
4000 + " unexpectedly changed to uid 0; recovered to " +
4001 + pkg.applicationInfo.uid;
4002 reportSettingsProblem(Log.WARN, msg);
4003 }
4004 }
4005 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4006 || (scanMode&SCAN_BOOTING) != 0)) {
4007 // If this is a system app, we can at least delete its
4008 // current data so the application will still work.
4009 int ret = removeDataDirsLI(pkgName);
4010 if (ret >= 0) {
4011 // TODO: Kill the processes first
4012 // Old data gone!
4013 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4014 ? "System package " : "Third party package ";
4015 String msg = prefix + pkg.packageName
4016 + " has changed from uid: "
4017 + currentUid + " to "
4018 + pkg.applicationInfo.uid + "; old data erased";
4019 reportSettingsProblem(Log.WARN, msg);
4020 recovered = true;
4021
4022 // And now re-install the app.
Nick Kralevich15069212013-01-09 15:54:56 -08004023 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid);
Dave Burke383fa182012-10-23 23:12:19 -07004024 if (ret == -1) {
4025 // Ack should not happen!
4026 msg = prefix + pkg.packageName
4027 + " could not have data directory re-created after delete.";
4028 reportSettingsProblem(Log.WARN, msg);
4029 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4030 return null;
4031 }
4032 }
4033 if (!recovered) {
4034 mHasSystemUidErrors = true;
4035 }
4036 } else if (!recovered) {
4037 // If we allow this install to proceed, we will be broken.
4038 // Abort, abort!
4039 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
4040 return null;
4041 }
4042 if (!recovered) {
4043 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
4044 + pkg.applicationInfo.uid + "/fs_"
4045 + currentUid;
4046 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
4047 String msg = "Package " + pkg.packageName
4048 + " has mismatched uid: "
4049 + currentUid + " on disk, "
4050 + pkg.applicationInfo.uid + " in settings";
4051 // writer
4052 synchronized (mPackages) {
4053 mSettings.mReadMessages.append(msg);
4054 mSettings.mReadMessages.append('\n');
4055 uidError = true;
4056 if (!pkgSetting.uidError) {
4057 reportSettingsProblem(Log.ERROR, msg);
4058 }
4059 }
4060 }
4061 }
Kenny Root4525f5b2012-10-22 14:24:23 -07004062 pkg.applicationInfo.dataDir = dataPath.getPath();
Dave Burke383fa182012-10-23 23:12:19 -07004063 } else {
4064 if (DEBUG_PACKAGE_SCANNING) {
4065 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4066 Log.v(TAG, "Want this data dir: " + dataPath);
4067 }
Nick Kralevich15069212013-01-09 15:54:56 -08004068 //invoke installer to do the actual installation
4069 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid);
Dave Burke383fa182012-10-23 23:12:19 -07004070 if (ret < 0) {
4071 // Error from installer
4072 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4073 return null;
4074 }
4075
4076 if (dataPath.exists()) {
4077 pkg.applicationInfo.dataDir = dataPath.getPath();
4078 } else {
4079 Slog.w(TAG, "Unable to create data directory: " + dataPath);
4080 pkg.applicationInfo.dataDir = null;
4081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004082 }
Kenny Root85387d72010-08-26 10:13:11 -07004083
4084 /*
Dave Burke383fa182012-10-23 23:12:19 -07004085 * Set the data dir to the default "/data/data/<package name>/lib"
4086 * if we got here without anyone telling us different (e.g., apps
4087 * stored on SD card have their native libraries stored in the ASEC
4088 * container with the APK).
4089 *
4090 * This happens during an upgrade from a package settings file that
4091 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07004092 */
Dave Burke383fa182012-10-23 23:12:19 -07004093 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
Kenny Rootbd135c12010-10-05 12:26:27 -07004094 if (pkgSetting.nativeLibraryPathString == null) {
Kenny Rootddbe50d2012-09-06 13:18:37 -07004095 setInternalAppNativeLibraryPath(pkg, pkgSetting);
Kenny Rootbd135c12010-10-05 12:26:27 -07004096 } else {
4097 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
4098 }
Kenny Root85387d72010-08-26 10:13:11 -07004099 }
Dave Burke383fa182012-10-23 23:12:19 -07004100
4101 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 }
4103
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004104 String path = scanFile.getPath();
4105 /* Note: We don't want to unpack the native binaries for
4106 * system applications, unless they have been updated
4107 * (the binaries are already under /system/lib).
4108 * Also, don't unpack libs for apps on the external card
4109 * since they should have their libraries in the ASEC
4110 * container already.
4111 *
4112 * In other words, we're going to unpack the binaries
4113 * only for non-system apps and system app upgrades.
4114 */
4115 if (pkg.applicationInfo.nativeLibraryDir != null) {
4116 try {
Kenny Rootddbe50d2012-09-06 13:18:37 -07004117 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
Kenny Root5832ead2011-08-02 15:47:08 -07004118 final String dataPathString = dataPath.getCanonicalPath();
Kenny Roote68d58a2010-10-18 16:08:54 -07004119
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004120 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4121 /*
4122 * Upgrading from a previous version of the OS sometimes
4123 * leaves native libraries in the /data/data/<app>/lib
4124 * directory for system apps even when they shouldn't be.
4125 * Recent changes in the JNI library search path
4126 * necessitates we remove those to match previous behavior.
4127 */
4128 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
4129 Log.i(TAG, "removed obsolete native libraries for system package "
4130 + path);
Kenny Root831baa22010-10-05 12:29:25 -07004131 }
Kenny Roota3e90792012-10-18 10:58:36 -07004132 } else {
4133 if (!isForwardLocked(pkg) && !isExternal(pkg)) {
4134 /*
4135 * Update native library dir if it starts with
4136 * /data/data
4137 */
4138 if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
4139 setInternalAppNativeLibraryPath(pkg, pkgSetting);
4140 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
4141 }
Kenny Root66269ea2011-07-12 14:14:01 -07004142
Kenny Roota3e90792012-10-18 10:58:36 -07004143 try {
4144 if (copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir) != PackageManager.INSTALL_SUCCEEDED) {
4145 Slog.e(TAG, "Unable to copy native libraries");
4146 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4147 return null;
4148 }
4149 } catch (IOException e) {
4150 Slog.e(TAG, "Unable to copy native libraries", e);
Kenny Rootddbe50d2012-09-06 13:18:37 -07004151 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4152 return null;
4153 }
Kenny Rootddbe50d2012-09-06 13:18:37 -07004154 }
4155
Dianne Hackborn40e9f292012-11-27 19:12:23 -08004156 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
Kenny Roota3e90792012-10-18 10:58:36 -07004157 final int[] userIds = sUserManager.getUserIds();
4158 synchronized (mInstallLock) {
4159 for (int userId : userIds) {
4160 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
4161 pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
4162 Slog.w(TAG, "Failed linking native library dir (user=" + userId
4163 + ")");
4164 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4165 return null;
4166 }
4167 }
Nick Kralevich7de350a2012-09-07 15:48:11 -07004168 }
Kenny Root831baa22010-10-05 12:29:25 -07004169 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004170 } catch (IOException ioe) {
Kenny Rootddbe50d2012-09-06 13:18:37 -07004171 Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004172 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004173 }
4174 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004175
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004176 if ((scanMode&SCAN_NO_DEX) == 0) {
Dianne Hackborn661cd522011-08-22 00:26:20 -07004177 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0)
4178 == DEX_OPT_FAILED) {
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004179 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
4180 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004181 }
4182 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004184 if (mFactoryTest && pkg.requestedPermissions.contains(
4185 android.Manifest.permission.FACTORY_TEST)) {
4186 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
4187 }
4188
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004189 // Request the ActivityManager to kill the process(only for existing packages)
4190 // so that we do not end up in a confused state while the user is still using the older
4191 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004192 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004193 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004194 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004195 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004196
Kenny Root447106f2011-03-23 11:00:15 -07004197 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004198 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004199 // We don't expect installation to fail beyond this point,
4200 if ((scanMode&SCAN_MONITOR) != 0) {
4201 mAppDirs.put(pkg.mPath, pkg);
4202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004203 // Add the new setting to mSettings
Kenny Root447106f2011-03-23 11:00:15 -07004204 mSettings.insertPackageSettingLPw(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07004206 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004207 // Make sure we don't accidentally delete its data.
Jeff Sharkey752cd922012-09-23 16:25:12 -07004208 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
4209 while (iter.hasNext()) {
4210 PackageCleanItem item = iter.next();
4211 if (pkgName.equals(item.packageName)) {
4212 iter.remove();
4213 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07004214 }
Jeff Sharkey752cd922012-09-23 16:25:12 -07004215
Dianne Hackborn78d6883692010-10-07 01:12:46 -07004216 // Take care of first install / last update times.
4217 if (currentTime != 0) {
4218 if (pkgSetting.firstInstallTime == 0) {
4219 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
4220 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
4221 pkgSetting.lastUpdateTime = currentTime;
4222 }
4223 } else if (pkgSetting.firstInstallTime == 0) {
4224 // We need *something*. Take time time stamp of the file.
4225 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
4226 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
4227 if (scanFileTime != pkgSetting.timeStamp) {
4228 // A package on the system image has changed; consider this
4229 // to be an update.
4230 pkgSetting.lastUpdateTime = scanFileTime;
4231 }
4232 }
4233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 int N = pkg.providers.size();
4235 StringBuilder r = null;
4236 int i;
4237 for (i=0; i<N; i++) {
4238 PackageParser.Provider p = pkg.providers.get(i);
4239 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
4240 p.info.processName, pkg.applicationInfo.uid);
4241 mProvidersByComponent.put(new ComponentName(p.info.packageName,
4242 p.info.name), p);
4243 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08004244 if (p.info.authority != null) {
4245 String names[] = p.info.authority.split(";");
4246 p.info.authority = null;
4247 for (int j = 0; j < names.length; j++) {
4248 if (j == 1 && p.syncable) {
4249 // We only want the first authority for a provider to possibly be
4250 // syncable, so if we already added this provider using a different
4251 // authority clear the syncable flag. We copy the provider before
4252 // changing it because the mProviders object contains a reference
4253 // to a provider that we don't want to change.
4254 // Only do this for the second authority since the resulting provider
4255 // object can be the same for all future authorities for this provider.
4256 p = new PackageParser.Provider(p);
4257 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08004259 if (!mProviders.containsKey(names[j])) {
4260 mProviders.put(names[j], p);
4261 if (p.info.authority == null) {
4262 p.info.authority = names[j];
4263 } else {
4264 p.info.authority = p.info.authority + ";" + names[j];
4265 }
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004266 if (DEBUG_PACKAGE_SCANNING) {
4267 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4268 Log.d(TAG, "Registered content provider: " + names[j]
4269 + ", className = " + p.info.name + ", isSyncable = "
4270 + p.info.isSyncable);
4271 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08004272 } else {
4273 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004274 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08004275 " (in package " + pkg.applicationInfo.packageName +
4276 "): name already used by "
4277 + ((other != null && other.getComponentName() != null)
4278 ? other.getComponentName().getPackageName() : "?"));
4279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004280 }
4281 }
4282 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4283 if (r == null) {
4284 r = new StringBuilder(256);
4285 } else {
4286 r.append(' ');
4287 }
4288 r.append(p.info.name);
4289 }
4290 }
4291 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004292 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004293 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004295 N = pkg.services.size();
4296 r = null;
4297 for (i=0; i<N; i++) {
4298 PackageParser.Service s = pkg.services.get(i);
4299 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
4300 s.info.processName, pkg.applicationInfo.uid);
4301 mServices.addService(s);
4302 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4303 if (r == null) {
4304 r = new StringBuilder(256);
4305 } else {
4306 r.append(' ');
4307 }
4308 r.append(s.info.name);
4309 }
4310 }
4311 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004312 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004313 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004315 N = pkg.receivers.size();
4316 r = null;
4317 for (i=0; i<N; i++) {
4318 PackageParser.Activity a = pkg.receivers.get(i);
4319 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
4320 a.info.processName, pkg.applicationInfo.uid);
4321 mReceivers.addActivity(a, "receiver");
4322 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4323 if (r == null) {
4324 r = new StringBuilder(256);
4325 } else {
4326 r.append(' ');
4327 }
4328 r.append(a.info.name);
4329 }
4330 }
4331 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004332 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004333 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004335 N = pkg.activities.size();
4336 r = null;
4337 for (i=0; i<N; i++) {
4338 PackageParser.Activity a = pkg.activities.get(i);
4339 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
4340 a.info.processName, pkg.applicationInfo.uid);
4341 mActivities.addActivity(a, "activity");
4342 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4343 if (r == null) {
4344 r = new StringBuilder(256);
4345 } else {
4346 r.append(' ');
4347 }
4348 r.append(a.info.name);
4349 }
4350 }
4351 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004352 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004353 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004355 N = pkg.permissionGroups.size();
4356 r = null;
4357 for (i=0; i<N; i++) {
4358 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
4359 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
4360 if (cur == null) {
4361 mPermissionGroups.put(pg.info.name, pg);
4362 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4363 if (r == null) {
4364 r = new StringBuilder(256);
4365 } else {
4366 r.append(' ');
4367 }
4368 r.append(pg.info.name);
4369 }
4370 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004371 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004372 + pg.info.packageName + " ignored: original from "
4373 + cur.info.packageName);
4374 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4375 if (r == null) {
4376 r = new StringBuilder(256);
4377 } else {
4378 r.append(' ');
4379 }
4380 r.append("DUP:");
4381 r.append(pg.info.name);
4382 }
4383 }
4384 }
4385 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004386 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004387 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004389 N = pkg.permissions.size();
4390 r = null;
4391 for (i=0; i<N; i++) {
4392 PackageParser.Permission p = pkg.permissions.get(i);
4393 HashMap<String, BasePermission> permissionMap =
4394 p.tree ? mSettings.mPermissionTrees
4395 : mSettings.mPermissions;
4396 p.group = mPermissionGroups.get(p.info.group);
4397 if (p.info.group == null || p.group != null) {
4398 BasePermission bp = permissionMap.get(p.info.name);
4399 if (bp == null) {
4400 bp = new BasePermission(p.info.name, p.info.packageName,
4401 BasePermission.TYPE_NORMAL);
4402 permissionMap.put(p.info.name, bp);
4403 }
4404 if (bp.perm == null) {
4405 if (bp.sourcePackage == null
4406 || bp.sourcePackage.equals(p.info.packageName)) {
4407 BasePermission tree = findPermissionTreeLP(p.info.name);
4408 if (tree == null
4409 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004410 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004411 bp.perm = p;
4412 bp.uid = pkg.applicationInfo.uid;
4413 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4414 if (r == null) {
4415 r = new StringBuilder(256);
4416 } else {
4417 r.append(' ');
4418 }
4419 r.append(p.info.name);
4420 }
4421 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004422 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004423 + p.info.packageName + " ignored: base tree "
4424 + tree.name + " is from package "
4425 + tree.sourcePackage);
4426 }
4427 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004428 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004429 + p.info.packageName + " ignored: original from "
4430 + bp.sourcePackage);
4431 }
4432 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4433 if (r == null) {
4434 r = new StringBuilder(256);
4435 } else {
4436 r.append(' ');
4437 }
4438 r.append("DUP:");
4439 r.append(p.info.name);
4440 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004441 if (bp.perm == p) {
4442 bp.protectionLevel = p.info.protectionLevel;
4443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004444 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004445 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004446 + p.info.packageName + " ignored: no group "
4447 + p.group);
4448 }
4449 }
4450 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004451 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004452 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004454 N = pkg.instrumentation.size();
4455 r = null;
4456 for (i=0; i<N; i++) {
4457 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
4458 a.info.packageName = pkg.applicationInfo.packageName;
4459 a.info.sourceDir = pkg.applicationInfo.sourceDir;
4460 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
4461 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07004462 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004463 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004464 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4465 if (r == null) {
4466 r = new StringBuilder(256);
4467 } else {
4468 r.append(' ');
4469 }
4470 r.append(a.info.name);
4471 }
4472 }
4473 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004474 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004475 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004476
Dianne Hackborn854060af2009-07-09 18:14:31 -07004477 if (pkg.protectedBroadcasts != null) {
4478 N = pkg.protectedBroadcasts.size();
4479 for (i=0; i<N; i++) {
4480 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
4481 }
4482 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004484 pkgSetting.setTimeStamp(scanFileTime);
4485 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004487 return pkg;
4488 }
4489
Kenny Rootddbe50d2012-09-06 13:18:37 -07004490 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
4491 PackageSetting pkgSetting) {
4492 final String apkLibPath = getApkName(pkgSetting.codePathString);
4493 final String nativeLibraryPath = new File(mAppLibInstallDir, apkLibPath).getPath();
4494 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
4495 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
4496 }
4497
4498 private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir)
4499 throws IOException {
4500 if (!nativeLibraryDir.isDirectory()) {
4501 nativeLibraryDir.delete();
Kenny Root9bbd70a2012-09-10 11:13:36 -07004502
Kenny Rootddbe50d2012-09-06 13:18:37 -07004503 if (!nativeLibraryDir.mkdir()) {
4504 throw new IOException("Cannot create " + nativeLibraryDir.getPath());
4505 }
Kenny Root9bbd70a2012-09-10 11:13:36 -07004506
Kenny Rootddbe50d2012-09-06 13:18:37 -07004507 try {
4508 Libcore.os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH
4509 | S_IXOTH);
4510 } catch (ErrnoException e) {
4511 throw new IOException("Cannot chmod native library directory "
4512 + nativeLibraryDir.getPath(), e);
4513 }
Kenny Root9bbd70a2012-09-10 11:13:36 -07004514 } else if (!SELinux.restorecon(nativeLibraryDir)) {
4515 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
Kenny Rootddbe50d2012-09-06 13:18:37 -07004516 }
4517
4518 /*
4519 * If this is an internal application or our nativeLibraryPath points to
4520 * the app-lib directory, unpack the libraries if necessary.
4521 */
4522 return NativeLibraryHelper.copyNativeBinariesIfNeededLI(scanFile, nativeLibraryDir);
4523 }
4524
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004525 private void killApplication(String pkgName, int appId) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004526 // Request the ActivityManager to kill the process(only for existing packages)
4527 // so that we do not end up in a confused state while the user is still using the older
4528 // version of the application while the new one gets installed.
4529 IActivityManager am = ActivityManagerNative.getDefault();
4530 if (am != null) {
4531 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004532 am.killApplicationWithAppId(pkgName, appId);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004533 } catch (RemoteException e) {
4534 }
4535 }
4536 }
4537
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004538 void removePackageLI(PackageSetting ps, boolean chatty) {
4539 if (DEBUG_INSTALL) {
4540 if (chatty)
4541 Log.d(TAG, "Removing package " + ps.name);
4542 }
4543
4544 // writer
4545 synchronized (mPackages) {
4546 mPackages.remove(ps.name);
4547 if (ps.codePathString != null) {
4548 mAppDirs.remove(ps.codePathString);
4549 }
4550
4551 final PackageParser.Package pkg = ps.pkg;
4552 if (pkg != null) {
4553 cleanPackageDataStructuresLILPw(pkg, chatty);
4554 }
4555 }
4556 }
4557
4558 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004559 if (DEBUG_INSTALL) {
4560 if (chatty)
4561 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
4562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004563
Kenny Root447106f2011-03-23 11:00:15 -07004564 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004565 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004566 mPackages.remove(pkg.applicationInfo.packageName);
4567 if (pkg.mPath != null) {
4568 mAppDirs.remove(pkg.mPath);
4569 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004570 cleanPackageDataStructuresLILPw(pkg, chatty);
4571 }
4572 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004573
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004574 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
4575 int N = pkg.providers.size();
4576 StringBuilder r = null;
4577 int i;
4578 for (i=0; i<N; i++) {
4579 PackageParser.Provider p = pkg.providers.get(i);
4580 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
4581 p.info.name));
4582 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004583
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004584 /* There was another ContentProvider with this authority when
4585 * this app was installed so this authority is null,
4586 * Ignore it as we don't have to unregister the provider.
4587 */
4588 continue;
4589 }
4590 String names[] = p.info.authority.split(";");
4591 for (int j = 0; j < names.length; j++) {
4592 if (mProviders.get(names[j]) == p) {
4593 mProviders.remove(names[j]);
4594 if (DEBUG_REMOVE) {
4595 if (chatty)
4596 Log.d(TAG, "Unregistered content provider: " + names[j]
4597 + ", className = " + p.info.name + ", isSyncable = "
4598 + p.info.isSyncable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004599 }
4600 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004601 }
4602 if (chatty) {
4603 if (r == null) {
4604 r = new StringBuilder(256);
4605 } else {
4606 r.append(' ');
4607 }
4608 r.append(p.info.name);
4609 }
4610 }
4611 if (r != null) {
4612 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r);
4613 }
4614
4615 N = pkg.services.size();
4616 r = null;
4617 for (i=0; i<N; i++) {
4618 PackageParser.Service s = pkg.services.get(i);
4619 mServices.removeService(s);
4620 if (chatty) {
4621 if (r == null) {
4622 r = new StringBuilder(256);
4623 } else {
4624 r.append(' ');
4625 }
4626 r.append(s.info.name);
4627 }
4628 }
4629 if (r != null) {
4630 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r);
4631 }
4632
4633 N = pkg.receivers.size();
4634 r = null;
4635 for (i=0; i<N; i++) {
4636 PackageParser.Activity a = pkg.receivers.get(i);
4637 mReceivers.removeActivity(a, "receiver");
4638 if (chatty) {
4639 if (r == null) {
4640 r = new StringBuilder(256);
4641 } else {
4642 r.append(' ');
4643 }
4644 r.append(a.info.name);
4645 }
4646 }
4647 if (r != null) {
4648 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r);
4649 }
4650
4651 N = pkg.activities.size();
4652 r = null;
4653 for (i=0; i<N; i++) {
4654 PackageParser.Activity a = pkg.activities.get(i);
4655 mActivities.removeActivity(a, "activity");
4656 if (chatty) {
4657 if (r == null) {
4658 r = new StringBuilder(256);
4659 } else {
4660 r.append(' ');
4661 }
4662 r.append(a.info.name);
4663 }
4664 }
4665 if (r != null) {
4666 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r);
4667 }
4668
4669 N = pkg.permissions.size();
4670 r = null;
4671 for (i=0; i<N; i++) {
4672 PackageParser.Permission p = pkg.permissions.get(i);
4673 BasePermission bp = mSettings.mPermissions.get(p.info.name);
4674 if (bp == null) {
4675 bp = mSettings.mPermissionTrees.get(p.info.name);
4676 }
4677 if (bp != null && bp.perm == p) {
4678 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004679 if (chatty) {
4680 if (r == null) {
4681 r = new StringBuilder(256);
4682 } else {
4683 r.append(' ');
4684 }
4685 r.append(p.info.name);
4686 }
4687 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004688 }
4689 if (r != null) {
4690 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
4691 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004692
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004693 N = pkg.instrumentation.size();
4694 r = null;
4695 for (i=0; i<N; i++) {
4696 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
4697 mInstrumentation.remove(a.getComponentName());
4698 if (chatty) {
4699 if (r == null) {
4700 r = new StringBuilder(256);
4701 } else {
4702 r.append(' ');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004703 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004704 r.append(a.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004705 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004706 }
4707 if (r != null) {
4708 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004709 }
4710 }
4711
4712 private static final boolean isPackageFilename(String name) {
4713 return name != null && name.endsWith(".apk");
4714 }
4715
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004716 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
4717 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
4718 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
4719 return true;
4720 }
4721 }
4722 return false;
4723 }
Dianne Hackborne639da72012-02-21 15:11:13 -08004724
4725 static final int UPDATE_PERMISSIONS_ALL = 1<<0;
4726 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
4727 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
4728
Kenny Root447106f2011-03-23 11:00:15 -07004729 private void updatePermissionsLPw(String changingPkg,
Dianne Hackborne639da72012-02-21 15:11:13 -08004730 PackageParser.Package pkgInfo, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004731 // Make sure there are no dangling permission trees.
Kenny Root447106f2011-03-23 11:00:15 -07004732 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004733 while (it.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07004734 final BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004735 if (bp.packageSetting == null) {
4736 // We may not yet have parsed the package, so just see if
4737 // we still know about its settings.
4738 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4739 }
4740 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004741 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004742 + " from package " + bp.sourcePackage);
4743 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004744 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4745 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4746 Slog.i(TAG, "Removing old permission tree: " + bp.name
4747 + " from package " + bp.sourcePackage);
Dianne Hackborne639da72012-02-21 15:11:13 -08004748 flags |= UPDATE_PERMISSIONS_ALL;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004749 it.remove();
4750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004751 }
4752 }
4753
4754 // Make sure all dynamic permissions have been assigned to a package,
4755 // and make sure there are no dangling permissions.
4756 it = mSettings.mPermissions.values().iterator();
4757 while (it.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07004758 final BasePermission bp = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004759 if (bp.type == BasePermission.TYPE_DYNAMIC) {
4760 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
4761 + bp.name + " pkg=" + bp.sourcePackage
4762 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004763 if (bp.packageSetting == null && bp.pendingInfo != null) {
Kenny Root447106f2011-03-23 11:00:15 -07004764 final BasePermission tree = findPermissionTreeLP(bp.name);
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07004765 if (tree != null && tree.perm != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004766 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004767 bp.perm = new PackageParser.Permission(tree.perm.owner,
4768 new PermissionInfo(bp.pendingInfo));
4769 bp.perm.info.packageName = tree.perm.info.packageName;
4770 bp.perm.info.name = bp.name;
4771 bp.uid = tree.uid;
4772 }
4773 }
4774 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004775 if (bp.packageSetting == null) {
4776 // We may not yet have parsed the package, so just see if
4777 // we still know about its settings.
4778 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4779 }
4780 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004781 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004782 + " from package " + bp.sourcePackage);
4783 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004784 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4785 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4786 Slog.i(TAG, "Removing old permission: " + bp.name
4787 + " from package " + bp.sourcePackage);
Dianne Hackborne639da72012-02-21 15:11:13 -08004788 flags |= UPDATE_PERMISSIONS_ALL;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004789 it.remove();
4790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004791 }
4792 }
4793
4794 // Now update the permissions for all packages, in particular
4795 // replace the granted permissions of the system packages.
Dianne Hackborne639da72012-02-21 15:11:13 -08004796 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004797 for (PackageParser.Package pkg : mPackages.values()) {
4798 if (pkg != pkgInfo) {
Dianne Hackborne639da72012-02-21 15:11:13 -08004799 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004800 }
4801 }
4802 }
4803
4804 if (pkgInfo != null) {
Dianne Hackborne639da72012-02-21 15:11:13 -08004805 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004806 }
4807 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004808
Kenny Root447106f2011-03-23 11:00:15 -07004809 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
4810 final PackageSetting ps = (PackageSetting) pkg.mExtras;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004811 if (ps == null) {
4812 return;
4813 }
4814 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackborne639da72012-02-21 15:11:13 -08004815 HashSet<String> origPermissions = gp.grantedPermissions;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004816 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004818 if (replace) {
4819 ps.permissionsFixed = false;
4820 if (gp == ps) {
Dianne Hackborne639da72012-02-21 15:11:13 -08004821 origPermissions = new HashSet<String>(gp.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004822 gp.grantedPermissions.clear();
4823 gp.gids = mGlobalGids;
4824 }
4825 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004827 if (gp.gids == null) {
4828 gp.gids = mGlobalGids;
4829 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004831 final int N = pkg.requestedPermissions.size();
4832 for (int i=0; i<N; i++) {
Kenny Root447106f2011-03-23 11:00:15 -07004833 final String name = pkg.requestedPermissions.get(i);
Dianne Hackborne639da72012-02-21 15:11:13 -08004834 //final boolean required = pkg.requestedPermssionsRequired.get(i);
Kenny Root447106f2011-03-23 11:00:15 -07004835 final BasePermission bp = mSettings.mPermissions.get(name);
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004836 if (DEBUG_INSTALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004837 if (gp != ps) {
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004838 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004839 }
4840 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004841 if (bp != null && bp.packageSetting != null) {
4842 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004843 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004844 boolean allowedSig = false;
Dianne Hackborne639da72012-02-21 15:11:13 -08004845 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
4846 if (level == PermissionInfo.PROTECTION_NORMAL
4847 || level == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004848 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07004849 } else if (bp.packageSetting == null) {
4850 // This permission is invalid; skip it.
4851 allowed = false;
Dianne Hackborne639da72012-02-21 15:11:13 -08004852 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
Kenny Root447106f2011-03-23 11:00:15 -07004853 allowed = (compareSignatures(
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07004854 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004855 == PackageManager.SIGNATURE_MATCH)
Kenny Root447106f2011-03-23 11:00:15 -07004856 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004857 == PackageManager.SIGNATURE_MATCH);
Dianne Hackborne639da72012-02-21 15:11:13 -08004858 if (!allowed && (bp.protectionLevel
4859 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
Kenny Root85387d72010-08-26 10:13:11 -07004860 if (isSystemApp(pkg)) {
Dianne Hackborne639da72012-02-21 15:11:13 -08004861 // For updated system applications, a system permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004862 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07004863 if (isUpdatedSystemApp(pkg)) {
Kenny Root447106f2011-03-23 11:00:15 -07004864 final PackageSetting sysPs = mSettings
4865 .getDisabledSystemPkgLPr(pkg.packageName);
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07004866 final GrantedPermissions origGp = sysPs.sharedUser != null
4867 ? sysPs.sharedUser : sysPs;
4868 if (origGp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004869 allowed = true;
4870 } else {
4871 allowed = false;
4872 }
4873 } else {
4874 allowed = true;
4875 }
4876 }
4877 }
Dianne Hackborne639da72012-02-21 15:11:13 -08004878 if (!allowed && (bp.protectionLevel
4879 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
4880 // For development permissions, a development permission
4881 // is granted only if it was already granted.
4882 if (origPermissions.contains(perm)) {
4883 allowed = true;
4884 } else {
4885 allowed = false;
4886 }
4887 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004888 if (allowed) {
4889 allowedSig = true;
4890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004891 } else {
4892 allowed = false;
4893 }
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004894 if (DEBUG_INSTALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004895 if (gp != ps) {
4896 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4897 }
4898 }
4899 if (allowed) {
4900 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4901 && ps.permissionsFixed) {
4902 // If this is an existing, non-system package, then
4903 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004904 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004905 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004906 // Except... if this is a permission that was added
4907 // to the platform (note: need to only do this when
4908 // updating the platform).
4909 final int NP = PackageParser.NEW_PERMISSIONS.length;
4910 for (int ip=0; ip<NP; ip++) {
4911 final PackageParser.NewPermissionInfo npi
4912 = PackageParser.NEW_PERMISSIONS[ip];
4913 if (npi.name.equals(perm)
4914 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4915 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004916 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004917 + pkg.packageName);
4918 break;
4919 }
4920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004921 }
4922 }
4923 if (allowed) {
4924 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004925 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004926 gp.grantedPermissions.add(perm);
4927 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004928 } else if (!ps.haveGids) {
4929 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004930 }
4931 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004932 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004933 + " to package " + pkg.packageName
4934 + " because it was previously installed without");
4935 }
4936 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004937 if (gp.grantedPermissions.remove(perm)) {
4938 changedPermission = true;
4939 gp.gids = removeInts(gp.gids, bp.gids);
4940 Slog.i(TAG, "Un-granting permission " + perm
4941 + " from package " + pkg.packageName
4942 + " (protectionLevel=" + bp.protectionLevel
4943 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4944 + ")");
4945 } else {
4946 Slog.w(TAG, "Not granting permission " + perm
4947 + " to package " + pkg.packageName
4948 + " (protectionLevel=" + bp.protectionLevel
4949 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4950 + ")");
4951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004952 }
4953 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004954 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004955 + " in package " + pkg.packageName);
4956 }
4957 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004958
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004959 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004960 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4961 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004962 // This is the first that we have heard about this package, so the
4963 // permissions we have now selected are fixed until explicitly
4964 // changed.
4965 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004966 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004967 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004968 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004969
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08004970 final class ActivityIntentResolver
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004971 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Kenny Root60f7ad82011-03-22 12:49:06 -07004972 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004973 boolean defaultOnly, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07004974 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004975 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Amith Yamasani483f3b02012-03-13 16:08:00 -07004976 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004977 }
4978
Amith Yamasani483f3b02012-03-13 16:08:00 -07004979 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
4980 int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07004981 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004982 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004983 return super.queryIntent(intent, resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004984 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004985 }
4986
Kenny Root60f7ad82011-03-22 12:49:06 -07004987 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004988 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07004989 if (!sUserManager.exists(userId)) return null;
Mihai Predaeae850c2009-05-13 10:13:48 +02004990 if (packageActivities == null) {
4991 return null;
4992 }
4993 mFlags = flags;
4994 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
Kenny Root62cc6902011-02-23 16:49:21 -08004995 final int N = packageActivities.size();
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07004996 ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
4997 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004998
4999 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02005000 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02005001 intentFilters = packageActivities.get(i).intents;
5002 if (intentFilters != null && intentFilters.size() > 0) {
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07005003 PackageParser.ActivityIntentInfo[] array =
5004 new PackageParser.ActivityIntentInfo[intentFilters.size()];
5005 intentFilters.toArray(array);
5006 listCut.add(array);
Mihai Predac3320db2009-05-18 20:15:32 +02005007 }
Mihai Predaeae850c2009-05-13 10:13:48 +02005008 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07005009 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
Mihai Predaeae850c2009-05-13 10:13:48 +02005010 }
5011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005012 public final void addActivity(PackageParser.Activity a, String type) {
Kenny Root502e9a42011-01-10 13:48:15 -08005013 final boolean systemApp = isSystemApp(a.info.applicationInfo);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005014 mActivities.put(a.getComponentName(), a);
Kenny Root9718cf52011-02-23 16:45:26 -08005015 if (DEBUG_SHOW_INFO)
5016 Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005017 TAG, " " + type + " " +
5018 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
Kenny Root9718cf52011-02-23 16:45:26 -08005019 if (DEBUG_SHOW_INFO)
5020 Log.v(TAG, " Class=" + a.info.name);
Kenny Root62cc6902011-02-23 16:49:21 -08005021 final int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02005022 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005023 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
Kenny Root502e9a42011-01-10 13:48:15 -08005024 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
5025 intent.setPriority(0);
5026 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
5027 + a.className + " with priority > 0, forcing to 0");
5028 }
Kenny Root9718cf52011-02-23 16:45:26 -08005029 if (DEBUG_SHOW_INFO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005030 Log.v(TAG, " IntentFilter:");
5031 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
5032 }
5033 if (!intent.debugCheck()) {
5034 Log.w(TAG, "==> For Activity " + a.info.name);
5035 }
5036 addFilter(intent);
5037 }
5038 }
5039
5040 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005041 mActivities.remove(a.getComponentName());
Kenny Root9718cf52011-02-23 16:45:26 -08005042 if (DEBUG_SHOW_INFO) {
5043 Log.v(TAG, " " + type + " "
5044 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
5045 : a.info.name) + ":");
5046 Log.v(TAG, " Class=" + a.info.name);
5047 }
5048 final int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02005049 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005050 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
Kenny Root9718cf52011-02-23 16:45:26 -08005051 if (DEBUG_SHOW_INFO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005052 Log.v(TAG, " IntentFilter:");
5053 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
5054 }
5055 removeFilter(intent);
5056 }
5057 }
5058
5059 @Override
5060 protected boolean allowFilterResult(
5061 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
5062 ActivityInfo filterAi = filter.activity.info;
5063 for (int i=dest.size()-1; i>=0; i--) {
5064 ActivityInfo destAi = dest.get(i).activityInfo;
5065 if (destAi.name == filterAi.name
5066 && destAi.packageName == filterAi.packageName) {
5067 return false;
5068 }
5069 }
5070 return true;
5071 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005073 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07005074 protected ActivityIntentInfo[] newArray(int size) {
5075 return new ActivityIntentInfo[size];
5076 }
5077
5078 @Override
Amith Yamasani483f3b02012-03-13 16:08:00 -07005079 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005080 if (!sUserManager.exists(userId)) return true;
Dianne Hackborne7f97212011-02-24 14:40:20 -08005081 PackageParser.Package p = filter.activity.owner;
5082 if (p != null) {
5083 PackageSetting ps = (PackageSetting)p.mExtras;
5084 if (ps != null) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07005085 // System apps are never considered stopped for purposes of
5086 // filtering, because there may be no way for the user to
5087 // actually re-launch them.
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005088 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
5089 && ps.getStopped(userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08005090 }
5091 }
5092 return false;
5093 }
5094
5095 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005096 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
5097 return info.activity.owner.packageName;
5098 }
5099
5100 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005101 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005102 int match, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005103 if (!sUserManager.exists(userId)) return null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005104 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005105 return null;
5106 }
5107 final PackageParser.Activity activity = info.activity;
5108 if (mSafeMode && (activity.info.applicationInfo.flags
5109 &ApplicationInfo.FLAG_SYSTEM) == 0) {
5110 return null;
5111 }
Amith Yamasani13593602012-03-22 16:16:17 -07005112 PackageSetting ps = (PackageSetting) activity.owner.mExtras;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005113 if (ps == null) {
5114 return null;
5115 }
5116 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
5117 ps.readUserState(userId), userId);
5118 if (ai == null) {
5119 return null;
5120 }
5121 final ResolveInfo res = new ResolveInfo();
5122 res.activityInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005123 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
5124 res.filter = info;
5125 }
5126 res.priority = info.getPriority();
5127 res.preferredOrder = activity.owner.mPreferredOrder;
5128 //System.out.println("Result: " + res.activityInfo.className +
5129 // " = " + res.priority);
5130 res.match = match;
5131 res.isDefault = info.hasDefault;
5132 res.labelRes = info.labelRes;
5133 res.nonLocalizedLabel = info.nonLocalizedLabel;
5134 res.icon = info.icon;
Dianne Hackbornd99b2932011-08-18 14:39:58 -07005135 res.system = isSystemApp(res.activityInfo.applicationInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005136 return res;
5137 }
5138
5139 @Override
5140 protected void sortResults(List<ResolveInfo> results) {
5141 Collections.sort(results, mResolvePrioritySorter);
5142 }
5143
5144 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005145 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005146 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005147 out.print(prefix); out.print(
5148 Integer.toHexString(System.identityHashCode(filter.activity)));
5149 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005150 out.print(filter.activity.getComponentShortName());
5151 out.print(" filter ");
5152 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005153 }
5154
5155// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
5156// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
5157// final List<ResolveInfo> retList = Lists.newArrayList();
5158// while (i.hasNext()) {
5159// final ResolveInfo resolveInfo = i.next();
5160// if (isEnabledLP(resolveInfo.activityInfo)) {
5161// retList.add(resolveInfo);
5162// }
5163// }
5164// return retList;
5165// }
5166
5167 // Keys are String (activity class name), values are Activity.
5168 private final HashMap<ComponentName, PackageParser.Activity> mActivities
5169 = new HashMap<ComponentName, PackageParser.Activity>();
5170 private int mFlags;
5171 }
5172
5173 private final class ServiceIntentResolver
5174 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Kenny Root60f7ad82011-03-22 12:49:06 -07005175 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005176 boolean defaultOnly, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005177 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005178 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005179 }
5180
Amith Yamasani483f3b02012-03-13 16:08:00 -07005181 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
5182 int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005183 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005184 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02005185 return super.queryIntent(intent, resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005186 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005187 }
5188
Kenny Root60f7ad82011-03-22 12:49:06 -07005189 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005190 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005191 if (!sUserManager.exists(userId)) return null;
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07005192 if (packageServices == null) {
5193 return null;
5194 }
5195 mFlags = flags;
5196 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
Kenny Root62cc6902011-02-23 16:49:21 -08005197 final int N = packageServices.size();
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07005198 ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
5199 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07005200
5201 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
5202 for (int i = 0; i < N; ++i) {
5203 intentFilters = packageServices.get(i).intents;
5204 if (intentFilters != null && intentFilters.size() > 0) {
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07005205 PackageParser.ServiceIntentInfo[] array =
5206 new PackageParser.ServiceIntentInfo[intentFilters.size()];
5207 intentFilters.toArray(array);
5208 listCut.add(array);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07005209 }
5210 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07005211 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07005212 }
5213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005214 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005215 mServices.put(s.getComponentName(), s);
Kenny Root9718cf52011-02-23 16:45:26 -08005216 if (DEBUG_SHOW_INFO) {
5217 Log.v(TAG, " "
5218 + (s.info.nonLocalizedLabel != null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005219 ? s.info.nonLocalizedLabel : s.info.name) + ":");
Kenny Root9718cf52011-02-23 16:45:26 -08005220 Log.v(TAG, " Class=" + s.info.name);
5221 }
5222 final int NI = s.intents.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005223 int j;
5224 for (j=0; j<NI; j++) {
5225 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
Kenny Root9718cf52011-02-23 16:45:26 -08005226 if (DEBUG_SHOW_INFO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005227 Log.v(TAG, " IntentFilter:");
5228 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
5229 }
5230 if (!intent.debugCheck()) {
5231 Log.w(TAG, "==> For Service " + s.info.name);
5232 }
5233 addFilter(intent);
5234 }
5235 }
5236
5237 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005238 mServices.remove(s.getComponentName());
Kenny Root9718cf52011-02-23 16:45:26 -08005239 if (DEBUG_SHOW_INFO) {
5240 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005241 ? s.info.nonLocalizedLabel : s.info.name) + ":");
Kenny Root9718cf52011-02-23 16:45:26 -08005242 Log.v(TAG, " Class=" + s.info.name);
5243 }
5244 final int NI = s.intents.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005245 int j;
5246 for (j=0; j<NI; j++) {
5247 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
Kenny Root9718cf52011-02-23 16:45:26 -08005248 if (DEBUG_SHOW_INFO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005249 Log.v(TAG, " IntentFilter:");
5250 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
5251 }
5252 removeFilter(intent);
5253 }
5254 }
5255
5256 @Override
5257 protected boolean allowFilterResult(
5258 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
5259 ServiceInfo filterSi = filter.service.info;
5260 for (int i=dest.size()-1; i>=0; i--) {
5261 ServiceInfo destAi = dest.get(i).serviceInfo;
5262 if (destAi.name == filterSi.name
5263 && destAi.packageName == filterSi.packageName) {
5264 return false;
5265 }
5266 }
5267 return true;
5268 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005270 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07005271 protected PackageParser.ServiceIntentInfo[] newArray(int size) {
5272 return new PackageParser.ServiceIntentInfo[size];
5273 }
5274
5275 @Override
Amith Yamasani483f3b02012-03-13 16:08:00 -07005276 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005277 if (!sUserManager.exists(userId)) return true;
Dianne Hackborne7f97212011-02-24 14:40:20 -08005278 PackageParser.Package p = filter.service.owner;
5279 if (p != null) {
5280 PackageSetting ps = (PackageSetting)p.mExtras;
5281 if (ps != null) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07005282 // System apps are never considered stopped for purposes of
5283 // filtering, because there may be no way for the user to
5284 // actually re-launch them.
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005285 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
5286 && ps.getStopped(userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08005287 }
5288 }
5289 return false;
5290 }
5291
5292 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005293 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
5294 return info.service.owner.packageName;
5295 }
5296
5297 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005298 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005299 int match, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005300 if (!sUserManager.exists(userId)) return null;
Jason parksa3cdaa52011-01-13 14:15:43 -06005301 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005302 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005303 return null;
5304 }
5305 final PackageParser.Service service = info.service;
5306 if (mSafeMode && (service.info.applicationInfo.flags
5307 &ApplicationInfo.FLAG_SYSTEM) == 0) {
5308 return null;
5309 }
Amith Yamasani13593602012-03-22 16:16:17 -07005310 PackageSetting ps = (PackageSetting) service.owner.mExtras;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005311 if (ps == null) {
5312 return null;
5313 }
5314 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
5315 ps.readUserState(userId), userId);
Dianne Hackborn4428e172012-08-24 17:43:05 -07005316 if (si == null) {
5317 return null;
5318 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005319 final ResolveInfo res = new ResolveInfo();
5320 res.serviceInfo = si;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005321 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
5322 res.filter = filter;
5323 }
5324 res.priority = info.getPriority();
5325 res.preferredOrder = service.owner.mPreferredOrder;
5326 //System.out.println("Result: " + res.activityInfo.className +
5327 // " = " + res.priority);
5328 res.match = match;
5329 res.isDefault = info.hasDefault;
5330 res.labelRes = info.labelRes;
5331 res.nonLocalizedLabel = info.nonLocalizedLabel;
5332 res.icon = info.icon;
Dianne Hackbornd99b2932011-08-18 14:39:58 -07005333 res.system = isSystemApp(res.serviceInfo.applicationInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005334 return res;
5335 }
5336
5337 @Override
5338 protected void sortResults(List<ResolveInfo> results) {
5339 Collections.sort(results, mResolvePrioritySorter);
5340 }
5341
5342 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005343 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005344 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005345 out.print(prefix); out.print(
5346 Integer.toHexString(System.identityHashCode(filter.service)));
5347 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005348 out.print(filter.service.getComponentShortName());
5349 out.print(" filter ");
5350 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005351 }
5352
5353// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
5354// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
5355// final List<ResolveInfo> retList = Lists.newArrayList();
5356// while (i.hasNext()) {
5357// final ResolveInfo resolveInfo = (ResolveInfo) i;
5358// if (isEnabledLP(resolveInfo.serviceInfo)) {
5359// retList.add(resolveInfo);
5360// }
5361// }
5362// return retList;
5363// }
5364
5365 // Keys are String (activity class name), values are Activity.
5366 private final HashMap<ComponentName, PackageParser.Service> mServices
5367 = new HashMap<ComponentName, PackageParser.Service>();
5368 private int mFlags;
5369 };
5370
5371 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
5372 new Comparator<ResolveInfo>() {
5373 public int compare(ResolveInfo r1, ResolveInfo r2) {
5374 int v1 = r1.priority;
5375 int v2 = r2.priority;
5376 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
5377 if (v1 != v2) {
5378 return (v1 > v2) ? -1 : 1;
5379 }
5380 v1 = r1.preferredOrder;
5381 v2 = r2.preferredOrder;
5382 if (v1 != v2) {
5383 return (v1 > v2) ? -1 : 1;
5384 }
5385 if (r1.isDefault != r2.isDefault) {
5386 return r1.isDefault ? -1 : 1;
5387 }
5388 v1 = r1.match;
5389 v2 = r2.match;
5390 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
Dianne Hackbornd99b2932011-08-18 14:39:58 -07005391 if (v1 != v2) {
5392 return (v1 > v2) ? -1 : 1;
5393 }
5394 if (r1.system != r2.system) {
5395 return r1.system ? -1 : 1;
5396 }
5397 return 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005398 }
5399 };
5400
5401 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
5402 new Comparator<ProviderInfo>() {
5403 public int compare(ProviderInfo p1, ProviderInfo p2) {
5404 final int v1 = p1.initOrder;
5405 final int v2 = p2.initOrder;
5406 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
5407 }
5408 };
5409
Kenny Root447106f2011-03-23 11:00:15 -07005410 static final void sendPackageBroadcast(String action, String pkg,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005411 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
5412 int[] userIds) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005413 IActivityManager am = ActivityManagerNative.getDefault();
5414 if (am != null) {
5415 try {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005416 if (userIds == null) {
Dianne Hackbornc72fc672012-09-20 13:12:03 -07005417 userIds = am.getRunningUserIds();
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005418 }
Amith Yamasani13593602012-03-22 16:16:17 -07005419 for (int id : userIds) {
5420 final Intent intent = new Intent(action,
5421 pkg != null ? Uri.fromParts("package", pkg, null) : null);
5422 if (extras != null) {
5423 intent.putExtras(extras);
5424 }
5425 if (targetPkg != null) {
5426 intent.setPackage(targetPkg);
5427 }
5428 // Modify the UID when posting to other users
5429 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005430 if (uid > 0 && UserHandle.getUserId(uid) != id) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005431 uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
Amith Yamasani13593602012-03-22 16:16:17 -07005432 intent.putExtra(Intent.EXTRA_UID, uid);
5433 }
Dianne Hackbornc72fc672012-09-20 13:12:03 -07005434 intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
Amith Yamasani13593602012-03-22 16:16:17 -07005435 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005436 if (DEBUG_BROADCASTS) {
5437 RuntimeException here = new RuntimeException("here");
5438 here.fillInStackTrace();
5439 Slog.d(TAG, "Sending to user " + id + ": "
5440 + intent.toShortString(false, true, false, false)
5441 + " " + intent.getExtras(), here);
5442 }
Amith Yamasani13593602012-03-22 16:16:17 -07005443 am.broadcastIntent(null, intent, null, finishedReceiver,
5444 0, null, null, null, finishedReceiver != null, false, id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005446 } catch (RemoteException ex) {
5447 }
5448 }
5449 }
Kenny Root300c13a2011-01-18 13:04:40 -08005450
5451 /**
5452 * Check if the external storage media is available. This is true if there
5453 * is a mounted external storage medium or if the external storage is
5454 * emulated.
5455 */
5456 private boolean isExternalMediaAvailable() {
5457 return mMediaMounted || Environment.isExternalStorageEmulated();
5458 }
5459
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005460 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
Kenny Root447106f2011-03-23 11:00:15 -07005461 // writer
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005462 synchronized (mPackages) {
Kenny Root300c13a2011-01-18 13:04:40 -08005463 if (!isExternalMediaAvailable()) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005464 // If the external storage is no longer mounted at this point,
5465 // the caller may not have been able to delete all of this
5466 // packages files and can not delete any more. Bail.
5467 return null;
5468 }
Jeff Sharkey752cd922012-09-23 16:25:12 -07005469 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
5470 if (lastPackage != null) {
5471 pkgs.remove(lastPackage);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005472 }
Jeff Sharkey752cd922012-09-23 16:25:12 -07005473 if (pkgs.size() > 0) {
5474 return pkgs.get(0);
5475 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005476 }
5477 return null;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005480 void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
5481 if (false) {
5482 RuntimeException here = new RuntimeException("here");
5483 here.fillInStackTrace();
5484 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
5485 + " andCode=" + andCode, here);
5486 }
5487 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
5488 userId, andCode ? 1 : 0, packageName));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005489 }
5490
Jeff Sharkey752cd922012-09-23 16:25:12 -07005491 void startCleaningPackages() {
Kenny Root447106f2011-03-23 11:00:15 -07005492 // reader
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005493 synchronized (mPackages) {
Kenny Root300c13a2011-01-18 13:04:40 -08005494 if (!isExternalMediaAvailable()) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005495 return;
5496 }
Jeff Sharkey752cd922012-09-23 16:25:12 -07005497 if (mSettings.mPackagesToBeCleaned.isEmpty()) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005498 return;
5499 }
5500 }
5501 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
5502 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
5503 IActivityManager am = ActivityManagerNative.getDefault();
5504 if (am != null) {
5505 try {
Jeff Sharkey752cd922012-09-23 16:25:12 -07005506 am.startService(null, intent, null, UserHandle.USER_OWNER);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005507 } catch (RemoteException e) {
5508 }
5509 }
5510 }
5511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512 private final class AppDirObserver extends FileObserver {
5513 public AppDirObserver(String path, int mask, boolean isrom) {
5514 super(path, mask);
5515 mRootDir = path;
5516 mIsRom = isrom;
5517 }
5518
5519 public void onEvent(int event, String path) {
5520 String removedPackage = null;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07005521 int removedAppId = -1;
Dianne Hackborn786b4402012-08-27 15:14:02 -07005522 int[] removedUsers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005523 String addedPackage = null;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07005524 int addedAppId = -1;
Dianne Hackborn786b4402012-08-27 15:14:02 -07005525 int[] addedUsers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005526
Kenny Root447106f2011-03-23 11:00:15 -07005527 // TODO post a message to the handler to obtain serial ordering
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005528 synchronized (mInstallLock) {
5529 String fullPathStr = null;
5530 File fullPath = null;
5531 if (path != null) {
5532 fullPath = new File(mRootDir, path);
5533 fullPathStr = fullPath.getPath();
5534 }
5535
Kenny Root9718cf52011-02-23 16:45:26 -08005536 if (DEBUG_APP_DIR_OBSERVER)
5537 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005538
5539 if (!isPackageFilename(path)) {
Kenny Root9718cf52011-02-23 16:45:26 -08005540 if (DEBUG_APP_DIR_OBSERVER)
5541 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005542 return;
5543 }
5544
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005545 // Ignore packages that are being installed or
5546 // have just been installed.
5547 if (ignoreCodePath(fullPathStr)) {
5548 return;
5549 }
5550 PackageParser.Package p = null;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07005551 PackageSetting ps = null;
Kenny Root447106f2011-03-23 11:00:15 -07005552 // reader
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005553 synchronized (mPackages) {
5554 p = mAppDirs.get(fullPathStr);
Dianne Hackborn786b4402012-08-27 15:14:02 -07005555 if (p != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07005556 ps = mSettings.mPackages.get(p.applicationInfo.packageName);
Dianne Hackborn786b4402012-08-27 15:14:02 -07005557 if (ps != null) {
5558 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
5559 } else {
5560 removedUsers = sUserManager.getUserIds();
5561 }
5562 }
5563 addedUsers = sUserManager.getUserIds();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005564 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005565 if ((event&REMOVE_EVENTS) != 0) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07005566 if (ps != null) {
5567 removePackageLI(ps, true);
5568 removedPackage = ps.name;
5569 removedAppId = ps.appId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005570 }
5571 }
5572
5573 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005574 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005575 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07005576 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
5577 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005578 PackageParser.PARSE_CHATTY |
5579 PackageParser.PARSE_MUST_BE_APK,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005580 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
Dianne Hackborn786b4402012-08-27 15:14:02 -07005581 System.currentTimeMillis(), UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005582 if (p != null) {
Kenny Root447106f2011-03-23 11:00:15 -07005583 /*
5584 * TODO this seems dangerous as the package may have
5585 * changed since we last acquired the mPackages
5586 * lock.
5587 */
5588 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005589 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07005590 updatePermissionsLPw(p.packageName, p,
Dianne Hackborne639da72012-02-21 15:11:13 -08005591 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005592 }
5593 addedPackage = p.applicationInfo.packageName;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07005594 addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005595 }
5596 }
5597 }
5598
Kenny Root447106f2011-03-23 11:00:15 -07005599 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005600 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07005601 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 }
5603 }
5604
5605 if (removedPackage != null) {
5606 Bundle extras = new Bundle(1);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07005607 extras.putInt(Intent.EXTRA_UID, removedAppId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005608 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07005609 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
Dianne Hackborn786b4402012-08-27 15:14:02 -07005610 extras, null, null, removedUsers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005611 }
5612 if (addedPackage != null) {
5613 Bundle extras = new Bundle(1);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07005614 extras.putInt(Intent.EXTRA_UID, addedAppId);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07005615 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
Dianne Hackborn786b4402012-08-27 15:14:02 -07005616 extras, null, null, addedUsers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005617 }
5618 }
5619
5620 private final String mRootDir;
5621 private final boolean mIsRom;
5622 }
Jacek Surazski65e13172009-04-28 15:26:38 +02005623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005624 /* Called when a downloaded package installation has been confirmed by the user */
5625 public void installPackage(
5626 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02005627 installPackage(packageURI, observer, flags, null);
5628 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005629
Jacek Surazski65e13172009-04-28 15:26:38 +02005630 /* Called when a downloaded package installation has been confirmed by the user */
5631 public void installPackage(
5632 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
5633 final String installerPackageName) {
Kenny Root5ab21572011-07-27 11:11:19 -07005634 installPackageWithVerification(packageURI, observer, flags, installerPackageName, null,
Rich Canningse1d7c712012-08-08 12:46:06 -07005635 null, null);
Kenny Root5ab21572011-07-27 11:11:19 -07005636 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005637
Kenny Root5ab21572011-07-27 11:11:19 -07005638 @Override
5639 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
5640 int flags, String installerPackageName, Uri verificationURI,
Rich Canningse1d7c712012-08-08 12:46:06 -07005641 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
rich cannings706e8ba2012-08-20 13:20:14 -07005642 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
Ben Gruver37d83a32012-09-27 13:02:06 -07005643 VerificationParams.NO_UID, manifestDigest);
rich cannings706e8ba2012-08-20 13:20:14 -07005644 installPackageWithVerificationAndEncryption(packageURI, observer, flags,
5645 installerPackageName, verificationParams, encryptionParams);
5646 }
5647
5648 public void installPackageWithVerificationAndEncryption(Uri packageURI,
5649 IPackageInstallObserver observer, int flags, String installerPackageName,
5650 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
5651 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
5652 null);
Kenny Root5ab21572011-07-27 11:11:19 -07005653
5654 final int uid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005655 UserHandle user;
5656 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
5657 user = UserHandle.ALL;
5658 } else {
Dianne Hackborn786b4402012-08-27 15:14:02 -07005659 user = new UserHandle(UserHandle.getUserId(uid));
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005660 }
Kenny Root5ab21572011-07-27 11:11:19 -07005661
5662 final int filteredFlags;
5663
5664 if (uid == Process.SHELL_UID || uid == 0) {
5665 if (DEBUG_INSTALL) {
5666 Slog.v(TAG, "Install from ADB");
5667 }
5668 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
5669 } else {
5670 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
5671 }
5672
rich cannings13d428e2012-09-13 13:43:07 -07005673 verificationParams.setInstallerUid(uid);
5674
Kenny Root5ab21572011-07-27 11:11:19 -07005675 final Message msg = mHandler.obtainMessage(INIT_COPY);
5676 msg.obj = new InstallParams(packageURI, observer, filteredFlags, installerPackageName,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005677 verificationParams, encryptionParams, user);
Kenny Root5ab21572011-07-27 11:11:19 -07005678 mHandler.sendMessage(msg);
5679 }
5680
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005681 /**
5682 * @hide
5683 */
5684 @Override
5685 public int installExistingPackage(String packageName) {
5686 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
5687 null);
5688 PackageSetting pkgSetting;
5689 final int uid = Binder.getCallingUid();
5690 final int userId = UserHandle.getUserId(uid);
5691
5692 long callingId = Binder.clearCallingIdentity();
5693 try {
5694 boolean sendAdded = false;
5695 Bundle extras = new Bundle(1);
5696
5697 // writer
5698 synchronized (mPackages) {
5699 pkgSetting = mSettings.mPackages.get(packageName);
5700 if (pkgSetting == null) {
5701 return PackageManager.INSTALL_FAILED_INVALID_URI;
5702 }
5703 if (!pkgSetting.getInstalled(userId)) {
5704 pkgSetting.setInstalled(true, userId);
5705 mSettings.writePackageRestrictionsLPr(userId);
5706 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
5707 sendAdded = true;
5708 }
5709 }
5710
5711 if (sendAdded) {
5712 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
5713 packageName, extras, null, null, new int[] {userId});
5714 }
5715 } finally {
5716 Binder.restoreCallingIdentity(callingId);
5717 }
5718
5719 return PackageManager.INSTALL_SUCCEEDED;
5720 }
5721
Kenny Root5ab21572011-07-27 11:11:19 -07005722 @Override
Kenny Root05ca4c92011-09-15 10:36:25 -07005723 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
rich cannings7e671512012-08-27 14:44:16 -07005724 mContext.enforceCallingOrSelfPermission(
5725 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
5726 "Only package verification agents can verify applications");
5727
Kenny Root5ab21572011-07-27 11:11:19 -07005728 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
Kenny Root05ca4c92011-09-15 10:36:25 -07005729 final PackageVerificationResponse response = new PackageVerificationResponse(
5730 verificationCode, Binder.getCallingUid());
Kenny Root5ab21572011-07-27 11:11:19 -07005731 msg.arg1 = id;
Kenny Root05ca4c92011-09-15 10:36:25 -07005732 msg.obj = response;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005733 mHandler.sendMessage(msg);
5734 }
5735
rich canningsd9ef3e52012-08-22 14:28:05 -07005736 @Override
5737 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
5738 long millisecondsToDelay) {
rich cannings7e671512012-08-27 14:44:16 -07005739 mContext.enforceCallingOrSelfPermission(
5740 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
5741 "Only package verification agents can extend verification timeouts");
5742
rich canningsd9ef3e52012-08-22 14:28:05 -07005743 final PackageVerificationState state = mPendingVerification.get(id);
5744 final PackageVerificationResponse response = new PackageVerificationResponse(
5745 verificationCodeAtTimeout, Binder.getCallingUid());
5746
rich canningsd1b5cfc2012-08-29 14:49:51 -07005747 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
5748 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
5749 }
5750 if (millisecondsToDelay < 0) {
5751 millisecondsToDelay = 0;
rich canningsd9ef3e52012-08-22 14:28:05 -07005752 }
5753 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
rich canningsd1b5cfc2012-08-29 14:49:51 -07005754 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
5755 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
rich canningsd9ef3e52012-08-22 14:28:05 -07005756 }
5757
5758 if ((state != null) && !state.timeoutExtended()) {
5759 state.extendTimeout();
5760
5761 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
5762 msg.arg1 = id;
5763 msg.obj = response;
5764 mHandler.sendMessageDelayed(msg, millisecondsToDelay);
5765 }
5766 }
5767
rich canningsd1b5cfc2012-08-29 14:49:51 -07005768 private void broadcastPackageVerified(int verificationId, Uri packageUri,
rich canningsd55deb02012-10-02 14:53:08 -07005769 int verificationCode, UserHandle user) {
rich canningsd1b5cfc2012-08-29 14:49:51 -07005770 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
5771 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
5772 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
5773 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
5774 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
5775
rich canningsd55deb02012-10-02 14:53:08 -07005776 mContext.sendBroadcastAsUser(intent, user,
5777 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
rich canningsd1b5cfc2012-08-29 14:49:51 -07005778 }
5779
Kenny Root05ca4c92011-09-15 10:36:25 -07005780 private ComponentName matchComponentForVerifier(String packageName,
5781 List<ResolveInfo> receivers) {
5782 ActivityInfo targetReceiver = null;
5783
5784 final int NR = receivers.size();
5785 for (int i = 0; i < NR; i++) {
5786 final ResolveInfo info = receivers.get(i);
5787 if (info.activityInfo == null) {
5788 continue;
5789 }
5790
5791 if (packageName.equals(info.activityInfo.packageName)) {
5792 targetReceiver = info.activityInfo;
5793 break;
5794 }
5795 }
5796
5797 if (targetReceiver == null) {
5798 return null;
5799 }
5800
5801 return new ComponentName(targetReceiver.packageName, targetReceiver.name);
5802 }
5803
5804 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
5805 List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
5806 if (pkgInfo.verifiers.length == 0) {
5807 return null;
5808 }
5809
5810 final int N = pkgInfo.verifiers.length;
5811 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
5812 for (int i = 0; i < N; i++) {
5813 final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
5814
5815 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
5816 receivers);
5817 if (comp == null) {
5818 continue;
5819 }
5820
5821 final int verifierUid = getUidForVerifier(verifierInfo);
5822 if (verifierUid == -1) {
5823 continue;
5824 }
5825
5826 if (DEBUG_VERIFY) {
5827 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
5828 + " with the correct signature");
5829 }
5830 sufficientVerifiers.add(comp);
5831 verificationState.addSufficientVerifier(verifierUid);
5832 }
5833
5834 return sufficientVerifiers;
5835 }
5836
5837 private int getUidForVerifier(VerifierInfo verifierInfo) {
5838 synchronized (mPackages) {
5839 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
5840 if (pkg == null) {
5841 return -1;
5842 } else if (pkg.mSignatures.length != 1) {
5843 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
5844 + " has more than one signature; ignoring");
5845 return -1;
5846 }
5847
5848 /*
5849 * If the public key of the package's signature does not match
5850 * our expected public key, then this is a different package and
5851 * we should skip.
5852 */
5853
5854 final byte[] expectedPublicKey;
5855 try {
5856 final Signature verifierSig = pkg.mSignatures[0];
5857 final PublicKey publicKey = verifierSig.getPublicKey();
5858 expectedPublicKey = publicKey.getEncoded();
5859 } catch (CertificateException e) {
5860 return -1;
5861 }
5862
5863 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
5864
5865 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
5866 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
5867 + " does not have the expected public key; ignoring");
5868 return -1;
5869 }
5870
5871 return pkg.applicationInfo.uid;
5872 }
5873 }
5874
Christopher Tate1bb69062010-02-19 17:02:12 -08005875 public void finishPackageInstall(int token) {
Kenny Root461ff1f2011-08-09 09:43:03 -07005876 enforceSystemOrRoot("Only the system is allowed to finish installs");
5877
5878 if (DEBUG_INSTALL) {
5879 Slog.v(TAG, "BM finishing package install for " + token);
5880 }
5881
5882 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
Christopher Tate1bb69062010-02-19 17:02:12 -08005883 mHandler.sendMessage(msg);
5884 }
5885
Kenny Root5ab21572011-07-27 11:11:19 -07005886 /**
5887 * Get the verification agent timeout.
5888 *
5889 * @return verification timeout in milliseconds
5890 */
5891 private long getVerificationTimeout() {
rich cannings4d8fc792012-09-07 14:43:43 -07005892 return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
5893 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
Kenny Root5ab21572011-07-27 11:11:19 -07005894 DEFAULT_VERIFICATION_TIMEOUT);
5895 }
5896
5897 /**
rich canningsa6cfe522012-05-21 15:50:56 -07005898 * Get the default verification agent response code.
5899 *
5900 * @return default verification response code
5901 */
5902 private int getDefaultVerificationResponse() {
rich cannings4d8fc792012-09-07 14:43:43 -07005903 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
5904 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
rich canningsa6cfe522012-05-21 15:50:56 -07005905 DEFAULT_VERIFICATION_RESPONSE);
5906 }
5907
5908 /**
Kenny Root5ab21572011-07-27 11:11:19 -07005909 * Check whether or not package verification has been enabled.
5910 *
5911 * @return true if verification should be performed
5912 */
rich cannings4e5753f2012-09-19 16:03:56 -07005913 private boolean isVerificationEnabled(int flags) {
rich canningse4bf0ea2012-09-14 13:18:55 -07005914 if (!DEFAULT_VERIFY_ENABLE) {
5915 return false;
5916 }
5917
rich cannings4e5753f2012-09-19 16:03:56 -07005918 // Check if installing from ADB
5919 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
rich canningsa2064df2012-09-30 14:52:41 -07005920 // Do not run verification in a test harness environment
5921 if (ActivityManager.isRunningInTestHarness()) {
5922 return false;
5923 }
rich cannings4e5753f2012-09-19 16:03:56 -07005924 // Check if the developer does not want package verification for ADB installs
5925 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
5926 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
5927 return false;
5928 }
5929 }
5930
rich cannings4d8fc792012-09-07 14:43:43 -07005931 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
rich canningse4bf0ea2012-09-14 13:18:55 -07005932 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
Kenny Root5ab21572011-07-27 11:11:19 -07005933 }
5934
Matt Finifterf8a98ed2012-05-14 15:43:34 -07005935 /**
5936 * Get the "allow unknown sources" setting.
5937 *
5938 * @return the current "allow unknown sources" setting
5939 */
5940 private int getUnknownSourcesSettings() {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07005941 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
5942 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
Matt Finifterf8a98ed2012-05-14 15:43:34 -07005943 -1);
5944 }
5945
Kenny Rootf03b45f2011-02-23 17:25:45 -08005946 public void setInstallerPackageName(String targetPackage, String installerPackageName) {
Dianne Hackborn880119b2010-11-18 22:26:40 -08005947 final int uid = Binder.getCallingUid();
Kenny Root447106f2011-03-23 11:00:15 -07005948 // writer
Dianne Hackborn880119b2010-11-18 22:26:40 -08005949 synchronized (mPackages) {
5950 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
5951 if (targetPackageSetting == null) {
5952 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
5953 }
5954
5955 PackageSetting installerPackageSetting;
5956 if (installerPackageName != null) {
5957 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
5958 if (installerPackageSetting == null) {
5959 throw new IllegalArgumentException("Unknown installer package: "
5960 + installerPackageName);
5961 }
5962 } else {
5963 installerPackageSetting = null;
5964 }
5965
5966 Signature[] callerSignature;
Kenny Root447106f2011-03-23 11:00:15 -07005967 Object obj = mSettings.getUserIdLPr(uid);
Dianne Hackborn880119b2010-11-18 22:26:40 -08005968 if (obj != null) {
5969 if (obj instanceof SharedUserSetting) {
5970 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
5971 } else if (obj instanceof PackageSetting) {
5972 callerSignature = ((PackageSetting)obj).signatures.mSignatures;
5973 } else {
5974 throw new SecurityException("Bad object " + obj + " for uid " + uid);
5975 }
5976 } else {
5977 throw new SecurityException("Unknown calling uid " + uid);
5978 }
5979
5980 // Verify: can't set installerPackageName to a package that is
5981 // not signed with the same cert as the caller.
5982 if (installerPackageSetting != null) {
Kenny Root447106f2011-03-23 11:00:15 -07005983 if (compareSignatures(callerSignature,
Dianne Hackborn880119b2010-11-18 22:26:40 -08005984 installerPackageSetting.signatures.mSignatures)
5985 != PackageManager.SIGNATURE_MATCH) {
5986 throw new SecurityException(
5987 "Caller does not have same cert as new installer package "
5988 + installerPackageName);
5989 }
5990 }
5991
5992 // Verify: if target already has an installer package, it must
5993 // be signed with the same cert as the caller.
5994 if (targetPackageSetting.installerPackageName != null) {
5995 PackageSetting setting = mSettings.mPackages.get(
5996 targetPackageSetting.installerPackageName);
5997 // If the currently set package isn't valid, then it's always
5998 // okay to change it.
5999 if (setting != null) {
Kenny Root447106f2011-03-23 11:00:15 -07006000 if (compareSignatures(callerSignature,
Dianne Hackborn880119b2010-11-18 22:26:40 -08006001 setting.signatures.mSignatures)
6002 != PackageManager.SIGNATURE_MATCH) {
6003 throw new SecurityException(
6004 "Caller does not have same cert as old installer package "
6005 + targetPackageSetting.installerPackageName);
6006 }
6007 }
6008 }
6009
6010 // Okay!
6011 targetPackageSetting.installerPackageName = installerPackageName;
6012 scheduleWriteSettingsLocked();
6013 }
6014 }
6015
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006016 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006017 // Queue up an async operation since the package installation may take a little while.
6018 mHandler.post(new Runnable() {
6019 public void run() {
6020 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07006021 // Result object to be returned
6022 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006023 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07006024 res.uid = -1;
6025 res.pkg = null;
6026 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006027 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07006028 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07006029 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006030 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07006031 }
Kenny Root6dceb882012-04-12 14:23:49 -07006032 args.doPostInstall(res.returnCode, res.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006033 }
Christopher Tate1bb69062010-02-19 17:02:12 -08006034
6035 // A restore should be performed at this point if (a) the install
6036 // succeeded, (b) the operation is not an update, and (c) the new
6037 // package has a backupAgent defined.
6038 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08006039 boolean doRestore = (!update
6040 && res.pkg != null
6041 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08006042
6043 // Set up the post-install work request bookkeeping. This will be used
6044 // and cleaned up by the post-install event handling regardless of whether
6045 // there's a restore pass performed. Token values are >= 1.
6046 int token;
6047 if (mNextInstallToken < 0) mNextInstallToken = 1;
6048 token = mNextInstallToken++;
6049
6050 PostInstallData data = new PostInstallData(args, res);
6051 mRunningInstalls.put(token, data);
6052 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
6053
6054 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
6055 // Pass responsibility to the Backup Manager. It will perform a
6056 // restore if appropriate, then pass responsibility back to the
6057 // Package Manager to run the post-install observer callbacks
6058 // and broadcasts.
6059 IBackupManager bm = IBackupManager.Stub.asInterface(
6060 ServiceManager.getService(Context.BACKUP_SERVICE));
6061 if (bm != null) {
6062 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
6063 + " to BM for possible restore");
6064 try {
6065 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
6066 } catch (RemoteException e) {
6067 // can't happen; the backup manager is local
6068 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006069 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08006070 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006071 }
Christopher Tate1bb69062010-02-19 17:02:12 -08006072 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006073 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08006074 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006076 }
Christopher Tate1bb69062010-02-19 17:02:12 -08006077
6078 if (!doRestore) {
6079 // No restore possible, or the Backup Manager was mysteriously not
6080 // available -- just fire the post-install work request directly.
6081 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
6082 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
6083 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006085 }
6086 });
6087 }
6088
Kenny Root5ab21572011-07-27 11:11:19 -07006089 private abstract class HandlerParams {
6090 private static final int MAX_RETRIES = 4;
6091
6092 /**
6093 * Number of times startCopy() has been attempted and had a non-fatal
6094 * error.
6095 */
6096 private int mRetries = 0;
6097
Amith Yamasani6ec10122012-08-23 13:49:25 -07006098 /** User handle for the user requesting the information or installation. */
6099 private final UserHandle mUser;
6100
6101 HandlerParams(UserHandle user) {
6102 mUser = user;
6103 }
6104
6105 UserHandle getUser() {
6106 return mUser;
6107 }
6108
Dianne Hackborn7d608422011-08-07 16:24:18 -07006109 final boolean startCopy() {
6110 boolean res;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006111 try {
Kenny Root5ab21572011-07-27 11:11:19 -07006112 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy");
6113
6114 if (++mRetries > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006115 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006116 mHandler.sendEmptyMessage(MCS_GIVE_UP);
6117 handleServiceError();
Dianne Hackborn7d608422011-08-07 16:24:18 -07006118 return false;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006119 } else {
6120 handleStartCopy();
Dianne Hackborn7d608422011-08-07 16:24:18 -07006121 res = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006122 }
6123 } catch (RemoteException e) {
Kenny Root5ab21572011-07-27 11:11:19 -07006124 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006125 mHandler.sendEmptyMessage(MCS_RECONNECT);
Dianne Hackborn7d608422011-08-07 16:24:18 -07006126 res = false;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006127 }
6128 handleReturnCode();
Dianne Hackborn7d608422011-08-07 16:24:18 -07006129 return res;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006130 }
6131
6132 final void serviceError() {
Kenny Root5ab21572011-07-27 11:11:19 -07006133 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006134 handleServiceError();
6135 handleReturnCode();
6136 }
Kenny Root5ab21572011-07-27 11:11:19 -07006137
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006138 abstract void handleStartCopy() throws RemoteException;
6139 abstract void handleServiceError();
6140 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006141 }
6142
Kenny Root366949c2011-01-14 17:18:14 -08006143 class MeasureParams extends HandlerParams {
6144 private final PackageStats mStats;
6145 private boolean mSuccess;
6146
6147 private final IPackageStatsObserver mObserver;
6148
Kenny Roota69b7eb2012-05-14 14:47:06 -07006149 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
Amith Yamasani6ec10122012-08-23 13:49:25 -07006150 super(new UserHandle(stats.userHandle));
Kenny Root366949c2011-01-14 17:18:14 -08006151 mObserver = observer;
6152 mStats = stats;
Kenny Root366949c2011-01-14 17:18:14 -08006153 }
6154
6155 @Override
6156 void handleStartCopy() throws RemoteException {
Kenny Roota69b7eb2012-05-14 14:47:06 -07006157 synchronized (mInstallLock) {
Dianne Hackborn0c380492012-08-20 17:23:30 -07006158 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
Kenny Roota69b7eb2012-05-14 14:47:06 -07006159 }
Kenny Root366949c2011-01-14 17:18:14 -08006160
Kenny Roota69b7eb2012-05-14 14:47:06 -07006161 final boolean mounted;
Kenny Root366949c2011-01-14 17:18:14 -08006162 if (Environment.isExternalStorageEmulated()) {
6163 mounted = true;
6164 } else {
6165 final String status = Environment.getExternalStorageState();
Jeff Sharkeyb049e212012-09-07 23:16:01 -07006166 mounted = (Environment.MEDIA_MOUNTED.equals(status)
6167 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
Kenny Root366949c2011-01-14 17:18:14 -08006168 }
6169
6170 if (mounted) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07006171 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
6172
6173 final File externalCacheDir = userEnv
Kenny Root366949c2011-01-14 17:18:14 -08006174 .getExternalStorageAppCacheDirectory(mStats.packageName);
6175 final long externalCacheSize = mContainerService
6176 .calculateDirectorySize(externalCacheDir.getPath());
6177 mStats.externalCacheSize = externalCacheSize;
6178
Jeff Sharkeyb049e212012-09-07 23:16:01 -07006179 final File externalDataDir = userEnv
Kenny Root366949c2011-01-14 17:18:14 -08006180 .getExternalStorageAppDataDirectory(mStats.packageName);
6181 long externalDataSize = mContainerService.calculateDirectorySize(externalDataDir
6182 .getPath());
6183
6184 if (externalCacheDir.getParentFile().equals(externalDataDir)) {
6185 externalDataSize -= externalCacheSize;
6186 }
6187 mStats.externalDataSize = externalDataSize;
6188
Jeff Sharkeyb049e212012-09-07 23:16:01 -07006189 final File externalMediaDir = userEnv
Kenny Root366949c2011-01-14 17:18:14 -08006190 .getExternalStorageAppMediaDirectory(mStats.packageName);
6191 mStats.externalMediaSize = mContainerService
Kenny Rootc7624d92011-02-23 16:25:25 -08006192 .calculateDirectorySize(externalMediaDir.getPath());
Kenny Rootbcd6c962011-01-17 11:21:49 -08006193
Jeff Sharkeyb049e212012-09-07 23:16:01 -07006194 final File externalObbDir = userEnv
Kenny Rootbcd6c962011-01-17 11:21:49 -08006195 .getExternalStorageAppObbDirectory(mStats.packageName);
6196 mStats.externalObbSize = mContainerService.calculateDirectorySize(externalObbDir
6197 .getPath());
Kenny Root366949c2011-01-14 17:18:14 -08006198 }
6199 }
6200
6201 @Override
6202 void handleReturnCode() {
6203 if (mObserver != null) {
6204 try {
6205 mObserver.onGetStatsCompleted(mStats, mSuccess);
6206 } catch (RemoteException e) {
6207 Slog.i(TAG, "Observer no longer exists.");
6208 }
6209 }
6210 }
6211
6212 @Override
6213 void handleServiceError() {
6214 Slog.e(TAG, "Could not measure application " + mStats.packageName
6215 + " external storage");
6216 }
6217 }
6218
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006219 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006220 final IPackageInstallObserver observer;
6221 int flags;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006222
6223 private final Uri mPackageURI;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006224 final String installerPackageName;
rich cannings706e8ba2012-08-20 13:20:14 -07006225 final VerificationParams verificationParams;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006226 private InstallArgs mArgs;
6227 private int mRet;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006228 private File mTempPackage;
6229 final ContainerEncryptionParams encryptionParams;
Kenny Root5ab21572011-07-27 11:11:19 -07006230
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006231 InstallParams(Uri packageURI,
6232 IPackageInstallObserver observer, int flags,
rich cannings706e8ba2012-08-20 13:20:14 -07006233 String installerPackageName, VerificationParams verificationParams,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006234 ContainerEncryptionParams encryptionParams, UserHandle user) {
Amith Yamasani6ec10122012-08-23 13:49:25 -07006235 super(user);
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006236 this.mPackageURI = packageURI;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006237 this.flags = flags;
6238 this.observer = observer;
6239 this.installerPackageName = installerPackageName;
rich cannings706e8ba2012-08-20 13:20:14 -07006240 this.verificationParams = verificationParams;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006241 this.encryptionParams = encryptionParams;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006242 }
6243
rich cannings706e8ba2012-08-20 13:20:14 -07006244 public ManifestDigest getManifestDigest() {
6245 if (verificationParams == null) {
6246 return null;
6247 }
6248 return verificationParams.getManifestDigest();
6249 }
6250
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006251 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
6252 String packageName = pkgLite.packageName;
6253 int installLocation = pkgLite.installLocation;
6254 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Kenny Root447106f2011-03-23 11:00:15 -07006255 // reader
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006256 synchronized (mPackages) {
6257 PackageParser.Package pkg = mPackages.get(packageName);
6258 if (pkg != null) {
6259 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006260 // Check for downgrading.
6261 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
6262 if (pkgLite.versionCode < pkg.mVersionCode) {
6263 Slog.w(TAG, "Can't install update of " + packageName
6264 + " update version " + pkgLite.versionCode
6265 + " is older than installed version "
6266 + pkg.mVersionCode);
6267 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
6268 }
6269 }
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006270 // Check for updated system application.
6271 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6272 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006273 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006274 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
6275 }
6276 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
6277 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006278 if (onSd) {
6279 // Install flag overrides everything.
6280 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
6281 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07006282 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006283 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
6284 // Application explicitly specified internal.
6285 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
6286 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
6287 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07006288 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006289 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07006290 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07006291 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
6292 }
6293 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006294 }
6295 }
6296 } else {
6297 // Invalid install. Return error code
6298 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
6299 }
6300 }
6301 }
6302 // All the special cases have been taken care of.
6303 // Return result based on recommended install location.
6304 if (onSd) {
6305 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
6306 }
6307 return pkgLite.recommendedInstallLocation;
6308 }
6309
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006310 /*
6311 * Invoke remote method to get package information and install
6312 * location values. Override install location based on default
6313 * policy if needed and then create install arguments based
6314 * on the install location.
6315 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006316 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08006317 int ret = PackageManager.INSTALL_SUCCEEDED;
Kenny Root05ca4c92011-09-15 10:36:25 -07006318 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
6319 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
6320 PackageInfoLite pkgLite = null;
6321
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07006322 if (onInt && onSd) {
6323 // Check if both bits are set.
6324 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
6325 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006326 } else {
Kenny Root62e1b4e2011-03-14 17:13:39 -07006327 final long lowThreshold;
6328
6329 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
6330 .getService(DeviceStorageMonitorService.SERVICE);
6331 if (dsm == null) {
6332 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
6333 lowThreshold = 0L;
6334 } else {
6335 lowThreshold = dsm.getMemoryLowThreshold();
6336 }
6337
Kenny Root11128572010-10-11 10:51:32 -07006338 try {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006339 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
Kenny Root11128572010-10-11 10:51:32 -07006340 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root11128572010-10-11 10:51:32 -07006341
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006342 final File packageFile;
6343 if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006344 mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
6345 if (mTempPackage != null) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08006346 ParcelFileDescriptor out;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006347 try {
6348 out = ParcelFileDescriptor.open(mTempPackage,
6349 ParcelFileDescriptor.MODE_READ_WRITE);
6350 } catch (FileNotFoundException e) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08006351 out = null;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006352 Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
6353 }
6354
6355 // Make a temporary file for decryption.
6356 ret = mContainerService
6357 .copyResource(mPackageURI, encryptionParams, out);
Dianne Hackborn40e9f292012-11-27 19:12:23 -08006358 IoUtils.closeQuietly(out);
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006359
6360 packageFile = mTempPackage;
6361
6362 FileUtils.setPermissions(packageFile.getAbsolutePath(),
Kenny Root0b2fa8c2012-09-14 10:26:16 -07006363 FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
6364 | FileUtils.S_IROTH,
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006365 -1, -1);
6366 } else {
6367 packageFile = null;
6368 }
6369 } else {
6370 packageFile = new File(mPackageURI.getPath());
6371 }
6372
6373 if (packageFile != null) {
6374 // Remote call to find out default install location
Kenny Rootcea37432012-10-18 14:57:33 -07006375 final String packageFilePath = packageFile.getAbsolutePath();
6376 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
6377 lowThreshold);
6378
6379 /*
6380 * If we have too little free space, try to free cache
6381 * before giving up.
6382 */
6383 if (pkgLite.recommendedInstallLocation
6384 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
6385 final long size = mContainerService.calculateInstalledSize(
6386 packageFilePath, isForwardLocked());
6387 if (mInstaller.freeCache(size + lowThreshold) >= 0) {
6388 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
6389 flags, lowThreshold);
6390 }
Kenny Root3f96d0e2012-12-11 12:48:08 -08006391 /*
6392 * The cache free must have deleted the file we
6393 * downloaded to install.
6394 *
6395 * TODO: fix the "freeCache" call to not delete
6396 * the file we care about.
6397 */
6398 if (pkgLite.recommendedInstallLocation
6399 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
6400 pkgLite.recommendedInstallLocation
6401 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
6402 }
Kenny Rootcea37432012-10-18 14:57:33 -07006403 }
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006404 }
6405 } finally {
6406 mContext.revokeUriPermission(mPackageURI,
6407 Intent.FLAG_GRANT_READ_URI_PERMISSION);
6408 }
6409 }
6410
6411 if (ret == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006412 int loc = pkgLite.recommendedInstallLocation;
Kenny Root1ebd74a2011-08-03 15:09:44 -07006413 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006414 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Kenny Root1ebd74a2011-08-03 15:09:44 -07006415 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006416 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
Kenny Root1ebd74a2011-08-03 15:09:44 -07006417 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006418 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6419 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
6420 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Kenny Root1ebd74a2011-08-03 15:09:44 -07006421 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
6422 ret = PackageManager.INSTALL_FAILED_INVALID_URI;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006423 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
Kenny Root1ebd74a2011-08-03 15:09:44 -07006424 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006425 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006426 // Override with defaults if needed.
6427 loc = installLocationPolicy(pkgLite, flags);
Kenny Roota3e90792012-10-18 10:58:36 -07006428 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
6429 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
6430 } else if (!onSd && !onInt) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07006431 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006432 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
6433 // Set the flag to install on external media.
6434 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07006435 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006436 } else {
6437 // Make sure the flag for installing on external
6438 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07006439 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006440 flags &= ~PackageManager.INSTALL_EXTERNAL;
6441 }
6442 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006443 }
6444 }
Kenny Root5ab21572011-07-27 11:11:19 -07006445
6446 final InstallArgs args = createInstallArgs(this);
Kenny Root05ca4c92011-09-15 10:36:25 -07006447 mArgs = args;
6448
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006449 if (ret == PackageManager.INSTALL_SUCCEEDED) {
rich cannings36070b42012-10-09 11:50:15 -07006450 /*
6451 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
6452 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
6453 */
6454 int userIdentifier = getUser().getIdentifier();
6455 if (userIdentifier == UserHandle.USER_ALL
6456 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
6457 userIdentifier = UserHandle.USER_OWNER;
6458 }
6459
Kenny Root5ab21572011-07-27 11:11:19 -07006460 /*
6461 * Determine if we have any installed package verifiers. If we
6462 * do, then we'll defer to them to verify the packages.
6463 */
Kenny Root05ca4c92011-09-15 10:36:25 -07006464 final int requiredUid = mRequiredVerifierPackage == null ? -1
rich cannings36070b42012-10-09 11:50:15 -07006465 : getPackageUid(mRequiredVerifierPackage, userIdentifier);
rich cannings4e5753f2012-09-19 16:03:56 -07006466 if (requiredUid != -1 && isVerificationEnabled(flags)) {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006467 final Intent verification = new Intent(
6468 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
6469 verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
Kenny Root05ca4c92011-09-15 10:36:25 -07006470 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root5ab21572011-07-27 11:11:19 -07006471
Andy Stadler250ce282012-08-24 16:09:03 -07006472 final List<ResolveInfo> receivers = queryIntentReceivers(verification,
6473 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
6474 0 /* TODO: Which userId? */);
Kenny Root05ca4c92011-09-15 10:36:25 -07006475
6476 if (DEBUG_VERIFY) {
Kenny Root5ab21572011-07-27 11:11:19 -07006477 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
Kenny Root05ca4c92011-09-15 10:36:25 -07006478 + verification.toString() + " with " + pkgLite.verifiers.length
6479 + " optional verifiers");
Kenny Root5ab21572011-07-27 11:11:19 -07006480 }
6481
6482 final int verificationId = mPendingVerificationToken++;
6483
6484 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
6485
6486 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
6487 installerPackageName);
6488
6489 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
6490
rich cannings13d428e2012-09-13 13:43:07 -07006491 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
6492 pkgLite.packageName);
6493
6494 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
6495 pkgLite.versionCode);
6496
rich cannings706e8ba2012-08-20 13:20:14 -07006497 if (verificationParams != null) {
6498 if (verificationParams.getVerificationURI() != null) {
6499 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
6500 verificationParams.getVerificationURI());
6501 }
6502 if (verificationParams.getOriginatingURI() != null) {
6503 verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
6504 verificationParams.getOriginatingURI());
6505 }
6506 if (verificationParams.getReferrer() != null) {
6507 verification.putExtra(Intent.EXTRA_REFERRER,
6508 verificationParams.getReferrer());
6509 }
Ben Gruver37d83a32012-09-27 13:02:06 -07006510 if (verificationParams.getOriginatingUid() >= 0) {
6511 verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
6512 verificationParams.getOriginatingUid());
6513 }
rich cannings13d428e2012-09-13 13:43:07 -07006514 if (verificationParams.getInstallerUid() >= 0) {
6515 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
6516 verificationParams.getInstallerUid());
6517 }
Kenny Root5ab21572011-07-27 11:11:19 -07006518 }
6519
Kenny Root05ca4c92011-09-15 10:36:25 -07006520 final PackageVerificationState verificationState = new PackageVerificationState(
6521 requiredUid, args);
6522
6523 mPendingVerification.append(verificationId, verificationState);
6524
6525 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
6526 receivers, verificationState);
Kenny Root5ab21572011-07-27 11:11:19 -07006527
6528 /*
Kenny Root05ca4c92011-09-15 10:36:25 -07006529 * If any sufficient verifiers were listed in the package
6530 * manifest, attempt to ask them.
Kenny Root5ab21572011-07-27 11:11:19 -07006531 */
Kenny Root05ca4c92011-09-15 10:36:25 -07006532 if (sufficientVerifiers != null) {
6533 final int N = sufficientVerifiers.size();
6534 if (N == 0) {
6535 Slog.i(TAG, "Additional verifiers required, but none installed.");
6536 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
6537 } else {
6538 for (int i = 0; i < N; i++) {
6539 final ComponentName verifierComponent = sufficientVerifiers.get(i);
6540
6541 final Intent sufficientIntent = new Intent(verification);
6542 sufficientIntent.setComponent(verifierComponent);
6543
rich canningsd55deb02012-10-02 14:53:08 -07006544 mContext.sendBroadcastAsUser(sufficientIntent, getUser());
Kenny Root05ca4c92011-09-15 10:36:25 -07006545 }
6546 }
6547 }
6548
6549 final ComponentName requiredVerifierComponent = matchComponentForVerifier(
6550 mRequiredVerifierPackage, receivers);
6551 if (ret == PackageManager.INSTALL_SUCCEEDED
6552 && mRequiredVerifierPackage != null) {
6553 /*
6554 * Send the intent to the required verification agent,
6555 * but only start the verification timeout after the
6556 * target BroadcastReceivers have run.
6557 */
6558 verification.setComponent(requiredVerifierComponent);
rich canningsd55deb02012-10-02 14:53:08 -07006559 mContext.sendOrderedBroadcastAsUser(verification, getUser(),
Kenny Root05ca4c92011-09-15 10:36:25 -07006560 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
6561 new BroadcastReceiver() {
6562 @Override
6563 public void onReceive(Context context, Intent intent) {
6564 final Message msg = mHandler
6565 .obtainMessage(CHECK_PENDING_VERIFICATION);
6566 msg.arg1 = verificationId;
6567 mHandler.sendMessageDelayed(msg, getVerificationTimeout());
6568 }
6569 }, null, 0, null, null);
6570
6571 /*
6572 * We don't want the copy to proceed until verification
6573 * succeeds, so null out this field.
6574 */
6575 mArgs = null;
6576 }
Kenny Root5ab21572011-07-27 11:11:19 -07006577 } else {
Kenny Root05ca4c92011-09-15 10:36:25 -07006578 /*
6579 * No package verification is enabled, so immediately start
6580 * the remote call to initiate copy using temporary file.
6581 */
Kenny Root5ab21572011-07-27 11:11:19 -07006582 ret = args.copyApk(mContainerService, true);
6583 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006584 }
Kenny Root5ab21572011-07-27 11:11:19 -07006585
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006586 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006587 }
6588
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006589 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006590 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07006591 // If mArgs is null, then MCS couldn't be reached. When it
6592 // reconnects, it will try again to install. At that point, this
6593 // will succeed.
6594 if (mArgs != null) {
6595 processPendingInstall(mArgs, mRet);
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006596
Kenny Root0b2fa8c2012-09-14 10:26:16 -07006597 if (mTempPackage != null) {
6598 if (!mTempPackage.delete()) {
6599 Slog.w(TAG, "Couldn't delete temporary file: " +
6600 mTempPackage.getAbsolutePath());
6601 }
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006602 }
6603 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006604 }
6605
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006606 @Override
6607 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006608 mArgs = createInstallArgs(this);
6609 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006610 }
Kenny Root6dceb882012-04-12 14:23:49 -07006611
6612 public boolean isForwardLocked() {
6613 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
6614 }
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006615
6616 public Uri getPackageUri() {
6617 if (mTempPackage != null) {
6618 return Uri.fromFile(mTempPackage);
6619 } else {
6620 return mPackageURI;
6621 }
6622 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006623 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006624
6625 /*
6626 * Utility class used in movePackage api.
6627 * srcArgs and targetArgs are not set for invalid flags and make
6628 * sure to do null checks when invoking methods on them.
6629 * We probably want to return ErrorPrams for both failed installs
6630 * and moves.
6631 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006632 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006633 final IPackageMoveObserver observer;
6634 final int flags;
6635 final String packageName;
6636 final InstallArgs srcArgs;
6637 final InstallArgs targetArgs;
Kenny Root6dceb882012-04-12 14:23:49 -07006638 int uid;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006639 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07006640
6641 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
Amith Yamasani6ec10122012-08-23 13:49:25 -07006642 String packageName, String dataDir, int uid, UserHandle user) {
6643 super(user);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006644 this.srcArgs = srcArgs;
6645 this.observer = observer;
6646 this.flags = flags;
6647 this.packageName = packageName;
Kenny Root6dceb882012-04-12 14:23:49 -07006648 this.uid = uid;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006649 if (srcArgs != null) {
6650 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07006651 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006652 } else {
6653 targetArgs = null;
6654 }
6655 }
6656
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006657 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006658 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6659 // Check for storage space on target medium
6660 if (!targetArgs.checkFreeStorage(mContainerService)) {
6661 Log.w(TAG, "Insufficient storage to install");
6662 return;
6663 }
Kenny Rootbf023582012-05-02 16:56:15 -07006664
6665 mRet = srcArgs.doPreCopy();
6666 if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6667 return;
6668 }
6669
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006670 mRet = targetArgs.copyApk(mContainerService, false);
Kenny Rootbf023582012-05-02 16:56:15 -07006671 if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6672 srcArgs.doPostCopy(uid);
6673 return;
6674 }
6675
6676 mRet = srcArgs.doPostCopy(uid);
6677 if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6678 return;
6679 }
6680
6681 mRet = targetArgs.doPreInstall(mRet);
6682 if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6683 return;
6684 }
6685
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006686 if (DEBUG_SD_INSTALL) {
6687 StringBuilder builder = new StringBuilder();
6688 if (srcArgs != null) {
6689 builder.append("src: ");
6690 builder.append(srcArgs.getCodePath());
6691 }
6692 if (targetArgs != null) {
6693 builder.append(" target : ");
6694 builder.append(targetArgs.getCodePath());
6695 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006696 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006697 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006698 }
6699
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006700 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006701 void handleReturnCode() {
Kenny Root6dceb882012-04-12 14:23:49 -07006702 targetArgs.doPostInstall(mRet, uid);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006703 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
6704 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
6705 currentStatus = PackageManager.MOVE_SUCCEEDED;
6706 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
6707 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
6708 }
6709 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006710 }
6711
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006712 @Override
6713 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006714 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006715 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006716 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006717
Kenny Root6dceb882012-04-12 14:23:49 -07006718 /**
6719 * Used during creation of InstallArgs
6720 *
6721 * @param flags package installation flags
6722 * @return true if should be installed on external storage
6723 */
6724 private static boolean installOnSd(int flags) {
6725 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
6726 return false;
6727 }
6728 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
6729 return true;
6730 }
6731 return false;
6732 }
6733
6734 /**
6735 * Used during creation of InstallArgs
6736 *
6737 * @param flags package installation flags
6738 * @return true if should be installed as forward locked
6739 */
6740 private static boolean installForwardLocked(int flags) {
6741 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
6742 }
6743
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006744 private InstallArgs createInstallArgs(InstallParams params) {
Kenny Root6dceb882012-04-12 14:23:49 -07006745 if (installOnSd(params.flags) || params.isForwardLocked()) {
6746 return new AsecInstallArgs(params);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006747 } else {
6748 return new FileInstallArgs(params);
6749 }
6750 }
6751
Kenny Root85387d72010-08-26 10:13:11 -07006752 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
6753 String nativeLibraryPath) {
Kenny Root84e35ea2012-06-06 16:05:05 -07006754 final boolean isInAsec;
6755 if (installOnSd(flags)) {
6756 /* Apps on SD card are always in ASEC containers. */
6757 isInAsec = true;
6758 } else if (installForwardLocked(flags)
6759 && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
6760 /*
6761 * Forward-locked apps are only in ASEC containers if they're the
6762 * new style
6763 */
6764 isInAsec = true;
6765 } else {
6766 isInAsec = false;
6767 }
6768
6769 if (isInAsec) {
Kenny Root6dceb882012-04-12 14:23:49 -07006770 return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
Kenny Rootbf023582012-05-02 16:56:15 -07006771 installOnSd(flags), installForwardLocked(flags));
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006772 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006773 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006774 }
6775 }
6776
Kenny Root85387d72010-08-26 10:13:11 -07006777 // Used by package mover
6778 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Kenny Root6dceb882012-04-12 14:23:49 -07006779 if (installOnSd(flags) || installForwardLocked(flags)) {
Kenny Rootbf023582012-05-02 16:56:15 -07006780 String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
6781 + AsecInstallArgs.RES_FILE_NAME);
6782 return new AsecInstallArgs(packageURI, cid, installOnSd(flags),
6783 installForwardLocked(flags));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006784 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006785 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006786 }
6787 }
6788
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006789 static abstract class InstallArgs {
6790 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006791 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006792 final int flags;
6793 final Uri packageURI;
6794 final String installerPackageName;
Kenny Root5ab21572011-07-27 11:11:19 -07006795 final ManifestDigest manifestDigest;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006796 final UserHandle user;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006797
Kenny Root5ab21572011-07-27 11:11:19 -07006798 InstallArgs(Uri packageURI, IPackageInstallObserver observer, int flags,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006799 String installerPackageName, ManifestDigest manifestDigest,
6800 UserHandle user) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006801 this.packageURI = packageURI;
6802 this.flags = flags;
6803 this.observer = observer;
6804 this.installerPackageName = installerPackageName;
Kenny Root5ab21572011-07-27 11:11:19 -07006805 this.manifestDigest = manifestDigest;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006806 this.user = user;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006807 }
6808
6809 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006810 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006811 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006812 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Kenny Root6dceb882012-04-12 14:23:49 -07006813
6814 abstract int doPostInstall(int status, int uid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006815 abstract String getCodePath();
6816 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07006817 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006818 // Need installer lock especially for dex file removal.
6819 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006820 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006821 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Kenny Root6dceb882012-04-12 14:23:49 -07006822
Kenny Rootbf023582012-05-02 16:56:15 -07006823 /**
6824 * Called before the source arguments are copied. This is used mostly
6825 * for MoveParams when it needs to read the source file to put it in the
6826 * destination.
6827 */
6828 int doPreCopy() {
6829 return PackageManager.INSTALL_SUCCEEDED;
6830 }
6831
6832 /**
6833 * Called after the source arguments are copied. This is used mostly for
6834 * MoveParams when it needs to read the source file to put it in the
6835 * destination.
6836 *
6837 * @return
6838 */
6839 int doPostCopy(int uid) {
6840 return PackageManager.INSTALL_SUCCEEDED;
6841 }
6842
Kenny Root6dceb882012-04-12 14:23:49 -07006843 protected boolean isFwdLocked() {
6844 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
6845 }
rich canningsd55deb02012-10-02 14:53:08 -07006846
6847 UserHandle getUser() {
6848 return user;
6849 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006850 }
6851
6852 class FileInstallArgs extends InstallArgs {
6853 File installDir;
6854 String codeFileName;
6855 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07006856 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006857 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006858
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006859 FileInstallArgs(InstallParams params) {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006860 super(params.getPackageUri(), params.observer, params.flags,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006861 params.installerPackageName, params.getManifestDigest(),
6862 params.getUser());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006863 }
6864
Kenny Root85387d72010-08-26 10:13:11 -07006865 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006866 super(null, null, 0, null, null, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006867 File codeFile = new File(fullCodePath);
6868 installDir = codeFile.getParentFile();
6869 codeFileName = fullCodePath;
6870 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07006871 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006872 }
6873
Kenny Root85387d72010-08-26 10:13:11 -07006874 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006875 super(packageURI, null, 0, null, null, null);
Kenny Root85387d72010-08-26 10:13:11 -07006876 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006877 String apkName = getNextCodePath(null, pkgName, ".apk");
6878 codeFileName = new File(installDir, apkName + ".apk").getPath();
6879 resourceFileName = getResourcePathFromCodePath();
Kenny Rootddbe50d2012-09-06 13:18:37 -07006880 libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006881 }
6882
Kenny Root11128572010-10-11 10:51:32 -07006883 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
Kenny Root62e1b4e2011-03-14 17:13:39 -07006884 final long lowThreshold;
6885
6886 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
6887 .getService(DeviceStorageMonitorService.SERVICE);
6888 if (dsm == null) {
6889 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
6890 lowThreshold = 0L;
6891 } else {
6892 if (dsm.isMemoryLow()) {
6893 Log.w(TAG, "Memory is reported as being too low; aborting package install");
6894 return false;
6895 }
6896
6897 lowThreshold = dsm.getMemoryLowThreshold();
6898 }
6899
Kenny Root11128572010-10-11 10:51:32 -07006900 try {
6901 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
6902 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root6dceb882012-04-12 14:23:49 -07006903 return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
Kenny Root11128572010-10-11 10:51:32 -07006904 } finally {
6905 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
6906 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006907 }
6908
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006909 String getCodePath() {
6910 return codeFileName;
6911 }
6912
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006913 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07006914 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006915 codeFileName = createTempPackageFile(installDir).getPath();
6916 resourceFileName = getResourcePathFromCodePath();
Kenny Rootddbe50d2012-09-06 13:18:37 -07006917 libraryPath = getLibraryPathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006918 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006919 }
6920
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006921 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006922 if (temp) {
6923 // Generate temp file name
6924 createCopyFile();
6925 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006926 // Get a ParcelFileDescriptor to write to the output file
6927 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006928 if (!created) {
6929 try {
6930 codeFile.createNewFile();
6931 // Set permissions
6932 if (!setPermissions()) {
6933 // Failed setting permissions.
6934 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6935 }
6936 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006937 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006938 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6939 }
6940 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006941 ParcelFileDescriptor out = null;
6942 try {
Kenny Root85387d72010-08-26 10:13:11 -07006943 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006944 } catch (FileNotFoundException e) {
Kenny Rootf5121a92011-08-10 16:23:32 -07006945 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006946 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6947 }
6948 // Copy the resource now
6949 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6950 try {
Kenny Root11128572010-10-11 10:51:32 -07006951 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
6952 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006953 ret = imcs.copyResource(packageURI, null, out);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006954 } finally {
Kenny Root2782a472012-04-14 21:48:21 -07006955 IoUtils.closeQuietly(out);
Kenny Root11128572010-10-11 10:51:32 -07006956 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006957 }
Kenny Root85387d72010-08-26 10:13:11 -07006958
Kenny Root2782a472012-04-14 21:48:21 -07006959 if (isFwdLocked()) {
6960 final File destResourceFile = new File(getResourcePath());
6961
6962 // Copy the public files
6963 try {
6964 PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
6965 } catch (IOException e) {
6966 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
6967 + " forward-locked app.");
6968 destResourceFile.delete();
6969 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6970 }
6971 }
Kenny Rootddbe50d2012-09-06 13:18:37 -07006972
6973 final File nativeLibraryFile = new File(getNativeLibraryPath());
6974 Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
6975 if (nativeLibraryFile.exists()) {
6976 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
6977 nativeLibraryFile.delete();
6978 }
6979 try {
6980 int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile);
6981 if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6982 return copyRet;
6983 }
6984 } catch (IOException e) {
6985 Slog.e(TAG, "Copying native libraries failed", e);
6986 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
6987 }
6988
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006989 return ret;
6990 }
6991
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006992 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006993 if (status != PackageManager.INSTALL_SUCCEEDED) {
6994 cleanUp();
6995 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006996 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006997 }
6998
6999 boolean doRename(int status, final String pkgName, String oldCodePath) {
7000 if (status != PackageManager.INSTALL_SUCCEEDED) {
7001 cleanUp();
7002 return false;
7003 } else {
Kenny Root2782a472012-04-14 21:48:21 -07007004 final File oldCodeFile = new File(getCodePath());
7005 final File oldResourceFile = new File(getResourcePath());
Kenny Rootddbe50d2012-09-06 13:18:37 -07007006 final File oldLibraryFile = new File(getNativeLibraryPath());
Kenny Root2782a472012-04-14 21:48:21 -07007007
7008 // Rename APK file based on packageName
7009 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
7010 final File newCodeFile = new File(installDir, apkName + ".apk");
7011 if (!oldCodeFile.renameTo(newCodeFile)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007012 return false;
7013 }
Kenny Root2782a472012-04-14 21:48:21 -07007014 codeFileName = newCodeFile.getPath();
7015
7016 // Rename public resource file if it's forward-locked.
7017 final File newResFile = new File(getResourcePathFromCodePath());
7018 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
7019 return false;
7020 }
Kenny Rootddbe50d2012-09-06 13:18:37 -07007021 resourceFileName = newResFile.getPath();
7022
7023 // Rename library path
7024 final File newLibraryFile = new File(getLibraryPathFromCodePath());
7025 if (newLibraryFile.exists()) {
7026 NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
7027 newLibraryFile.delete();
7028 }
7029 if (!oldLibraryFile.renameTo(newLibraryFile)) {
7030 Slog.e(TAG, "Cannot rename native library directory "
7031 + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
7032 return false;
7033 }
7034 libraryPath = newLibraryFile.getPath();
Kenny Root2782a472012-04-14 21:48:21 -07007035
7036 // Attempt to set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007037 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007038 return false;
7039 }
Kenny Root2782a472012-04-14 21:48:21 -07007040
rpcraig554cb0c2012-07-05 06:41:43 -04007041 if (!SELinux.restorecon(newCodeFile)) {
7042 return false;
7043 }
7044
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007045 return true;
7046 }
7047 }
7048
Kenny Root6dceb882012-04-12 14:23:49 -07007049 int doPostInstall(int status, int uid) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007050 if (status != PackageManager.INSTALL_SUCCEEDED) {
7051 cleanUp();
7052 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007053 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007054 }
7055
7056 String getResourcePath() {
7057 return resourceFileName;
7058 }
7059
Kenny Root2782a472012-04-14 21:48:21 -07007060 private String getResourcePathFromCodePath() {
7061 final String codePath = getCodePath();
7062 if (isFwdLocked()) {
7063 final StringBuilder sb = new StringBuilder();
7064
7065 sb.append(mAppInstallDir.getPath());
7066 sb.append('/');
7067 sb.append(getApkName(codePath));
7068 sb.append(".zip");
7069
7070 /*
7071 * If our APK is a temporary file, mark the resource as a
7072 * temporary file as well so it can be cleaned up after
7073 * catastrophic failure.
7074 */
7075 if (codePath.endsWith(".tmp")) {
7076 sb.append(".tmp");
7077 }
7078
7079 return sb.toString();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007080 } else {
7081 return codePath;
7082 }
7083 }
7084
Kenny Rootddbe50d2012-09-06 13:18:37 -07007085 private String getLibraryPathFromCodePath() {
7086 return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
7087 }
7088
Kenny Root85387d72010-08-26 10:13:11 -07007089 @Override
7090 String getNativeLibraryPath() {
Kenny Rootddbe50d2012-09-06 13:18:37 -07007091 if (libraryPath == null) {
7092 libraryPath = getLibraryPathFromCodePath();
7093 }
Kenny Root85387d72010-08-26 10:13:11 -07007094 return libraryPath;
7095 }
7096
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007097 private boolean cleanUp() {
7098 boolean ret = true;
7099 String sourceDir = getCodePath();
7100 String publicSourceDir = getResourcePath();
7101 if (sourceDir != null) {
7102 File sourceFile = new File(sourceDir);
7103 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007104 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007105 ret = false;
7106 }
7107 // Delete application's code and resources
7108 sourceFile.delete();
7109 }
7110 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
7111 final File publicSourceFile = new File(publicSourceDir);
7112 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007113 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007114 }
7115 if (publicSourceFile.exists()) {
7116 publicSourceFile.delete();
7117 }
7118 }
Kenny Rootddbe50d2012-09-06 13:18:37 -07007119
7120 if (libraryPath != null) {
7121 File nativeLibraryFile = new File(libraryPath);
7122 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
7123 if (!nativeLibraryFile.delete()) {
7124 Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
7125 }
7126 }
7127
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007128 return ret;
7129 }
7130
7131 void cleanUpResourcesLI() {
7132 String sourceDir = getCodePath();
Jeff Brown5d6d90f2011-07-11 13:04:53 -07007133 if (cleanUp()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007134 int retCode = mInstaller.rmdex(sourceDir);
7135 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007136 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007137 + " at location "
7138 + sourceDir + ", retcode=" + retCode);
7139 // we don't consider this to be a failure of the core package deletion
7140 }
7141 }
7142 }
7143
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007144 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007145 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07007146 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007147 final int filePermissions =
7148 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
7149 |FileUtils.S_IROTH;
7150 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
7151 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007152 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007153 getCodePath()
7154 + ". The return code was: " + retCode);
7155 // TODO Define new internal error
7156 return false;
7157 }
7158 return true;
7159 }
7160 return true;
7161 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007162
7163 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07007164 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007165 cleanUpResourcesLI();
7166 return true;
7167 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007168 }
7169
Kenny Root51a573c2012-05-17 13:30:28 -07007170 private boolean isAsecExternal(String cid) {
7171 final String asecPath = PackageHelper.getSdFilesystem(cid);
7172 return !asecPath.startsWith(mAsecInternalPath);
7173 }
7174
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07007175 /**
7176 * Extract the MountService "container ID" from the full code path of an
7177 * .apk.
7178 */
7179 static String cidFromCodePath(String fullCodePath) {
7180 int eidx = fullCodePath.lastIndexOf("/");
7181 String subStr1 = fullCodePath.substring(0, eidx);
7182 int sidx = subStr1.lastIndexOf("/");
7183 return subStr1.substring(sidx+1, eidx);
7184 }
7185
Kenny Root6dceb882012-04-12 14:23:49 -07007186 class AsecInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007187 static final String RES_FILE_NAME = "pkg.apk";
Kenny Root6dceb882012-04-12 14:23:49 -07007188 static final String PUBLIC_RES_FILE_NAME = "res.zip";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007189
Kenny Root85387d72010-08-26 10:13:11 -07007190 String cid;
7191 String packagePath;
Kenny Root6dceb882012-04-12 14:23:49 -07007192 String resourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07007193 String libraryPath;
7194
Kenny Root6dceb882012-04-12 14:23:49 -07007195 AsecInstallArgs(InstallParams params) {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07007196 super(params.getPackageUri(), params.observer, params.flags,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007197 params.installerPackageName, params.getManifestDigest(),
7198 params.getUser());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007199 }
7200
Kenny Root6dceb882012-04-12 14:23:49 -07007201 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
Kenny Rootbf023582012-05-02 16:56:15 -07007202 boolean isExternal, boolean isForwardLocked) {
7203 super(null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007204 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
7205 null, null, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007206 // Extract cid from fullCodePath
7207 int eidx = fullCodePath.lastIndexOf("/");
7208 String subStr1 = fullCodePath.substring(0, eidx);
7209 int sidx = subStr1.lastIndexOf("/");
7210 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07007211 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007212 }
7213
Kenny Rootc7a89992012-06-05 15:13:17 -07007214 AsecInstallArgs(String cid, boolean isForwardLocked) {
7215 super(null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007216 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
7217 null, null, null);
Dianne Hackbornaa77de12010-05-14 22:33:54 -07007218 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07007219 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007220 }
7221
Kenny Rootbf023582012-05-02 16:56:15 -07007222 AsecInstallArgs(Uri packageURI, String cid, boolean isExternal, boolean isForwardLocked) {
7223 super(packageURI, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007224 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
7225 null, null, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007226 this.cid = cid;
7227 }
7228
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007229 void createCopyFile() {
7230 cid = getTempContainerId();
7231 }
7232
Kenny Root11128572010-10-11 10:51:32 -07007233 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
7234 try {
7235 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
7236 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root6dceb882012-04-12 14:23:49 -07007237 return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
Kenny Root11128572010-10-11 10:51:32 -07007238 } finally {
7239 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
7240 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08007241 }
7242
Kenny Root6dceb882012-04-12 14:23:49 -07007243 private final boolean isExternal() {
7244 return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
7245 }
7246
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007247 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007248 if (temp) {
7249 createCopyFile();
Kenny Rootf5121a92011-08-10 16:23:32 -07007250 } else {
7251 /*
7252 * Pre-emptively destroy the container since it's destroyed if
7253 * copying fails due to it existing anyway.
7254 */
7255 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007256 }
Kenny Root11128572010-10-11 10:51:32 -07007257
7258 final String newCachePath;
7259 try {
7260 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
7261 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root6dceb882012-04-12 14:23:49 -07007262 newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
7263 RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
Kenny Root11128572010-10-11 10:51:32 -07007264 } finally {
7265 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
7266 }
7267
Kenny Root85387d72010-08-26 10:13:11 -07007268 if (newCachePath != null) {
7269 setCachePath(newCachePath);
7270 return PackageManager.INSTALL_SUCCEEDED;
7271 } else {
7272 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7273 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007274 }
7275
7276 @Override
7277 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07007278 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007279 }
7280
7281 @Override
7282 String getResourcePath() {
Kenny Root6dceb882012-04-12 14:23:49 -07007283 return resourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07007284 }
7285
7286 @Override
7287 String getNativeLibraryPath() {
7288 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007289 }
7290
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007291 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007292 if (status != PackageManager.INSTALL_SUCCEEDED) {
7293 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08007294 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007295 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08007296 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007297 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07007298 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
7299 Process.SYSTEM_UID);
7300 if (newCachePath != null) {
7301 setCachePath(newCachePath);
7302 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007303 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7304 }
7305 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007306 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007307 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007308 }
7309
7310 boolean doRename(int status, final String pkgName,
7311 String oldCodePath) {
7312 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007313 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007314 if (PackageHelper.isContainerMounted(cid)) {
7315 // Unmount the container
7316 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007317 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007318 return false;
7319 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007320 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007321 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07007322 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
7323 " which might be stale. Will try to clean up.");
7324 // Clean up the stale container and proceed to recreate.
7325 if (!PackageHelper.destroySdDir(newCacheId)) {
7326 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
7327 return false;
7328 }
7329 // Successfully cleaned up stale container. Try to rename again.
7330 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
7331 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
7332 + " inspite of cleaning it up.");
7333 return false;
7334 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007335 }
7336 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007337 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007338 newCachePath = PackageHelper.mountSdDir(newCacheId,
7339 getEncryptKey(), Process.SYSTEM_UID);
7340 } else {
7341 newCachePath = PackageHelper.getSdDir(newCacheId);
7342 }
7343 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007344 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007345 return false;
7346 }
7347 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07007348 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007349 " at new path: " + newCachePath);
7350 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07007351 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007352 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007353 }
7354
Kenny Root85387d72010-08-26 10:13:11 -07007355 private void setCachePath(String newCachePath) {
7356 File cachePath = new File(newCachePath);
7357 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
7358 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
Kenny Root6dceb882012-04-12 14:23:49 -07007359
7360 if (isFwdLocked()) {
7361 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
7362 } else {
7363 resourcePath = packagePath;
7364 }
Kenny Root85387d72010-08-26 10:13:11 -07007365 }
7366
Kenny Root6dceb882012-04-12 14:23:49 -07007367 int doPostInstall(int status, int uid) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007368 if (status != PackageManager.INSTALL_SUCCEEDED) {
7369 cleanUp();
7370 } else {
Kenny Rootbf023582012-05-02 16:56:15 -07007371 final int groupOwner;
7372 final String protectedFile;
7373 if (isFwdLocked()) {
Kenny Roote091f222012-09-11 15:01:26 -07007374 groupOwner = UserHandle.getSharedAppGid(uid);
Kenny Rootbf023582012-05-02 16:56:15 -07007375 protectedFile = RES_FILE_NAME;
7376 } else {
7377 groupOwner = -1;
7378 protectedFile = null;
7379 }
7380
Kenny Root6dceb882012-04-12 14:23:49 -07007381 if (uid < Process.FIRST_APPLICATION_UID
Kenny Rootbf023582012-05-02 16:56:15 -07007382 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
Kenny Root6dceb882012-04-12 14:23:49 -07007383 Slog.e(TAG, "Failed to finalize " + cid);
7384 PackageHelper.destroySdDir(cid);
7385 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7386 }
7387
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08007388 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007389 if (!mounted) {
Kenny Root6dceb882012-04-12 14:23:49 -07007390 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007391 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007392 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007393 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007394 }
7395
7396 private void cleanUp() {
Kenny Root6dceb882012-04-12 14:23:49 -07007397 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
7398
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007399 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08007400 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007401 }
7402
7403 void cleanUpResourcesLI() {
7404 String sourceFile = getCodePath();
7405 // Remove dex file
Jeff Brown5d6d90f2011-07-11 13:04:53 -07007406 int retCode = mInstaller.rmdex(sourceFile);
7407 if (retCode < 0) {
7408 Slog.w(TAG, "Couldn't remove dex file for package: "
7409 + " at location "
7410 + sourceFile.toString() + ", retcode=" + retCode);
7411 // we don't consider this to be a failure of the core package deletion
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007412 }
7413 cleanUp();
7414 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007415
7416 boolean matchContainer(String app) {
7417 if (cid.startsWith(app)) {
7418 return true;
7419 }
7420 return false;
7421 }
7422
7423 String getPackageName() {
Kenny Rootc7a89992012-06-05 15:13:17 -07007424 return getAsecPackageName(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007425 }
7426
7427 boolean doPostDeleteLI(boolean delete) {
7428 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08007429 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007430 if (mounted) {
7431 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08007432 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007433 }
7434 if (ret && delete) {
7435 cleanUpResourcesLI();
7436 }
7437 return ret;
7438 }
Kenny Rootbf023582012-05-02 16:56:15 -07007439
7440 @Override
7441 int doPreCopy() {
7442 if (isFwdLocked()) {
7443 if (!PackageHelper.fixSdPermissions(cid,
7444 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
7445 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7446 }
7447 }
7448
7449 return PackageManager.INSTALL_SUCCEEDED;
7450 }
7451
7452 @Override
7453 int doPostCopy(int uid) {
7454 if (isFwdLocked()) {
Kenny Rootbf023582012-05-02 16:56:15 -07007455 if (uid < Process.FIRST_APPLICATION_UID
Kenny Roote091f222012-09-11 15:01:26 -07007456 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
7457 RES_FILE_NAME)) {
Kenny Rootbf023582012-05-02 16:56:15 -07007458 Slog.e(TAG, "Failed to finalize " + cid);
7459 PackageHelper.destroySdDir(cid);
7460 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7461 }
7462 }
7463
7464 return PackageManager.INSTALL_SUCCEEDED;
7465 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007466 };
7467
Kenny Rootc7a89992012-06-05 15:13:17 -07007468 static String getAsecPackageName(String packageCid) {
7469 int idx = packageCid.lastIndexOf("-");
7470 if (idx == -1) {
7471 return packageCid;
7472 }
7473 return packageCid.substring(0, idx);
7474 }
7475
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007476 // Utility method used to create code paths based on package name and available index.
7477 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
7478 String idxStr = "";
7479 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007480 // Fall back to default value of idx=1 if prefix is not
7481 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007482 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00007483 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007484 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00007485 if (subStr.endsWith(suffix)) {
7486 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007487 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007488 // If oldCodePath already contains prefix find out the
7489 // ending index to either increment or decrement.
7490 int sidx = subStr.lastIndexOf(prefix);
7491 if (sidx != -1) {
7492 subStr = subStr.substring(sidx + prefix.length());
7493 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007494 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
7495 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007496 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007497 try {
7498 idx = Integer.parseInt(subStr);
7499 if (idx <= 1) {
7500 idx++;
7501 } else {
7502 idx--;
7503 }
7504 } catch(NumberFormatException e) {
7505 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007506 }
7507 }
7508 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007509 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007510 return prefix + idxStr;
7511 }
7512
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007513 // Utility method used to ignore ADD/REMOVE events
7514 // by directory observer.
7515 private static boolean ignoreCodePath(String fullPathStr) {
7516 String apkName = getApkName(fullPathStr);
7517 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
7518 if (idx != -1 && ((idx+1) < apkName.length())) {
7519 // Make sure the package ends with a numeral
7520 String version = apkName.substring(idx+1);
7521 try {
7522 Integer.parseInt(version);
7523 return true;
7524 } catch (NumberFormatException e) {}
7525 }
7526 return false;
7527 }
7528
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007529 // Utility method that returns the relative package path with respect
7530 // to the installation directory. Like say for /data/data/com.test-1.apk
7531 // string com.test-1 is returned.
7532 static String getApkName(String codePath) {
7533 if (codePath == null) {
7534 return null;
7535 }
7536 int sidx = codePath.lastIndexOf("/");
7537 int eidx = codePath.lastIndexOf(".");
7538 if (eidx == -1) {
7539 eidx = codePath.length();
7540 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007541 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007542 return null;
7543 }
7544 return codePath.substring(sidx+1, eidx);
7545 }
7546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007547 class PackageInstalledInfo {
7548 String name;
7549 int uid;
Dianne Hackborn786b4402012-08-27 15:14:02 -07007550 // The set of users that originally had this package installed.
7551 int[] origUsers;
7552 // The set of users that now have this package installed.
7553 int[] newUsers;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007554 PackageParser.Package pkg;
7555 int returnCode;
7556 PackageRemovedInfo removedInfo;
7557 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007559 /*
7560 * Install a non-existing package.
7561 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007562 private void installNewPackageLI(PackageParser.Package pkg,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007563 int parseFlags, int scanMode, UserHandle user,
Jacek Surazski65e13172009-04-28 15:26:38 +02007564 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007565 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007566 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08007567
Dave Burke383fa182012-10-23 23:12:19 -07007568 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007569 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07007570 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
7571 // A package with the same name is already installed, though
7572 // it has been renamed to an older name. The package we
7573 // are trying to install should be installed as an update to
7574 // the existing one, but that has not been requested, so bail.
7575 Slog.w(TAG, "Attempt to re-install " + pkgName
7576 + " without first uninstalling package running as "
7577 + mSettings.mRenamedPackages.get(pkgName));
7578 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
7579 return;
7580 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007581 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007582 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007583 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007584 + " without first uninstalling.");
7585 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
7586 return;
7587 }
7588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007589 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007590 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007591 System.currentTimeMillis(), user);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007592 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007593 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007594 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
7595 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
7596 }
7597 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007598 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02007599 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007600 res);
7601 // delete the partially installed application. the data directory will have to be
7602 // restored if it was already existing
7603 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
7604 // remove package from internal structures. Note that we want deletePackageX to
7605 // delete the package data and cache directories that it created in
7606 // scanPackageLocked, unless those directories existed before we even tried to
7607 // install.
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007608 deletePackageLI(pkgName, UserHandle.ALL, false,
7609 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007610 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007611 }
7612 }
7613 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007614
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007615 private void replacePackageLI(PackageParser.Package pkg,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007616 int parseFlags, int scanMode, UserHandle user,
Jacek Surazski65e13172009-04-28 15:26:38 +02007617 String installerPackageName, PackageInstalledInfo res) {
7618
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007619 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007620 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007621 // First find the old package info and check signatures
7622 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007623 oldPackage = mPackages.get(pkgName);
Kenny Root447106f2011-03-23 11:00:15 -07007624 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07007625 != PackageManager.SIGNATURE_MATCH) {
Kenny Root8c11f1d2012-04-14 12:10:38 -07007626 Slog.w(TAG, "New package has a different signature: " + pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007627 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
7628 return;
7629 }
7630 }
Kenny Root85387d72010-08-26 10:13:11 -07007631 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007632 if (sysPkg) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007633 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
7634 user, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007635 } else {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007636 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
7637 user, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007638 }
7639 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007641 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007642 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
Jacek Surazski65e13172009-04-28 15:26:38 +02007643 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007644 PackageParser.Package newPackage = null;
7645 String pkgName = deletedPackage.packageName;
7646 boolean deletedPkg = true;
7647 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007648
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007649 long origUpdateTime;
7650 if (pkg.mExtras != null) {
7651 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
7652 } else {
7653 origUpdateTime = 0;
7654 }
7655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007656 // First delete the existing package while retaining the data directory
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007657 if (!deletePackageLI(pkgName, null, true, PackageManager.DELETE_KEEP_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007658 res.removedInfo, true)) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007659 // If the existing package wasn't successfully deleted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007660 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
7661 deletedPkg = false;
7662 } else {
7663 // Successfully deleted the old package. Now proceed with re-installation
7664 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007665 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007666 System.currentTimeMillis(), user);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007667 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007668 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007669 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
7670 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08007671 }
7672 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007673 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02007674 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007675 res);
7676 updatedSettings = true;
7677 }
7678 }
7679
Suchi Amalapurapuae181712010-03-30 14:01:02 -07007680 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007681 // remove package from internal structures. Note that we want deletePackageX to
7682 // delete the package data and cache directories that it created in
7683 // scanPackageLocked, unless those directories existed before we even tried to
7684 // install.
7685 if(updatedSettings) {
7686 deletePackageLI(
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007687 pkgName, null, true,
7688 PackageManager.DELETE_KEEP_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007689 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007690 }
7691 // Since we failed to install the new package we need to restore the old
7692 // package that we deleted.
7693 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07007694 File restoreFile = new File(deletedPackage.mPath);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007695 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07007696 boolean oldOnSd = isExternal(deletedPackage);
7697 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
7698 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
7699 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007700 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
7701 | SCAN_UPDATE_TIME;
7702 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
Dianne Hackborn786b4402012-08-27 15:14:02 -07007703 origUpdateTime, null) == null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07007704 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
7705 return;
7706 }
7707 // Restore of old package succeeded. Update permissions.
Kenny Root447106f2011-03-23 11:00:15 -07007708 // writer
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007709 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07007710 updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
Dianne Hackborne639da72012-02-21 15:11:13 -08007711 UPDATE_PERMISSIONS_ALL);
Kenny Root447106f2011-03-23 11:00:15 -07007712 // can downgrade to reader
7713 mSettings.writeLPr();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007714 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07007715 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007716 }
7717 }
7718 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007720 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007721 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
Jacek Surazski65e13172009-04-28 15:26:38 +02007722 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007723 PackageParser.Package newPackage = null;
7724 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007725 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007726 PackageParser.PARSE_IS_SYSTEM;
7727 String packageName = deletedPackage.packageName;
7728 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
7729 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007730 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007731 return;
7732 }
7733 PackageParser.Package oldPkg;
7734 PackageSetting oldPkgSetting;
Kenny Root447106f2011-03-23 11:00:15 -07007735 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007736 synchronized (mPackages) {
7737 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007738 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007739 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
7740 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007741 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007742 return;
7743 }
7744 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007745
7746 killApplication(packageName, oldPkg.applicationInfo.uid);
7747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007748 res.removedInfo.uid = oldPkg.applicationInfo.uid;
7749 res.removedInfo.removedPackage = packageName;
7750 // Remove existing system package
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007751 removePackageLI(oldPkgSetting, true);
Kenny Root447106f2011-03-23 11:00:15 -07007752 // writer
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08007753 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07007754 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007755 // We didn't need to disable the .apk as a current system package,
7756 // which means we are replacing another update that is already
7757 // installed. We need to make sure to delete the older one's .apk.
Kenny Root6dceb882012-04-12 14:23:49 -07007758 res.removedInfo.args = createInstallArgs(0,
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007759 deletedPackage.applicationInfo.sourceDir,
7760 deletedPackage.applicationInfo.publicSourceDir,
7761 deletedPackage.applicationInfo.nativeLibraryDir);
7762 } else {
7763 res.removedInfo.args = null;
7764 }
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08007765 }
7766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007767 // Successfully disabled the old package. Now proceed with re-installation
7768 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
7769 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007770 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007771 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007772 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007773 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
7774 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
7775 }
7776 } else {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007777 if (newPackage.mExtras != null) {
7778 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
7779 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
7780 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
7781 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007782 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007783 updatedSettings = true;
7784 }
7785
Suchi Amalapurapuae181712010-03-30 14:01:02 -07007786 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007787 // Re installation failed. Restore old information
7788 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07007789 if (newPackage != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007790 removeInstalledPackageLI(newPackage, true);
Dianne Hackborn62da8462009-05-13 15:06:13 -07007791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007792 // Add back the old system package
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007793 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007794 // Restore the old system information in Settings
7795 synchronized(mPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007796 if (updatedSettings) {
Kenny Root447106f2011-03-23 11:00:15 -07007797 mSettings.enableSystemPackageLPw(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02007798 mSettings.setInstallerPackageName(packageName,
7799 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007800 }
Kenny Root447106f2011-03-23 11:00:15 -07007801 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007802 }
7803 }
7804 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007805
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007806 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07007807 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007808 int retCode;
7809 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
7810 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
7811 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07007812 if (mNoDexOpt) {
7813 /*
7814 * If we're in an engineering build, programs are lazily run
7815 * through dexopt. If the .dex file doesn't exist yet, it
7816 * will be created when the program is run next.
7817 */
7818 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
7819 } else {
7820 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
7821 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7822 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007823 }
7824 }
7825 return PackageManager.INSTALL_SUCCEEDED;
7826 }
7827
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007828 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02007829 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007830 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007831 synchronized (mPackages) {
7832 //write settings. the installStatus will be incomplete at this stage.
7833 //note that the new package setting would have already been
7834 //added to mPackages. It hasn't been persisted yet.
Kenny Rootcf0b38c2011-03-22 14:17:59 -07007835 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
Kenny Root447106f2011-03-23 11:00:15 -07007836 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007837 }
7838
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07007839 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007840 != PackageManager.INSTALL_SUCCEEDED) {
7841 // Discontinue if moving dex files failed.
7842 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007843 }
Kenny Root6dceb882012-04-12 14:23:49 -07007844
7845 Log.d(TAG, "New package installed in " + newPackage.mPath);
7846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007847 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07007848 updatePermissionsLPw(newPackage.packageName, newPackage,
Dianne Hackborne639da72012-02-21 15:11:13 -08007849 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
7850 ? UPDATE_PERMISSIONS_ALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007851 res.name = pkgName;
7852 res.uid = newPackage.applicationInfo.uid;
7853 res.pkg = newPackage;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07007854 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02007855 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007856 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
7857 //to update install status
Kenny Root447106f2011-03-23 11:00:15 -07007858 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007859 }
7860 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007861
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007862 private void installPackageLI(InstallArgs args,
7863 boolean newInstall, PackageInstalledInfo res) {
7864 int pFlags = args.flags;
7865 String installerPackageName = args.installerPackageName;
7866 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007867 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08007868 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007869 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07007870 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007871 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07007872 // Result object to be returned
7873 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
7874
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007875 // Retrieve PackageSettings and parse package
Kenny Root6dceb882012-04-12 14:23:49 -07007876 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
7877 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
7878 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007879 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
7880 pp.setSeparateProcesses(mSeparateProcesses);
7881 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
7882 null, mMetrics, parseFlags);
7883 if (pkg == null) {
7884 res.returnCode = pp.getParseError();
7885 return;
7886 }
7887 String pkgName = res.name = pkg.packageName;
7888 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
7889 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
7890 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
7891 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007893 }
7894 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
7895 res.returnCode = pp.getParseError();
7896 return;
7897 }
Kenny Root5ab21572011-07-27 11:11:19 -07007898
7899 /* If the installer passed in a manifest digest, compare it now. */
7900 if (args.manifestDigest != null) {
7901 if (DEBUG_INSTALL) {
7902 final String parsedManifest = pkg.manifestDigest == null ? "null"
7903 : pkg.manifestDigest.toString();
7904 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
7905 + parsedManifest);
7906 }
7907
7908 if (!args.manifestDigest.equals(pkg.manifestDigest)) {
7909 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
7910 return;
7911 }
7912 } else if (DEBUG_INSTALL) {
7913 final String parsedManifest = pkg.manifestDigest == null
7914 ? "null" : pkg.manifestDigest.toString();
7915 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
7916 }
7917
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007918 // Get rid of all references to package scan path via parser.
7919 pp = null;
7920 String oldCodePath = null;
7921 boolean systemApp = false;
7922 synchronized (mPackages) {
7923 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007924 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
7925 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08007926 if (pkg.mOriginalPackages != null
7927 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007928 && mPackages.containsKey(oldName)) {
7929 // This package is derived from an original package,
7930 // and this device has been updating from that original
7931 // name. We must continue using the original name, so
7932 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08007933 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007934 pkgName = pkg.packageName;
7935 replace = true;
7936 } else if (mPackages.containsKey(pkgName)) {
7937 // This package, under its official name, already exists
7938 // on the device; we should replace it.
7939 replace = true;
7940 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007941 }
7942 PackageSetting ps = mSettings.mPackages.get(pkgName);
7943 if (ps != null) {
7944 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
7945 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7946 systemApp = (ps.pkg.applicationInfo.flags &
7947 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07007948 }
Dianne Hackborn786b4402012-08-27 15:14:02 -07007949 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
Dianne Hackbornade3eca2009-05-11 18:54:45 -07007950 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007951 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007952
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007953 if (systemApp && onSd) {
7954 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007955 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007956 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
7957 return;
7958 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08007959
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007960 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
7961 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7962 return;
7963 }
7964 // Set application objects path explicitly after the rename
7965 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07007966 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007967 if (replace) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007968 replacePackageLI(pkg, parseFlags, scanMode, args.user,
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007969 installerPackageName, res);
7970 } else {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007971 installNewPackageLI(pkg, parseFlags, scanMode, args.user,
Dianne Hackborn786b4402012-08-27 15:14:02 -07007972 installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007973 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007974 synchronized (mPackages) {
Dianne Hackborn786b4402012-08-27 15:14:02 -07007975 final PackageSetting ps = mSettings.mPackages.get(pkgName);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007976 if (ps != null) {
Dianne Hackborn786b4402012-08-27 15:14:02 -07007977 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007978 }
7979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007980 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007981
Kenny Root85387d72010-08-26 10:13:11 -07007982 private static boolean isForwardLocked(PackageParser.Package pkg) {
7983 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007984 }
7985
Kenny Root88670d82012-05-09 15:47:35 -07007986
7987 private boolean isForwardLocked(PackageSetting ps) {
7988 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
7989 }
7990
Kenny Root85387d72010-08-26 10:13:11 -07007991 private static boolean isExternal(PackageParser.Package pkg) {
7992 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
7993 }
7994
Kenny Root6dceb882012-04-12 14:23:49 -07007995 private static boolean isExternal(PackageSetting ps) {
7996 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
7997 }
7998
Kenny Root85387d72010-08-26 10:13:11 -07007999 private static boolean isSystemApp(PackageParser.Package pkg) {
8000 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
8001 }
8002
Kenny Root502e9a42011-01-10 13:48:15 -08008003 private static boolean isSystemApp(ApplicationInfo info) {
8004 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
8005 }
8006
Kenny Root208d3412012-05-07 19:42:35 -07008007 private static boolean isSystemApp(PackageSetting ps) {
8008 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
8009 }
8010
Kenny Root85387d72010-08-26 10:13:11 -07008011 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
8012 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008013 }
8014
Kenny Root88670d82012-05-09 15:47:35 -07008015 private int packageFlagsToInstallFlags(PackageSetting ps) {
8016 int installFlags = 0;
8017 if (isExternal(ps)) {
8018 installFlags |= PackageManager.INSTALL_EXTERNAL;
8019 }
8020 if (isForwardLocked(ps)) {
8021 installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
8022 }
8023 return installFlags;
8024 }
8025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008026 private void deleteTempPackageFiles() {
Kenny Root0b2fa8c2012-09-14 10:26:16 -07008027 final FilenameFilter filter = new FilenameFilter() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008028 public boolean accept(File dir, String name) {
8029 return name.startsWith("vmdl") && name.endsWith(".tmp");
8030 }
8031 };
Kenny Root0b2fa8c2012-09-14 10:26:16 -07008032 deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
8033 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
8034 }
8035
8036 private static final void deleteTempPackageFilesInDirectory(File directory,
8037 FilenameFilter filter) {
8038 final String[] tmpFilesList = directory.list(filter);
8039 if (tmpFilesList == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008040 return;
8041 }
Kenny Root0b2fa8c2012-09-14 10:26:16 -07008042 for (int i = 0; i < tmpFilesList.length; i++) {
8043 final File tmpFile = new File(directory, tmpFilesList[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008044 tmpFile.delete();
8045 }
8046 }
8047
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008048 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008049 File tmpPackageFile;
8050 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008051 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008052 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008053 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008054 return null;
8055 }
8056 try {
8057 FileUtils.setPermissions(
8058 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
8059 -1, -1);
rpcraig554cb0c2012-07-05 06:41:43 -04008060 if (!SELinux.restorecon(tmpPackageFile)) {
8061 return null;
8062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008063 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008064 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008065 return null;
8066 }
8067 return tmpPackageFile;
8068 }
8069
8070 public void deletePackage(final String packageName,
8071 final IPackageDeleteObserver observer,
8072 final int flags) {
8073 mContext.enforceCallingOrSelfPermission(
8074 android.Manifest.permission.DELETE_PACKAGES, null);
8075 // Queue up an async operation since the package deletion may take a little while.
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008076 final int uid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008077 mHandler.post(new Runnable() {
8078 public void run() {
8079 mHandler.removeCallbacks(this);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008080 final int returnCode = deletePackageX(packageName, uid, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008081 if (observer != null) {
8082 try {
Kenny Rootc39bb4a2011-02-28 13:27:19 -08008083 observer.packageDeleted(packageName, returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008084 } catch (RemoteException e) {
8085 Log.i(TAG, "Observer no longer exists.");
8086 } //end catch
8087 } //end if
8088 } //end run
8089 });
8090 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008092 /**
8093 * This method is an internal method that could be get invoked either
8094 * to delete an installed package or to clean up a failed installation.
8095 * After deleting an installed package, a broadcast is sent to notify any
8096 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008097 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008098 * installation wouldn't have sent the initial broadcast either
8099 * The key steps in deleting a package are
8100 * deleting the package information in internal structures like mPackages,
8101 * deleting the packages base directories through installd
8102 * updating mSettings to reflect current status
8103 * persisting settings for later use
8104 * sending a broadcast if necessary
8105 */
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008106 private int deletePackageX(String packageName, int uid, int flags) {
Kenny Rootc39bb4a2011-02-28 13:27:19 -08008107 final PackageRemovedInfo info = new PackageRemovedInfo();
8108 final boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008109
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08008110 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
8111 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
8112 try {
Amith Yamasani599dd7c2012-09-14 23:20:08 -07008113 if (dpm != null && dpm.packageHasActiveAdmins(packageName, UserHandle.getUserId(uid))) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008114 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Kenny Rootc39bb4a2011-02-28 13:27:19 -08008115 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08008116 }
8117 } catch (RemoteException e) {
8118 }
Amith Yamasani599dd7c2012-09-14 23:20:08 -07008119
Dianne Hackbornc72fc672012-09-20 13:12:03 -07008120 boolean removedForAllUsers = false;
8121 boolean systemUpdate = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008122 synchronized (mInstallLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008123 res = deletePackageLI(packageName,
8124 (flags & PackageManager.DELETE_ALL_USERS) != 0
8125 ? UserHandle.ALL : new UserHandle(UserHandle.getUserId(uid)),
8126 true, flags | REMOVE_CHATTY, info, true);
Dianne Hackbornc72fc672012-09-20 13:12:03 -07008127 systemUpdate = info.isRemovedPackageSystemUpdate;
8128 if (res && !systemUpdate && mPackages.get(packageName) == null) {
8129 removedForAllUsers = true;
8130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008131 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008132
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008133 if (res) {
Dianne Hackbornc72fc672012-09-20 13:12:03 -07008134 info.sendBroadcast(true, systemUpdate, removedForAllUsers);
Romain Guy96f43572009-03-24 20:27:49 -07008135
Dianne Hackbornc72fc672012-09-20 13:12:03 -07008136 // If the removed package was a system update, the old system package
Romain Guy96f43572009-03-24 20:27:49 -07008137 // was re-enabled; we need to broadcast this information
8138 if (systemUpdate) {
8139 Bundle extras = new Bundle(1);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008140 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
8141 ? info.removedAppId : info.uid);
Romain Guy96f43572009-03-24 20:27:49 -07008142 extras.putBoolean(Intent.EXTRA_REPLACING, true);
8143
Dianne Hackborne7f97212011-02-24 14:40:20 -08008144 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008145 extras, null, null, null);
Dianne Hackborne7f97212011-02-24 14:40:20 -08008146 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008147 extras, null, null, null);
Dianne Hackborne7f97212011-02-24 14:40:20 -08008148 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008149 null, packageName, null, null);
Romain Guy96f43572009-03-24 20:27:49 -07008150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008151 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07008152 // Force a gc here.
8153 Runtime.getRuntime().gc();
8154 // Delete the resources here after sending the broadcast to let
8155 // other processes clean up before deleting resources.
8156 if (info.args != null) {
8157 synchronized (mInstallLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008158 info.args.doPostDeleteLI(true);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07008159 }
8160 }
Kenny Rootc39bb4a2011-02-28 13:27:19 -08008161
8162 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008163 }
8164
8165 static class PackageRemovedInfo {
8166 String removedPackage;
8167 int uid = -1;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008168 int removedAppId = -1;
8169 int[] removedUsers = null;
Romain Guy96f43572009-03-24 20:27:49 -07008170 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008171 // Clean up resources deleted packages.
8172 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07008173
Dianne Hackbornc72fc672012-09-20 13:12:03 -07008174 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008175 Bundle extras = new Bundle(1);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008176 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008177 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
8178 if (replacing) {
8179 extras.putBoolean(Intent.EXTRA_REPLACING, true);
8180 }
Dianne Hackbornc72fc672012-09-20 13:12:03 -07008181 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008182 if (removedPackage != null) {
Dianne Hackborne7f97212011-02-24 14:40:20 -08008183 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008184 extras, null, null, removedUsers);
Dianne Hackbornf9abb402011-08-10 15:00:59 -07008185 if (fullRemove && !replacing) {
8186 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008187 extras, null, null, removedUsers);
Dianne Hackbornf9abb402011-08-10 15:00:59 -07008188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008189 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008190 if (removedAppId >= 0) {
Amith Yamasani13593602012-03-22 16:16:17 -07008191 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008192 removedUsers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008193 }
8194 }
8195 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008197 /*
8198 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
8199 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008200 * make sure this flag is set for partially installed apps. If not its meaningless to
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008201 * delete a partially installed application.
8202 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008203 private void removePackageDataLI(PackageSetting ps, PackageRemovedInfo outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008204 int flags, boolean writeSettings) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008205 String packageName = ps.name;
8206 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008207 // Retrieve object to delete permissions for shared user later on
Kenny Root447106f2011-03-23 11:00:15 -07008208 final PackageSetting deletedPs;
8209 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008210 synchronized (mPackages) {
8211 deletedPs = mSettings.mPackages.get(packageName);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008212 if (outInfo != null) {
8213 outInfo.removedPackage = packageName;
8214 outInfo.removedUsers = deletedPs != null
Dianne Hackborn786b4402012-08-27 15:14:02 -07008215 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
8216 : null;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008218 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008219 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07008220 removeDataDirsLI(packageName);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008221 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008222 }
Kenny Root447106f2011-03-23 11:00:15 -07008223 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008224 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008225 if (deletedPs != null) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008226 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008227 if (outInfo != null) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008228 outInfo.removedAppId = mSettings.removePackageLPw(packageName);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008229 }
8230 if (deletedPs != null) {
Dianne Hackborne639da72012-02-21 15:11:13 -08008231 updatePermissionsLPw(deletedPs.name, null, 0);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008232 if (deletedPs.sharedUser != null) {
8233 // remove permissions associated with package
Kenny Root447106f2011-03-23 11:00:15 -07008234 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008235 }
8236 }
Amith Yamasania3f133a2012-08-09 17:11:28 -07008237 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008238 }
8239 }
Kenny Root447106f2011-03-23 11:00:15 -07008240 // can downgrade to reader
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008241 if (writeSettings) {
8242 // Save settings now
Kenny Root447106f2011-03-23 11:00:15 -07008243 mSettings.writeLPr();
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008245 }
8246 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008248 /*
8249 * Tries to delete system package.
8250 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008251 private boolean deleteSystemPackageLI(PackageSetting newPs,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008252 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008253 PackageSetting disabledPs = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008254 // Confirm if the system package has been updated
8255 // An updated system app can be deleted. This will also have to restore
8256 // the system pkg from system partition
Kenny Root447106f2011-03-23 11:00:15 -07008257 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008258 synchronized (mPackages) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008259 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008260 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008261 if (disabledPs == null) {
8262 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008263 return false;
8264 } else {
8265 Log.i(TAG, "Deleting system pkg from data partition");
8266 }
8267 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07008268 outInfo.isRemovedPackageSystemUpdate = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008269 if (disabledPs.versionCode < newPs.versionCode) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008270 // Delete data for downgrades
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008271 flags &= ~PackageManager.DELETE_KEEP_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008272 } else {
8273 // Preserve data by setting flag
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008274 flags |= PackageManager.DELETE_KEEP_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008275 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008276 boolean ret = deleteInstalledPackageLI(newPs, true, flags, outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008277 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008278 if (!ret) {
8279 return false;
8280 }
Kenny Root447106f2011-03-23 11:00:15 -07008281 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008282 synchronized (mPackages) {
8283 // Reinstate the old system package
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008284 mSettings.enableSystemPackageLPw(newPs.name);
Kenny Root8f7cc022010-09-12 09:04:56 -07008285 // Remove any native libraries from the upgraded package.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008286 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008287 }
8288 // Install the system package
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008289 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008290 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008291 SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008293 if (newPkg == null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008294 Slog.w(TAG, "Failed to restore system package:" + newPs.name
8295 + " with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008296 return false;
8297 }
Kenny Root447106f2011-03-23 11:00:15 -07008298 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008299 synchronized (mPackages) {
Dianne Hackborne639da72012-02-21 15:11:13 -08008300 updatePermissionsLPw(newPkg.packageName, newPkg,
8301 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
Kenny Root447106f2011-03-23 11:00:15 -07008302 // can downgrade to reader here
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008303 if (writeSettings) {
Kenny Root447106f2011-03-23 11:00:15 -07008304 mSettings.writeLPr();
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008306 }
8307 return true;
8308 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008309
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008310 private boolean deleteInstalledPackageLI(PackageSetting ps,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008311 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
8312 boolean writeSettings) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008313 if (outInfo != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008314 outInfo.uid = ps.appId;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008316
8317 // Delete package data from internal structures and also remove data if flag is set
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008318 removePackageDataLI(ps, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008319
8320 // Delete application code and resources
Kenny Root92bc9b32012-10-23 17:42:40 -07008321 if (deleteCodeAndResources && (outInfo != null)) {
Kenny Root5455f682012-09-09 14:52:10 -07008322 outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008323 ps.resourcePathString, ps.nativeLibraryPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008324 }
8325 return true;
8326 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008328 /*
8329 * This method handles package deletion in general
8330 */
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008331 private boolean deletePackageLI(String packageName, UserHandle user,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008332 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
8333 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008334 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008335 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008336 return false;
8337 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008338 PackageSetting ps;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008339 boolean dataOnly = false;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008340 int removeUser = -1;
8341 int appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008342 synchronized (mPackages) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008343 ps = mSettings.mPackages.get(packageName);
8344 if (ps == null) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008345 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
8346 return false;
8347 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008348 if (!isSystemApp(ps) && user != null
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008349 && user.getIdentifier() != UserHandle.USER_ALL) {
8350 // The caller is asking that the package only be deleted for a single
8351 // user. To do this, we just mark its uninstalled state and delete
8352 // its data.
8353 ps.setUserState(user.getIdentifier(),
8354 COMPONENT_ENABLED_STATE_DEFAULT,
8355 false, //installed
8356 true, //stopped
8357 true, //notLaunched
8358 null, null);
8359 if (ps.isAnyInstalled(sUserManager.getUserIds())) {
8360 // Other user still have this package installed, so all
8361 // we need to do is clear this user's data and save that
8362 // it is uninstalled.
8363 removeUser = user.getIdentifier();
8364 appId = ps.appId;
8365 mSettings.writePackageRestrictionsLPr(removeUser);
8366 } else {
8367 // We need to set it back to 'installed' so the uninstall
8368 // broadcasts will be sent correctly.
8369 ps.setInstalled(true, user.getIdentifier());
8370 }
8371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008372 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008373
8374 if (removeUser >= 0) {
8375 // From above, we determined that we are deleting this only
8376 // for a single user. Continue the work here.
8377 if (outInfo != null) {
8378 outInfo.removedPackage = packageName;
8379 outInfo.removedAppId = appId;
8380 outInfo.removedUsers = new int[] {removeUser};
8381 }
8382 mInstaller.clearUserData(packageName, removeUser);
8383 schedulePackageCleaning(packageName, removeUser, false);
8384 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008385 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008387 if (dataOnly) {
8388 // Delete application data first
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008389 removePackageDataLI(ps, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008390 return true;
8391 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008392 boolean ret = false;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008393 if (isSystemApp(ps)) {
8394 Log.i(TAG, "Removing system package:" + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008395 // When an updated system application is deleted we delete the existing resources as well and
8396 // fall back to existing code in system partition
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008397 ret = deleteSystemPackageLI(ps, flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008398 } else {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008399 Log.i(TAG, "Removing non-system package:" + ps.name);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008400 // Kill application pre-emptively especially for apps on sd.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008401 killApplication(packageName, ps.appId);
8402 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008403 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008404 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008405 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008406 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008407
Dianne Hackborn183ce022012-06-29 15:00:21 -07008408 private final class ClearStorageConnection implements ServiceConnection {
8409 IMediaContainerService mContainerService;
8410
8411 @Override
8412 public void onServiceConnected(ComponentName name, IBinder service) {
8413 synchronized (this) {
8414 mContainerService = IMediaContainerService.Stub.asInterface(service);
8415 notifyAll();
8416 }
8417 }
8418
8419 @Override
8420 public void onServiceDisconnected(ComponentName name) {
8421 }
8422 }
8423
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008424 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
Dianne Hackborn183ce022012-06-29 15:00:21 -07008425 final boolean mounted;
8426 if (Environment.isExternalStorageEmulated()) {
8427 mounted = true;
8428 } else {
8429 final String status = Environment.getExternalStorageState();
8430
8431 mounted = status.equals(Environment.MEDIA_MOUNTED)
8432 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
8433 }
8434
8435 if (!mounted) {
8436 return;
8437 }
8438
8439 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008440 int[] users;
8441 if (userId == UserHandle.USER_ALL) {
8442 users = sUserManager.getUserIds();
8443 } else {
8444 users = new int[] { userId };
8445 }
Jeff Sharkey752cd922012-09-23 16:25:12 -07008446 final ClearStorageConnection conn = new ClearStorageConnection();
Amith Yamasani27b89e62013-01-16 12:30:11 -08008447 if (mContext.bindServiceAsUser(
8448 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
Jeff Sharkey752cd922012-09-23 16:25:12 -07008449 try {
8450 for (int curUser : users) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008451 long timeout = SystemClock.uptimeMillis() + 5000;
8452 synchronized (conn) {
8453 long now = SystemClock.uptimeMillis();
8454 while (conn.mContainerService == null && now < timeout) {
8455 try {
8456 conn.wait(timeout - now);
8457 } catch (InterruptedException e) {
8458 }
Dianne Hackborn183ce022012-06-29 15:00:21 -07008459 }
8460 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008461 if (conn.mContainerService == null) {
8462 return;
8463 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07008464
8465 final UserEnvironment userEnv = new UserEnvironment(curUser);
8466 final File externalCacheDir = userEnv
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008467 .getExternalStorageAppCacheDirectory(packageName);
Dianne Hackborn183ce022012-06-29 15:00:21 -07008468 try {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008469 conn.mContainerService.clearDirectory(externalCacheDir.toString());
Dianne Hackborn183ce022012-06-29 15:00:21 -07008470 } catch (RemoteException e) {
8471 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008472 if (allData) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07008473 final File externalDataDir = userEnv
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008474 .getExternalStorageAppDataDirectory(packageName);
8475 try {
8476 conn.mContainerService.clearDirectory(externalDataDir.toString());
8477 } catch (RemoteException e) {
8478 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07008479 final File externalMediaDir = userEnv
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008480 .getExternalStorageAppMediaDirectory(packageName);
8481 try {
8482 conn.mContainerService.clearDirectory(externalMediaDir.toString());
8483 } catch (RemoteException e) {
8484 }
Dianne Hackborn183ce022012-06-29 15:00:21 -07008485 }
8486 }
Jeff Sharkey752cd922012-09-23 16:25:12 -07008487 } finally {
8488 mContext.unbindService(conn);
Dianne Hackborn183ce022012-06-29 15:00:21 -07008489 }
8490 }
8491 }
8492
Amith Yamasani483f3b02012-03-13 16:08:00 -07008493 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008494 public void clearApplicationUserData(final String packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07008495 final IPackageDataObserver observer, final int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008496 mContext.enforceCallingOrSelfPermission(
8497 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
Amith Yamasanif203aee2012-08-29 18:41:53 -07008498 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008499 // Queue up an async operation since the package deletion may take a little while.
8500 mHandler.post(new Runnable() {
8501 public void run() {
8502 mHandler.removeCallbacks(this);
8503 final boolean succeeded;
8504 synchronized (mInstallLock) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008505 succeeded = clearApplicationUserDataLI(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008506 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008507 clearExternalStorageDataSync(packageName, userId, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008508 if (succeeded) {
8509 // invoke DeviceStorageMonitor's update method to clear any notifications
8510 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
8511 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
8512 if (dsm != null) {
8513 dsm.updateMemory();
8514 }
8515 }
8516 if(observer != null) {
8517 try {
8518 observer.onRemoveCompleted(packageName, succeeded);
8519 } catch (RemoteException e) {
8520 Log.i(TAG, "Observer no longer exists.");
8521 }
8522 } //end if observer
8523 } //end run
8524 });
8525 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008526
Amith Yamasani483f3b02012-03-13 16:08:00 -07008527 private boolean clearApplicationUserDataLI(String packageName, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008528 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008529 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008530 return false;
8531 }
8532 PackageParser.Package p;
8533 boolean dataOnly = false;
8534 synchronized (mPackages) {
8535 p = mPackages.get(packageName);
8536 if(p == null) {
8537 dataOnly = true;
8538 PackageSetting ps = mSettings.mPackages.get(packageName);
8539 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008540 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008541 return false;
8542 }
8543 p = ps.pkg;
8544 }
8545 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08008546
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08008547 if (!dataOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008548 //need to check this only for fully installed applications
8549 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008550 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008551 return false;
8552 }
8553 final ApplicationInfo applicationInfo = p.applicationInfo;
8554 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008555 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008556 return false;
8557 }
8558 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07008559 int retCode = mInstaller.clearUserData(packageName, userId);
Jeff Brown5d6d90f2011-07-11 13:04:53 -07008560 if (retCode < 0) {
8561 Slog.w(TAG, "Couldn't remove cache files for package: "
8562 + packageName);
8563 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008564 }
8565 return true;
8566 }
8567
8568 public void deleteApplicationCacheFiles(final String packageName,
8569 final IPackageDataObserver observer) {
8570 mContext.enforceCallingOrSelfPermission(
8571 android.Manifest.permission.DELETE_CACHE_FILES, null);
8572 // Queue up an async operation since the package deletion may take a little while.
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008573 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008574 mHandler.post(new Runnable() {
8575 public void run() {
8576 mHandler.removeCallbacks(this);
8577 final boolean succeded;
8578 synchronized (mInstallLock) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008579 succeded = deleteApplicationCacheFilesLI(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008580 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008581 clearExternalStorageDataSync(packageName, userId, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008582 if(observer != null) {
8583 try {
8584 observer.onRemoveCompleted(packageName, succeded);
8585 } catch (RemoteException e) {
8586 Log.i(TAG, "Observer no longer exists.");
8587 }
8588 } //end if observer
8589 } //end run
8590 });
8591 }
8592
Amith Yamasani483f3b02012-03-13 16:08:00 -07008593 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008594 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008595 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008596 return false;
8597 }
8598 PackageParser.Package p;
8599 synchronized (mPackages) {
8600 p = mPackages.get(packageName);
8601 }
8602 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008603 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008604 return false;
8605 }
8606 final ApplicationInfo applicationInfo = p.applicationInfo;
8607 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008608 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008609 return false;
8610 }
Amith Yamasani54289b82012-10-01 10:39:14 -07008611 int retCode = mInstaller.deleteCacheFiles(packageName, userId);
Jeff Brown5d6d90f2011-07-11 13:04:53 -07008612 if (retCode < 0) {
8613 Slog.w(TAG, "Couldn't remove cache files for package: "
Amith Yamasani54289b82012-10-01 10:39:14 -07008614 + packageName + " u" + userId);
Jeff Brown5d6d90f2011-07-11 13:04:53 -07008615 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008616 }
8617 return true;
8618 }
8619
Dianne Hackborn0c380492012-08-20 17:23:30 -07008620 public void getPackageSizeInfo(final String packageName, int userHandle,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008621 final IPackageStatsObserver observer) {
8622 mContext.enforceCallingOrSelfPermission(
8623 android.Manifest.permission.GET_PACKAGE_SIZE, null);
Kenny Root366949c2011-01-14 17:18:14 -08008624
Dianne Hackborn0c380492012-08-20 17:23:30 -07008625 PackageStats stats = new PackageStats(packageName, userHandle);
Kenny Root366949c2011-01-14 17:18:14 -08008626
Kenny Roota69b7eb2012-05-14 14:47:06 -07008627 /*
8628 * Queue up an async operation since the package measurement may take a
8629 * little while.
8630 */
8631 Message msg = mHandler.obtainMessage(INIT_COPY);
8632 msg.obj = new MeasureParams(stats, observer);
8633 mHandler.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008634 }
8635
Dianne Hackborn0c380492012-08-20 17:23:30 -07008636 private boolean getPackageSizeInfoLI(String packageName, int userHandle,
8637 PackageStats pStats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008638 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008639 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008640 return false;
8641 }
8642 PackageParser.Package p;
8643 boolean dataOnly = false;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07008644 String asecPath = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008645 synchronized (mPackages) {
8646 p = mPackages.get(packageName);
8647 if(p == null) {
8648 dataOnly = true;
8649 PackageSetting ps = mSettings.mPackages.get(packageName);
8650 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008651 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008652 return false;
8653 }
8654 p = ps.pkg;
8655 }
Kenny Root2afded12012-06-04 16:39:47 -07008656 if (p != null && (isExternal(p) || isForwardLocked(p))) {
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07008657 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
8658 if (secureContainerId != null) {
8659 asecPath = PackageHelper.getSdFilesystem(secureContainerId);
8660 }
8661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008662 }
8663 String publicSrcDir = null;
8664 if(!dataOnly) {
8665 final ApplicationInfo applicationInfo = p.applicationInfo;
8666 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008667 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008668 return false;
8669 }
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07008670 if (isForwardLocked(p)) {
8671 publicSrcDir = applicationInfo.publicSourceDir;
8672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008673 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008674 int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, publicSrcDir,
Jeff Brown5d6d90f2011-07-11 13:04:53 -07008675 asecPath, pStats);
8676 if (res < 0) {
8677 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008678 }
Kenny Root2afded12012-06-04 16:39:47 -07008679
8680 // Fix-up for forward-locked applications in ASEC containers.
8681 if (!isExternal(p)) {
8682 pStats.codeSize += pStats.externalCodeSize;
8683 pStats.externalCodeSize = 0L;
8684 }
8685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008686 return true;
8687 }
8688
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008690 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07008691 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008692 }
8693
8694 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07008695 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008696 }
8697
8698 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008699 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008700 }
8701
Kenny Root447106f2011-03-23 11:00:15 -07008702 private int getUidTargetSdkVersionLockedLPr(int uid) {
8703 Object obj = mSettings.getUserIdLPr(uid);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008704 if (obj instanceof SharedUserSetting) {
Kenny Root60f7ad82011-03-22 12:49:06 -07008705 final SharedUserSetting sus = (SharedUserSetting) obj;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008706 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
Kenny Root60f7ad82011-03-22 12:49:06 -07008707 final Iterator<PackageSetting> it = sus.packages.iterator();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008708 while (it.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07008709 final PackageSetting ps = it.next();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008710 if (ps.pkg != null) {
8711 int v = ps.pkg.applicationInfo.targetSdkVersion;
8712 if (v < vers) vers = v;
8713 }
8714 }
8715 return vers;
8716 } else if (obj instanceof PackageSetting) {
Kenny Root60f7ad82011-03-22 12:49:06 -07008717 final PackageSetting ps = (PackageSetting) obj;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008718 if (ps.pkg != null) {
8719 return ps.pkg.applicationInfo.targetSdkVersion;
8720 }
8721 }
8722 return Build.VERSION_CODES.CUR_DEVELOPMENT;
8723 }
8724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008725 public void addPreferredActivity(IntentFilter filter, int match,
Amith Yamasania3f133a2012-08-09 17:11:28 -07008726 ComponentName[] set, ComponentName activity, int userId) {
Kenny Root447106f2011-03-23 11:00:15 -07008727 // writer
Amith Yamasania3f133a2012-08-09 17:11:28 -07008728 int callingUid = Binder.getCallingUid();
Amith Yamasanif203aee2012-08-29 18:41:53 -07008729 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008730 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008731 if (mContext.checkCallingOrSelfPermission(
8732 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
8733 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasania3f133a2012-08-09 17:11:28 -07008734 if (getUidTargetSdkVersionLockedLPr(callingUid)
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008735 < Build.VERSION_CODES.FROYO) {
8736 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
Amith Yamasania3f133a2012-08-09 17:11:28 -07008737 + callingUid);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008738 return;
8739 }
8740 mContext.enforceCallingOrSelfPermission(
8741 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
8742 }
Amith Yamasania3f133a2012-08-09 17:11:28 -07008743
8744 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008745 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
Dianne Hackborn63092712012-10-07 14:45:35 -07008746 mSettings.editPreferredActivitiesLPw(userId).addFilter(
8747 new PreferredActivity(filter, match, set, activity));
8748 mSettings.writePackageRestrictionsLPr(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008749 }
8750 }
8751
Satish Sampath8dbe6122009-06-02 23:35:54 +01008752 public void replacePreferredActivity(IntentFilter filter, int match,
8753 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01008754 if (filter.countActions() != 1) {
8755 throw new IllegalArgumentException(
8756 "replacePreferredActivity expects filter to have only 1 action.");
8757 }
8758 if (filter.countCategories() != 1) {
8759 throw new IllegalArgumentException(
8760 "replacePreferredActivity expects filter to have only 1 category.");
8761 }
8762 if (filter.countDataAuthorities() != 0
8763 || filter.countDataPaths() != 0
8764 || filter.countDataSchemes() != 0
8765 || filter.countDataTypes() != 0) {
8766 throw new IllegalArgumentException(
8767 "replacePreferredActivity expects filter to have no data authorities, " +
8768 "paths, schemes or types.");
8769 }
8770 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008771 if (mContext.checkCallingOrSelfPermission(
8772 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
8773 != PackageManager.PERMISSION_GRANTED) {
Kenny Root447106f2011-03-23 11:00:15 -07008774 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008775 < Build.VERSION_CODES.FROYO) {
8776 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
8777 + Binder.getCallingUid());
8778 return;
8779 }
8780 mContext.enforceCallingOrSelfPermission(
8781 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
8782 }
Amith Yamasania3f133a2012-08-09 17:11:28 -07008783
8784 final int callingUserId = UserHandle.getCallingUserId();
Dianne Hackborn04505102012-02-29 12:34:04 -08008785 ArrayList<PreferredActivity> removed = null;
Dianne Hackborn63092712012-10-07 14:45:35 -07008786 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
8787 if (pir != null) {
8788 Iterator<PreferredActivity> it = pir.filterIterator();
8789 String action = filter.getAction(0);
8790 String category = filter.getCategory(0);
8791 while (it.hasNext()) {
8792 PreferredActivity pa = it.next();
8793 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
8794 if (removed == null) {
8795 removed = new ArrayList<PreferredActivity>();
8796 }
8797 removed.add(pa);
8798 Log.i(TAG, "Removing preferred activity " + pa.mPref.mComponent + ":");
8799 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
Dianne Hackborn04505102012-02-29 12:34:04 -08008800 }
Satish Sampath8dbe6122009-06-02 23:35:54 +01008801 }
Dianne Hackborn63092712012-10-07 14:45:35 -07008802 if (removed != null) {
8803 for (int i=0; i<removed.size(); i++) {
8804 PreferredActivity pa = removed.get(i);
8805 pir.removeFilter(pa);
8806 }
Dianne Hackborn04505102012-02-29 12:34:04 -08008807 }
8808 }
Amith Yamasania3f133a2012-08-09 17:11:28 -07008809 addPreferredActivity(filter, match, set, activity, callingUserId);
Satish Sampath8dbe6122009-06-02 23:35:54 +01008810 }
8811 }
8812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008813 public void clearPackagePreferredActivities(String packageName) {
Kenny Root447106f2011-03-23 11:00:15 -07008814 final int uid = Binder.getCallingUid();
8815 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008816 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08008817 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008818 if (pkg == null || pkg.applicationInfo.uid != uid) {
8819 if (mContext.checkCallingOrSelfPermission(
8820 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
8821 != PackageManager.PERMISSION_GRANTED) {
Kenny Root447106f2011-03-23 11:00:15 -07008822 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008823 < Build.VERSION_CODES.FROYO) {
8824 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
8825 + Binder.getCallingUid());
8826 return;
8827 }
8828 mContext.enforceCallingOrSelfPermission(
8829 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
8830 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08008831 }
8832
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08008833 int user = UserHandle.getCallingUserId();
8834 if (clearPackagePreferredActivitiesLPw(packageName, user)) {
8835 mSettings.writePackageRestrictionsLPr(user);
8836 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008837 }
8838 }
8839 }
8840
Amith Yamasania3f133a2012-08-09 17:11:28 -07008841 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
8842 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
Dianne Hackborn04505102012-02-29 12:34:04 -08008843 ArrayList<PreferredActivity> removed = null;
Dianne Hackborn63092712012-10-07 14:45:35 -07008844 boolean changed = false;
8845 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
8846 final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
8847 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
8848 if (userId != UserHandle.USER_ALL && userId != thisUserId) {
Amith Yamasania3f133a2012-08-09 17:11:28 -07008849 continue;
8850 }
Dianne Hackborn63092712012-10-07 14:45:35 -07008851 Iterator<PreferredActivity> it = pir.filterIterator();
8852 while (it.hasNext()) {
8853 PreferredActivity pa = it.next();
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08008854 if (packageName == null ||
8855 pa.mPref.mComponent.getPackageName().equals(packageName)) {
Dianne Hackborn63092712012-10-07 14:45:35 -07008856 if (removed == null) {
8857 removed = new ArrayList<PreferredActivity>();
8858 }
8859 removed.add(pa);
Dianne Hackborn04505102012-02-29 12:34:04 -08008860 }
Dianne Hackborn63092712012-10-07 14:45:35 -07008861 }
8862 if (removed != null) {
8863 for (int j=0; j<removed.size(); j++) {
8864 PreferredActivity pa = removed.get(j);
8865 pir.removeFilter(pa);
8866 }
8867 changed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008868 }
8869 }
Dianne Hackborn63092712012-10-07 14:45:35 -07008870 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008871 }
8872
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08008873 public void resetPreferredActivities(int userId) {
8874 mContext.enforceCallingOrSelfPermission(
8875 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
8876 // writer
8877 synchronized (mPackages) {
8878 int user = UserHandle.getCallingUserId();
8879 clearPackagePreferredActivitiesLPw(null, user);
8880 mSettings.readDefaultPreferredAppsLPw(this, user);
8881 mSettings.writePackageRestrictionsLPr(user);
8882 scheduleWriteSettingsLocked();
8883 }
8884 }
8885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008886 public int getPreferredActivities(List<IntentFilter> outFilters,
8887 List<ComponentName> outActivities, String packageName) {
8888
8889 int num = 0;
Amith Yamasania3f133a2012-08-09 17:11:28 -07008890 final int userId = UserHandle.getCallingUserId();
Kenny Root447106f2011-03-23 11:00:15 -07008891 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008892 synchronized (mPackages) {
Dianne Hackborn63092712012-10-07 14:45:35 -07008893 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
8894 if (pir != null) {
8895 final Iterator<PreferredActivity> it = pir.filterIterator();
8896 while (it.hasNext()) {
8897 final PreferredActivity pa = it.next();
8898 if (packageName == null
8899 || pa.mPref.mComponent.getPackageName().equals(packageName)) {
8900 if (outFilters != null) {
8901 outFilters.add(new IntentFilter(pa));
8902 }
8903 if (outActivities != null) {
8904 outActivities.add(pa.mPref.mComponent);
8905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008906 }
8907 }
8908 }
8909 }
8910
8911 return num;
8912 }
8913
Amith Yamasani483f3b02012-03-13 16:08:00 -07008914 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008915 public void setApplicationEnabledSetting(String appPackageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07008916 int newState, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07008917 if (!sUserManager.exists(userId)) return;
Amith Yamasani483f3b02012-03-13 16:08:00 -07008918 setEnabledSetting(appPackageName, null, newState, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008919 }
8920
Amith Yamasani483f3b02012-03-13 16:08:00 -07008921 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008922 public void setComponentEnabledSetting(ComponentName componentName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07008923 int newState, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07008924 if (!sUserManager.exists(userId)) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008925 setEnabledSetting(componentName.getPackageName(),
Amith Yamasani483f3b02012-03-13 16:08:00 -07008926 componentName.getClassName(), newState, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008927 }
8928
8929 private void setEnabledSetting(
Amith Yamasani483f3b02012-03-13 16:08:00 -07008930 final String packageName, String className, int newState, final int flags, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008931 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
8932 || newState == COMPONENT_ENABLED_STATE_ENABLED
Dianne Hackborn0ac30312011-06-17 14:49:23 -07008933 || newState == COMPONENT_ENABLED_STATE_DISABLED
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08008934 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
8935 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008936 throw new IllegalArgumentException("Invalid new component state: "
8937 + newState);
8938 }
8939 PackageSetting pkgSetting;
8940 final int uid = Binder.getCallingUid();
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08008941 final int permission = mContext.checkCallingOrSelfPermission(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008942 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
Amith Yamasanif203aee2012-08-29 18:41:53 -07008943 enforceCrossUserPermission(uid, userId, false, "set enabled");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008944 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008945 boolean sendNow = false;
8946 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08008947 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008948 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08008949 ArrayList<String> components;
Kenny Root447106f2011-03-23 11:00:15 -07008950
8951 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008952 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008953 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008954 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008955 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008956 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008957 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008958 }
8959 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008960 "Unknown component: " + packageName
8961 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008962 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07008963 // Allow root and verify that userId is not being specified by a different user
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008964 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008965 throw new SecurityException(
8966 "Permission Denial: attempt to change component state from pid="
8967 + Binder.getCallingPid()
Amith Yamasani13593602012-03-22 16:16:17 -07008968 + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008969 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008970 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008971 // We're dealing with an application/package level state change
Amith Yamasani483f3b02012-03-13 16:08:00 -07008972 if (pkgSetting.getEnabled(userId) == newState) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07008973 // Nothing to do
8974 return;
8975 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07008976 pkgSetting.setEnabled(newState, userId);
Amith Yamasani13593602012-03-22 16:16:17 -07008977 // pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008978 } else {
8979 // We're dealing with a component level state change
Dianne Hackborn65696252012-03-05 18:49:21 -08008980 // First, verify that this is a valid class name.
8981 PackageParser.Package pkg = pkgSetting.pkg;
8982 if (pkg == null || !pkg.hasComponentClassName(className)) {
8983 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
8984 throw new IllegalArgumentException("Component class " + className
8985 + " does not exist in " + packageName);
8986 } else {
8987 Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
8988 + className + " does not exist in " + packageName);
8989 }
8990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008991 switch (newState) {
8992 case COMPONENT_ENABLED_STATE_ENABLED:
Amith Yamasani483f3b02012-03-13 16:08:00 -07008993 if (!pkgSetting.enableComponentLPw(className, userId)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07008994 return;
8995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008996 break;
8997 case COMPONENT_ENABLED_STATE_DISABLED:
Amith Yamasani483f3b02012-03-13 16:08:00 -07008998 if (!pkgSetting.disableComponentLPw(className, userId)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07008999 return;
9000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009001 break;
9002 case COMPONENT_ENABLED_STATE_DEFAULT:
Amith Yamasani483f3b02012-03-13 16:08:00 -07009003 if (!pkgSetting.restoreComponentLPw(className, userId)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07009004 return;
9005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009006 break;
9007 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009008 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009009 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009010 }
9011 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07009012 mSettings.writePackageRestrictionsLPr(userId);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07009013 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08009014 components = mPendingBroadcasts.get(packageName);
Kenny Root447106f2011-03-23 11:00:15 -07009015 final boolean newPackage = components == null;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08009016 if (newPackage) {
9017 components = new ArrayList<String>();
9018 }
9019 if (!components.contains(componentName)) {
9020 components.add(componentName);
9021 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009022 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
9023 sendNow = true;
9024 // Purge entry from pending broadcast list if another one exists already
9025 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08009026 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009027 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08009028 if (newPackage) {
9029 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009030 }
9031 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
9032 // Schedule a message
9033 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
9034 }
9035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009036 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009038 long callingId = Binder.clearCallingIdentity();
9039 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009040 if (sendNow) {
9041 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08009042 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009044 } finally {
9045 Binder.restoreCallingIdentity(callingId);
9046 }
9047 }
9048
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009049 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08009050 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
Kenny Root4dfe6ff2011-02-23 17:00:43 -08009051 if (DEBUG_INSTALL)
9052 Log.v(TAG, "Sending package changed: package=" + packageName + " components="
9053 + componentNames);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08009054 Bundle extras = new Bundle(4);
9055 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
9056 String nameList[] = new String[componentNames.size()];
9057 componentNames.toArray(nameList);
9058 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009059 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
9060 extras.putInt(Intent.EXTRA_UID, packageUid);
Amith Yamasani13593602012-03-22 16:16:17 -07009061 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009062 new int[] {UserHandle.getUserId(packageUid)});
Dianne Hackborne7f97212011-02-24 14:40:20 -08009063 }
9064
Amith Yamasani483f3b02012-03-13 16:08:00 -07009065 public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07009066 if (!sUserManager.exists(userId)) return;
Dianne Hackborne7f97212011-02-24 14:40:20 -08009067 final int uid = Binder.getCallingUid();
9068 final int permission = mContext.checkCallingOrSelfPermission(
9069 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
9070 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Amith Yamasanif203aee2012-08-29 18:41:53 -07009071 enforceCrossUserPermission(uid, userId, true, "stop package");
Kenny Root447106f2011-03-23 11:00:15 -07009072 // writer
Dianne Hackborne7f97212011-02-24 14:40:20 -08009073 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07009074 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
Amith Yamasani483f3b02012-03-13 16:08:00 -07009075 uid, userId)) {
9076 scheduleWritePackageRestrictionsLocked(userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08009077 }
9078 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009079 }
9080
Jacek Surazski65e13172009-04-28 15:26:38 +02009081 public String getInstallerPackageName(String packageName) {
Kenny Root447106f2011-03-23 11:00:15 -07009082 // reader
Jacek Surazski65e13172009-04-28 15:26:38 +02009083 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07009084 return mSettings.getInstallerPackageNameLPr(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02009085 }
9086 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009087
Amith Yamasani483f3b02012-03-13 16:08:00 -07009088 @Override
9089 public int getApplicationEnabledSetting(String packageName, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07009090 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
Amith Yamasani483f3b02012-03-13 16:08:00 -07009091 int uid = Binder.getCallingUid();
Amith Yamasanif203aee2012-08-29 18:41:53 -07009092 enforceCrossUserPermission(uid, userId, false, "get enabled");
Kenny Root447106f2011-03-23 11:00:15 -07009093 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009094 synchronized (mPackages) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07009095 return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009096 }
9097 }
9098
Amith Yamasani483f3b02012-03-13 16:08:00 -07009099 @Override
9100 public int getComponentEnabledSetting(ComponentName componentName, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07009101 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
Amith Yamasani483f3b02012-03-13 16:08:00 -07009102 int uid = Binder.getCallingUid();
Amith Yamasanif203aee2012-08-29 18:41:53 -07009103 enforceCrossUserPermission(uid, userId, false, "get component enabled");
Kenny Root447106f2011-03-23 11:00:15 -07009104 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009105 synchronized (mPackages) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07009106 return mSettings.getComponentEnabledSettingLPr(componentName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009107 }
9108 }
9109
9110 public void enterSafeMode() {
Kenny Root461ff1f2011-08-09 09:43:03 -07009111 enforceSystemOrRoot("Only the system can request entering safe mode");
9112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009113 if (!mSystemReady) {
9114 mSafeMode = true;
9115 }
9116 }
9117
9118 public void systemReady() {
9119 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07009120
9121 // Read the compatibilty setting when the system is ready.
Jeff Sharkey6e2bee72012-10-01 13:39:08 -07009122 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07009123 mContext.getContentResolver(),
Jeff Sharkey6e2bee72012-10-01 13:39:08 -07009124 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07009125 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07009126 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07009127 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07009128 }
Dianne Hackborn63092712012-10-07 14:45:35 -07009129
9130 synchronized (mPackages) {
9131 // Verify that all of the preferred activity components actually
9132 // exist. It is possible for applications to be updated and at
9133 // that point remove a previously declared activity component that
9134 // had been set as a preferred activity. We try to clean this up
9135 // the next time we encounter that preferred activity, but it is
9136 // possible for the user flow to never be able to return to that
9137 // situation so here we do a sanity check to make sure we haven't
9138 // left any junk around.
9139 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
9140 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
9141 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
9142 removed.clear();
9143 for (PreferredActivity pa : pir.filterSet()) {
9144 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
9145 removed.add(pa);
9146 }
9147 }
9148 if (removed.size() > 0) {
9149 for (int j=0; j<removed.size(); j++) {
9150 PreferredActivity pa = removed.get(i);
Dianne Hackborn63092712012-10-07 14:45:35 -07009151 Slog.w(TAG, "Removing dangling preferred activity: "
Dianne Hackborn40e9f292012-11-27 19:12:23 -08009152 + pa.mPref.mComponent);
Dianne Hackborn63092712012-10-07 14:45:35 -07009153 pir.removeFilter(pa);
9154 }
9155 mSettings.writePackageRestrictionsLPr(
9156 mSettings.mPreferredActivities.keyAt(i));
9157 }
9158 }
9159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009160 }
9161
9162 public boolean isSafeMode() {
9163 return mSafeMode;
9164 }
9165
9166 public boolean hasSystemUidErrors() {
9167 return mHasSystemUidErrors;
9168 }
9169
9170 static String arrayToString(int[] array) {
9171 StringBuffer buf = new StringBuffer(128);
9172 buf.append('[');
9173 if (array != null) {
9174 for (int i=0; i<array.length; i++) {
9175 if (i > 0) buf.append(", ");
9176 buf.append(array[i]);
9177 }
9178 }
9179 buf.append(']');
9180 return buf.toString();
9181 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009182
Kenny Root447106f2011-03-23 11:00:15 -07009183 static class DumpState {
9184 public static final int DUMP_LIBS = 1 << 0;
9185
9186 public static final int DUMP_FEATURES = 1 << 1;
9187
9188 public static final int DUMP_RESOLVERS = 1 << 2;
9189
9190 public static final int DUMP_PERMISSIONS = 1 << 3;
9191
9192 public static final int DUMP_PACKAGES = 1 << 4;
9193
9194 public static final int DUMP_SHARED_USERS = 1 << 5;
9195
9196 public static final int DUMP_MESSAGES = 1 << 6;
9197
9198 public static final int DUMP_PROVIDERS = 1 << 7;
9199
Kenny Root05ca4c92011-09-15 10:36:25 -07009200 public static final int DUMP_VERIFIERS = 1 << 8;
9201
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07009202 public static final int DUMP_PREFERRED = 1 << 9;
9203
9204 public static final int DUMP_PREFERRED_XML = 1 << 10;
9205
Kenny Root447106f2011-03-23 11:00:15 -07009206 public static final int OPTION_SHOW_FILTERS = 1 << 0;
9207
9208 private int mTypes;
9209
9210 private int mOptions;
9211
9212 private boolean mTitlePrinted;
9213
9214 private SharedUserSetting mSharedUser;
9215
9216 public boolean isDumping(int type) {
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07009217 if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
Kenny Root447106f2011-03-23 11:00:15 -07009218 return true;
9219 }
9220
9221 return (mTypes & type) != 0;
9222 }
9223
9224 public void setDump(int type) {
9225 mTypes |= type;
9226 }
9227
9228 public boolean isOptionEnabled(int option) {
9229 return (mOptions & option) != 0;
9230 }
9231
9232 public void setOptionEnabled(int option) {
9233 mOptions |= option;
9234 }
9235
9236 public boolean onTitlePrinted() {
9237 final boolean printed = mTitlePrinted;
9238 mTitlePrinted = true;
9239 return printed;
9240 }
9241
9242 public boolean getTitlePrinted() {
9243 return mTitlePrinted;
9244 }
9245
9246 public void setTitlePrinted(boolean enabled) {
9247 mTitlePrinted = enabled;
9248 }
9249
9250 public SharedUserSetting getSharedUser() {
9251 return mSharedUser;
9252 }
9253
9254 public void setSharedUser(SharedUserSetting user) {
9255 mSharedUser = user;
9256 }
9257 }
9258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009259 @Override
9260 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
9261 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
9262 != PackageManager.PERMISSION_GRANTED) {
9263 pw.println("Permission Denial: can't dump ActivityManager from from pid="
9264 + Binder.getCallingPid()
9265 + ", uid=" + Binder.getCallingUid()
9266 + " without permission "
9267 + android.Manifest.permission.DUMP);
9268 return;
9269 }
9270
Kenny Root447106f2011-03-23 11:00:15 -07009271 DumpState dumpState = new DumpState();
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08009272 boolean fullPreferred = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009273
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009274 String packageName = null;
9275
9276 int opti = 0;
9277 while (opti < args.length) {
9278 String opt = args[opti];
9279 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9280 break;
9281 }
9282 opti++;
9283 if ("-a".equals(opt)) {
9284 // Right now we only know how to print all.
9285 } else if ("-h".equals(opt)) {
9286 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009287 pw.println(" [-h] [-f] [cmd] ...");
9288 pw.println(" -f: print details of intent filters");
9289 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009290 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009291 pw.println(" l[ibraries]: list known shared libraries");
9292 pw.println(" f[ibraries]: list device features");
9293 pw.println(" r[esolvers]: dump intent resolvers");
9294 pw.println(" perm[issions]: dump permissions");
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07009295 pw.println(" pref[erred]: print preferred package settings");
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08009296 pw.println(" preferred-xml [--full]: print preferred package settings as xml");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009297 pw.println(" prov[iders]: dump content providers");
9298 pw.println(" p[ackages]: dump installed packages");
9299 pw.println(" s[hared-users]: dump shared user IDs");
9300 pw.println(" m[essages]: print collected runtime messages");
Kenny Root05ca4c92011-09-15 10:36:25 -07009301 pw.println(" v[erifiers]: print package verifier info");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009302 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009303 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009304 } else if ("-f".equals(opt)) {
Kenny Root447106f2011-03-23 11:00:15 -07009305 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009306 } else {
9307 pw.println("Unknown argument: " + opt + "; use -h for help");
9308 }
9309 }
9310
9311 // Is the caller requesting to dump a particular piece of data?
9312 if (opti < args.length) {
9313 String cmd = args[opti];
9314 opti++;
9315 // Is this a package name?
9316 if ("android".equals(cmd) || cmd.contains(".")) {
9317 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009318 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07009319 dumpState.setDump(DumpState.DUMP_LIBS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009320 } else if ("f".equals(cmd) || "features".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07009321 dumpState.setDump(DumpState.DUMP_FEATURES);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009322 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07009323 dumpState.setDump(DumpState.DUMP_RESOLVERS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009324 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07009325 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07009326 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
9327 dumpState.setDump(DumpState.DUMP_PREFERRED);
9328 } else if ("preferred-xml".equals(cmd)) {
9329 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08009330 opti++;
9331 if (opti < args.length && "--full".equals(args[opti])) {
9332 fullPreferred = true;
9333 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009334 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07009335 dumpState.setDump(DumpState.DUMP_PACKAGES);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009336 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07009337 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009338 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07009339 dumpState.setDump(DumpState.DUMP_PROVIDERS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009340 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07009341 dumpState.setDump(DumpState.DUMP_MESSAGES);
Kenny Root05ca4c92011-09-15 10:36:25 -07009342 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
9343 dumpState.setDump(DumpState.DUMP_VERIFIERS);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009344 }
9345 }
Kenny Root447106f2011-03-23 11:00:15 -07009346
9347 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009348 synchronized (mPackages) {
Kenny Root05ca4c92011-09-15 10:36:25 -07009349 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
9350 if (dumpState.onTitlePrinted())
9351 pw.println(" ");
9352 pw.println("Verifiers:");
9353 pw.print(" Required: ");
9354 pw.print(mRequiredVerifierPackage);
9355 pw.print(" (uid=");
Amith Yamasani483f3b02012-03-13 16:08:00 -07009356 pw.print(getPackageUid(mRequiredVerifierPackage, 0));
Kenny Root05ca4c92011-09-15 10:36:25 -07009357 pw.println(")");
9358 }
9359
Kenny Root447106f2011-03-23 11:00:15 -07009360 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
9361 if (dumpState.onTitlePrinted())
9362 pw.println(" ");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009363 pw.println("Libraries:");
Kenny Root447106f2011-03-23 11:00:15 -07009364 final Iterator<String> it = mSharedLibraries.keySet().iterator();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009365 while (it.hasNext()) {
9366 String name = it.next();
9367 pw.print(" ");
9368 pw.print(name);
9369 pw.print(" -> ");
9370 pw.println(mSharedLibraries.get(name));
9371 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009372 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009373
Kenny Root447106f2011-03-23 11:00:15 -07009374 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
9375 if (dumpState.onTitlePrinted())
9376 pw.println(" ");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009377 pw.println("Features:");
9378 Iterator<String> it = mAvailableFeatures.keySet().iterator();
9379 while (it.hasNext()) {
9380 String name = it.next();
9381 pw.print(" ");
9382 pw.println(name);
9383 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009384 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009385
Kenny Root447106f2011-03-23 11:00:15 -07009386 if (dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
9387 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
9388 : "Activity Resolver Table:", " ", packageName,
9389 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
9390 dumpState.setTitlePrinted(true);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009391 }
Kenny Root447106f2011-03-23 11:00:15 -07009392 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
9393 : "Receiver Resolver Table:", " ", packageName,
9394 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
9395 dumpState.setTitlePrinted(true);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009396 }
Kenny Root447106f2011-03-23 11:00:15 -07009397 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
9398 : "Service Resolver Table:", " ", packageName,
9399 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
9400 dumpState.setTitlePrinted(true);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009401 }
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07009402 }
9403
9404 if (dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
Dianne Hackborn63092712012-10-07 14:45:35 -07009405 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
9406 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
9407 int user = mSettings.mPreferredActivities.keyAt(i);
9408 if (pir.dump(pw,
9409 dumpState.getTitlePrinted()
9410 ? "\nPreferred Activities User " + user + ":"
9411 : "Preferred Activities User " + user + ":", " ",
9412 packageName, dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
9413 dumpState.setTitlePrinted(true);
9414 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009415 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009416 }
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07009417
9418 if (dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
9419 pw.flush();
9420 FileOutputStream fout = new FileOutputStream(fd);
9421 BufferedOutputStream str = new BufferedOutputStream(fout);
9422 XmlSerializer serializer = new FastXmlSerializer();
9423 try {
9424 serializer.setOutput(str, "utf-8");
9425 serializer.startDocument(null, true);
9426 serializer.setFeature(
9427 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08009428 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07009429 serializer.endDocument();
9430 serializer.flush();
9431 } catch (IllegalArgumentException e) {
9432 pw.println("Failed writing: " + e);
9433 } catch (IllegalStateException e) {
9434 pw.println("Failed writing: " + e);
9435 } catch (IOException e) {
9436 pw.println("Failed writing: " + e);
9437 }
9438 }
9439
Kenny Root447106f2011-03-23 11:00:15 -07009440 if (dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
9441 mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009442 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009443
Kenny Root447106f2011-03-23 11:00:15 -07009444 if (dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
9445 boolean printedSomething = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009446 for (PackageParser.Provider p : mProvidersByComponent.values()) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009447 if (packageName != null && !packageName.equals(p.info.packageName)) {
9448 continue;
9449 }
9450 if (!printedSomething) {
Kenny Root447106f2011-03-23 11:00:15 -07009451 if (dumpState.onTitlePrinted())
9452 pw.println(" ");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009453 pw.println("Registered ContentProviders:");
9454 printedSomething = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009455 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009456 pw.print(" "); pw.print(p.getComponentShortName()); pw.println(":");
9457 pw.print(" "); pw.println(p.toString());
9458 }
9459 printedSomething = false;
9460 for (Map.Entry<String, PackageParser.Provider> entry : mProviders.entrySet()) {
9461 PackageParser.Provider p = entry.getValue();
9462 if (packageName != null && !packageName.equals(p.info.packageName)) {
9463 continue;
9464 }
9465 if (!printedSomething) {
9466 if (dumpState.onTitlePrinted())
9467 pw.println(" ");
9468 pw.println("ContentProvider Authorities:");
9469 printedSomething = true;
9470 }
9471 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:");
9472 pw.print(" "); pw.println(p.toString());
Kenny Rooteca64b32012-06-25 16:37:32 -07009473 if (p.info != null && p.info.applicationInfo != null) {
9474 final String appInfo = p.info.applicationInfo.toString();
9475 pw.print(" applicationInfo="); pw.println(appInfo);
9476 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009477 }
9478 }
9479
Kenny Root447106f2011-03-23 11:00:15 -07009480 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
9481 mSettings.dumpPackagesLPr(pw, packageName, dumpState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009482 }
Kenny Root447106f2011-03-23 11:00:15 -07009483
9484 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
9485 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009486 }
Kenny Root447106f2011-03-23 11:00:15 -07009487
9488 if (dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
9489 if (dumpState.onTitlePrinted())
9490 pw.println(" ");
9491 mSettings.dumpReadMessagesLPr(pw, dumpState);
9492
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009493 pw.println(" ");
9494 pw.println("Package warning messages:");
Kenny Root447106f2011-03-23 11:00:15 -07009495 final File fname = getSettingsProblemFile();
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -08009496 FileInputStream in = null;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009497 try {
9498 in = new FileInputStream(fname);
Kenny Root447106f2011-03-23 11:00:15 -07009499 final int avail = in.available();
9500 final byte[] data = new byte[avail];
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009501 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009502 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009503 } catch (FileNotFoundException e) {
9504 } catch (IOException e) {
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -08009505 } finally {
9506 if (in != null) {
9507 try {
9508 in.close();
Kenny Root447106f2011-03-23 11:00:15 -07009509 } catch (IOException e) {
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -08009510 }
9511 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009512 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009514 }
9515 }
9516
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009517 // ------- apps on sdcard specific code -------
9518 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root447106f2011-03-23 11:00:15 -07009519
Kenny Root305bcbf2010-09-03 07:56:38 -07009520 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
Kenny Root447106f2011-03-23 11:00:15 -07009521
Kenny Root305bcbf2010-09-03 07:56:38 -07009522 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
Kenny Root447106f2011-03-23 11:00:15 -07009523
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009524 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009525
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009526 private String getEncryptKey() {
9527 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009528 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9529 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009530 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009531 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9532 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009533 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009534 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009535 return null;
9536 }
9537 }
9538 return sdEncKey;
9539 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009540 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009541 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009542 } catch (IOException ioe) {
Kenny Root447106f2011-03-23 11:00:15 -07009543 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
Rich Cannings8d578832010-09-09 15:12:40 -07009544 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009545 }
Rich Cannings8d578832010-09-09 15:12:40 -07009546
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009547 }
9548
Kenny Root447106f2011-03-23 11:00:15 -07009549 /* package */static String getTempContainerId() {
Kenny Rootc78a8072010-07-27 15:18:38 -07009550 int tmpIdx = 1;
9551 String list[] = PackageHelper.getSecureContainerList();
9552 if (list != null) {
9553 for (final String name : list) {
9554 // Ignore null and non-temporary container entries
9555 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9556 continue;
9557 }
9558
9559 String subStr = name.substring(mTempContainerPrefix.length());
9560 try {
9561 int cid = Integer.parseInt(subStr);
9562 if (cid >= tmpIdx) {
9563 tmpIdx = cid + 1;
9564 }
9565 } catch (NumberFormatException e) {
9566 }
9567 }
9568 }
9569 return mTempContainerPrefix + tmpIdx;
9570 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009571
Kenny Root447106f2011-03-23 11:00:15 -07009572 /*
9573 * Update media status on PackageManager.
9574 */
9575 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9576 int callingUid = Binder.getCallingUid();
9577 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
9578 throw new SecurityException("Media status can only be updated by the system");
9579 }
9580 // reader; this apparently protects mMediaMounted, but should probably
9581 // be a different lock in that case.
9582 synchronized (mPackages) {
9583 Log.i(TAG, "Updating external media status from "
9584 + (mMediaMounted ? "mounted" : "unmounted") + " to "
9585 + (mediaStatus ? "mounted" : "unmounted"));
9586 if (DEBUG_SD_INSTALL)
9587 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
9588 + ", mMediaMounted=" + mMediaMounted);
9589 if (mediaStatus == mMediaMounted) {
9590 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
9591 : 0, -1);
9592 mHandler.sendMessage(msg);
9593 return;
9594 }
9595 mMediaMounted = mediaStatus;
9596 }
9597 // Queue up an async operation since the package installation may take a
9598 // little while.
9599 mHandler.post(new Runnable() {
9600 public void run() {
Kenny Root438a0ef2012-08-09 13:36:16 -07009601 updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
Kenny Root447106f2011-03-23 11:00:15 -07009602 }
9603 });
9604 }
9605
Kenny Root51a573c2012-05-17 13:30:28 -07009606 /**
9607 * Called by MountService when the initial ASECs to scan are available.
9608 * Should block until all the ASEC containers are finished being scanned.
9609 */
9610 public void scanAvailableAsecs() {
Kenny Root438a0ef2012-08-09 13:36:16 -07009611 updateExternalMediaStatusInner(true, false, false);
Kenny Root51a573c2012-05-17 13:30:28 -07009612 }
9613
Kenny Root447106f2011-03-23 11:00:15 -07009614 /*
9615 * Collect information of applications on external media, map them against
9616 * existing containers and update information based on current mount status.
9617 * Please note that we always have to report status if reportStatus has been
9618 * set to true especially when unloading packages.
9619 */
Kenny Root438a0ef2012-08-09 13:36:16 -07009620 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
9621 boolean externalStorage) {
Kenny Root447106f2011-03-23 11:00:15 -07009622 // Collection of uids
9623 int uidArr[] = null;
9624 // Collection of stale containers
9625 HashSet<String> removeCids = new HashSet<String>();
9626 // Collection of packages on external media with valid containers.
Kenny Root6dceb882012-04-12 14:23:49 -07009627 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
Kenny Root447106f2011-03-23 11:00:15 -07009628 // Get list of secure containers.
9629 final String list[] = PackageHelper.getSecureContainerList();
9630 if (list == null || list.length == 0) {
9631 Log.i(TAG, "No secure containers on sdcard");
9632 } else {
9633 // Process list of secure containers and categorize them
9634 // as active or stale based on their package internal state.
9635 int uidList[] = new int[list.length];
9636 int num = 0;
9637 // reader
9638 synchronized (mPackages) {
9639 for (String cid : list) {
Kenny Root447106f2011-03-23 11:00:15 -07009640 if (DEBUG_SD_INSTALL)
9641 Log.i(TAG, "Processing container " + cid);
Kenny Rootc7a89992012-06-05 15:13:17 -07009642 String pkgName = getAsecPackageName(cid);
Kenny Root447106f2011-03-23 11:00:15 -07009643 if (pkgName == null) {
9644 if (DEBUG_SD_INSTALL)
9645 Log.i(TAG, "Container : " + cid + " stale");
9646 removeCids.add(cid);
9647 continue;
9648 }
9649 if (DEBUG_SD_INSTALL)
9650 Log.i(TAG, "Looking for pkg : " + pkgName);
Kenny Rootc7a89992012-06-05 15:13:17 -07009651
9652 final PackageSetting ps = mSettings.mPackages.get(pkgName);
9653 if (ps == null) {
9654 Log.i(TAG, "Deleting container with no matching settings " + cid);
9655 removeCids.add(cid);
9656 continue;
9657 }
9658
Kenny Root438a0ef2012-08-09 13:36:16 -07009659 /*
9660 * Skip packages that are not external if we're unmounting
9661 * external storage.
9662 */
9663 if (externalStorage && !isMounted && !isExternal(ps)) {
9664 continue;
9665 }
9666
Kenny Rootc7a89992012-06-05 15:13:17 -07009667 final AsecInstallArgs args = new AsecInstallArgs(cid, isForwardLocked(ps));
Kenny Root447106f2011-03-23 11:00:15 -07009668 // The package status is changed only if the code path
9669 // matches between settings and the container id.
Kenny Rootc7a89992012-06-05 15:13:17 -07009670 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
9671 if (DEBUG_SD_INSTALL) {
Kenny Root447106f2011-03-23 11:00:15 -07009672 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
9673 + " at code path: " + ps.codePathString);
Kenny Rootc7a89992012-06-05 15:13:17 -07009674 }
9675
Kenny Root447106f2011-03-23 11:00:15 -07009676 // We do have a valid package installed on sdcard
9677 processCids.put(args, ps.codePathString);
Kenny Rootc7a89992012-06-05 15:13:17 -07009678 final int uid = ps.appId;
Kenny Root447106f2011-03-23 11:00:15 -07009679 if (uid != -1) {
9680 uidList[num++] = uid;
9681 }
9682 } else {
Kenny Rootc7a89992012-06-05 15:13:17 -07009683 Log.i(TAG, "Deleting stale container for " + cid);
Kenny Root447106f2011-03-23 11:00:15 -07009684 removeCids.add(cid);
9685 }
9686 }
9687 }
9688
9689 if (num > 0) {
9690 // Sort uid list
9691 Arrays.sort(uidList, 0, num);
9692 // Throw away duplicates
9693 uidArr = new int[num];
9694 uidArr[0] = uidList[0];
9695 int di = 0;
9696 for (int i = 1; i < num; i++) {
9697 if (uidList[i - 1] != uidList[i]) {
9698 uidArr[di++] = uidList[i];
9699 }
9700 }
9701 }
9702 }
9703 // Process packages with valid entries.
Kenny Root6dceb882012-04-12 14:23:49 -07009704 if (isMounted) {
Kenny Root447106f2011-03-23 11:00:15 -07009705 if (DEBUG_SD_INSTALL)
9706 Log.i(TAG, "Loading packages");
9707 loadMediaPackages(processCids, uidArr, removeCids);
Jeff Sharkey752cd922012-09-23 16:25:12 -07009708 startCleaningPackages();
Kenny Root447106f2011-03-23 11:00:15 -07009709 } else {
9710 if (DEBUG_SD_INSTALL)
9711 Log.i(TAG, "Unloading packages");
9712 unloadMediaPackages(processCids, uidArr, reportStatus);
9713 }
9714 }
9715
9716 private void sendResourcesChangedBroadcast(boolean mediaStatus, ArrayList<String> pkgList,
9717 int uidArr[], IIntentReceiver finishedReceiver) {
9718 int size = pkgList.size();
9719 if (size > 0) {
9720 // Send broadcasts here
9721 Bundle extras = new Bundle();
9722 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
9723 .toArray(new String[size]));
9724 if (uidArr != null) {
9725 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9726 }
9727 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9728 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009729 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
Kenny Root447106f2011-03-23 11:00:15 -07009730 }
9731 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009732
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009733 /*
Kenny Root447106f2011-03-23 11:00:15 -07009734 * Look at potentially valid container ids from processCids If package
9735 * information doesn't match the one on record or package scanning fails,
9736 * the cid is added to list of removeCids. We currently don't delete stale
9737 * containers.
9738 */
Kenny Root6dceb882012-04-12 14:23:49 -07009739 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
Kenny Root447106f2011-03-23 11:00:15 -07009740 HashSet<String> removeCids) {
9741 ArrayList<String> pkgList = new ArrayList<String>();
Kenny Root6dceb882012-04-12 14:23:49 -07009742 Set<AsecInstallArgs> keys = processCids.keySet();
Kenny Root447106f2011-03-23 11:00:15 -07009743 boolean doGc = false;
Kenny Root6dceb882012-04-12 14:23:49 -07009744 for (AsecInstallArgs args : keys) {
Kenny Root447106f2011-03-23 11:00:15 -07009745 String codePath = processCids.get(args);
9746 if (DEBUG_SD_INSTALL)
9747 Log.i(TAG, "Loading container : " + args.cid);
9748 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9749 try {
9750 // Make sure there are no container errors first.
9751 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
9752 Slog.e(TAG, "Failed to mount cid : " + args.cid
9753 + " when installing from sdcard");
9754 continue;
9755 }
9756 // Check code path here.
9757 if (codePath == null || !codePath.equals(args.getCodePath())) {
9758 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
9759 + " does not match one in settings " + codePath);
9760 continue;
9761 }
9762 // Parse package
Kenny Root51a573c2012-05-17 13:30:28 -07009763 int parseFlags = mDefParseFlags;
9764 if (args.isExternal()) {
9765 parseFlags |= PackageParser.PARSE_ON_SDCARD;
9766 }
Kenny Rootc7a89992012-06-05 15:13:17 -07009767 if (args.isFwdLocked()) {
9768 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
9769 }
Kenny Root51a573c2012-05-17 13:30:28 -07009770
Kenny Root447106f2011-03-23 11:00:15 -07009771 doGc = true;
9772 synchronized (mInstallLock) {
9773 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009774 0, 0, null);
Kenny Root447106f2011-03-23 11:00:15 -07009775 // Scan the package
9776 if (pkg != null) {
9777 /*
9778 * TODO why is the lock being held? doPostInstall is
9779 * called in other places without the lock. This needs
9780 * to be straightened out.
9781 */
9782 // writer
9783 synchronized (mPackages) {
9784 retCode = PackageManager.INSTALL_SUCCEEDED;
9785 pkgList.add(pkg.packageName);
9786 // Post process args
Kenny Root6dceb882012-04-12 14:23:49 -07009787 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
9788 pkg.applicationInfo.uid);
Kenny Root447106f2011-03-23 11:00:15 -07009789 }
9790 } else {
9791 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard");
9792 }
9793 }
9794
9795 } finally {
9796 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9797 // Don't destroy container here. Wait till gc clears things
9798 // up.
9799 removeCids.add(args.cid);
9800 }
9801 }
9802 }
9803 // writer
9804 synchronized (mPackages) {
9805 // If the platform SDK has changed since the last time we booted,
9806 // we need to re-grant app permission to catch any new ones that
9807 // appear. This is really a hack, and means that apps can in some
9808 // cases get permissions that the user didn't initially explicitly
9809 // allow... it would be nice to have some better way to handle
9810 // this situation.
9811 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
9812 if (regrantPermissions)
9813 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
9814 + mSdkVersion + "; regranting permissions for external storage");
9815 mSettings.mExternalSdkPlatform = mSdkVersion;
9816
9817 // Make sure group IDs have been assigned, and any permission
9818 // changes in other apps are accounted for
Dianne Hackborne639da72012-02-21 15:11:13 -08009819 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
9820 | (regrantPermissions
9821 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
9822 : 0));
Kenny Root447106f2011-03-23 11:00:15 -07009823 // can downgrade to reader
9824 // Persist settings
9825 mSettings.writeLPr();
9826 }
9827 // Send a broadcast to let everyone know we are done processing
9828 if (pkgList.size() > 0) {
9829 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
9830 }
9831 // Force gc to avoid any stale parser references that we might have.
9832 if (doGc) {
9833 Runtime.getRuntime().gc();
9834 }
9835 // List stale containers and destroy stale temporary containers.
9836 if (removeCids != null) {
9837 for (String cid : removeCids) {
9838 if (cid.startsWith(mTempContainerPrefix)) {
9839 Log.i(TAG, "Destroying stale temporary container " + cid);
9840 PackageHelper.destroySdDir(cid);
9841 } else {
9842 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009843 }
9844 }
Kenny Root447106f2011-03-23 11:00:15 -07009845 }
9846 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009847
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009848 /*
Kenny Root447106f2011-03-23 11:00:15 -07009849 * Utility method to unload a list of specified containers
9850 */
Kenny Root6dceb882012-04-12 14:23:49 -07009851 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
Kenny Root447106f2011-03-23 11:00:15 -07009852 // Just unmount all valid containers.
Kenny Root6dceb882012-04-12 14:23:49 -07009853 for (AsecInstallArgs arg : cidArgs) {
Kenny Root447106f2011-03-23 11:00:15 -07009854 synchronized (mInstallLock) {
9855 arg.doPostDeleteLI(false);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009856 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009857 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009858 }
9859
Kenny Root447106f2011-03-23 11:00:15 -07009860 /*
9861 * Unload packages mounted on external media. This involves deleting package
9862 * data from internal structures, sending broadcasts about diabled packages,
9863 * gc'ing to free up references, unmounting all secure containers
9864 * corresponding to packages on external media, and posting a
9865 * UPDATED_MEDIA_STATUS message if status has been requested. Please note
9866 * that we always have to post this message if status has been requested no
9867 * matter what.
9868 */
Kenny Root6dceb882012-04-12 14:23:49 -07009869 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
Kenny Root447106f2011-03-23 11:00:15 -07009870 final boolean reportStatus) {
9871 if (DEBUG_SD_INSTALL)
9872 Log.i(TAG, "unloading media packages");
9873 ArrayList<String> pkgList = new ArrayList<String>();
Kenny Root6dceb882012-04-12 14:23:49 -07009874 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
9875 final Set<AsecInstallArgs> keys = processCids.keySet();
9876 for (AsecInstallArgs args : keys) {
Kenny Root447106f2011-03-23 11:00:15 -07009877 String pkgName = args.getPackageName();
9878 if (DEBUG_SD_INSTALL)
9879 Log.i(TAG, "Trying to unload pkg : " + pkgName);
9880 // Delete package internally
9881 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9882 synchronized (mInstallLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009883 boolean res = deletePackageLI(pkgName, null, false,
9884 PackageManager.DELETE_KEEP_DATA, outInfo, false);
Kenny Root447106f2011-03-23 11:00:15 -07009885 if (res) {
9886 pkgList.add(pkgName);
9887 } else {
9888 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
9889 failedList.add(args);
9890 }
9891 }
9892 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009893
Kenny Root447106f2011-03-23 11:00:15 -07009894 // reader
9895 synchronized (mPackages) {
9896 // We didn't update the settings after removing each package;
9897 // write them now for all packages.
9898 mSettings.writeLPr();
9899 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009900
Kenny Root447106f2011-03-23 11:00:15 -07009901 // We have to absolutely send UPDATED_MEDIA_STATUS only
9902 // after confirming that all the receivers processed the ordered
9903 // broadcast when packages get disabled, force a gc to clean things up.
9904 // and unload all the containers.
9905 if (pkgList.size() > 0) {
9906 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9907 public void performReceive(Intent intent, int resultCode, String data,
Dianne Hackborn20e80982012-08-31 19:00:44 -07009908 Bundle extras, boolean ordered, boolean sticky,
9909 int sendingUser) throws RemoteException {
Kenny Root447106f2011-03-23 11:00:15 -07009910 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9911 reportStatus ? 1 : 0, 1, keys);
9912 mHandler.sendMessage(msg);
9913 }
9914 });
9915 } else {
9916 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
9917 keys);
9918 mHandler.sendMessage(msg);
9919 }
9920 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009921
Amith Yamasani6ec10122012-08-23 13:49:25 -07009922 /** Binder call */
9923 @Override
Kenny Root447106f2011-03-23 11:00:15 -07009924 public void movePackage(final String packageName, final IPackageMoveObserver observer,
9925 final int flags) {
9926 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
Amith Yamasani6ec10122012-08-23 13:49:25 -07009927 UserHandle user = new UserHandle(UserHandle.getCallingUserId());
Kenny Root447106f2011-03-23 11:00:15 -07009928 int returnCode = PackageManager.MOVE_SUCCEEDED;
9929 int currFlags = 0;
9930 int newFlags = 0;
9931 // reader
9932 synchronized (mPackages) {
9933 PackageParser.Package pkg = mPackages.get(packageName);
9934 if (pkg == null) {
9935 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9936 } else {
9937 // Disable moving fwd locked apps and system packages
9938 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
9939 Slog.w(TAG, "Cannot move system application");
9940 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root447106f2011-03-23 11:00:15 -07009941 } else if (pkg.mOperationPending) {
9942 Slog.w(TAG, "Attempt to move package which has pending operations");
9943 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
9944 } else {
9945 // Find install location first
9946 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
9947 && (flags & PackageManager.MOVE_INTERNAL) != 0) {
9948 Slog.w(TAG, "Ambigous flags specified for move location.");
9949 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9950 } else {
9951 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
9952 : PackageManager.INSTALL_INTERNAL;
9953 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9954 : PackageManager.INSTALL_INTERNAL;
Kenny Rootbf023582012-05-02 16:56:15 -07009955
Kenny Root447106f2011-03-23 11:00:15 -07009956 if (newFlags == currFlags) {
9957 Slog.w(TAG, "No move required. Trying to move to same location");
9958 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Kenny Rootbf023582012-05-02 16:56:15 -07009959 } else {
9960 if (isForwardLocked(pkg)) {
9961 currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9962 newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9963 }
Kenny Root447106f2011-03-23 11:00:15 -07009964 }
9965 }
9966 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9967 pkg.mOperationPending = true;
9968 }
9969 }
9970 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009971
Kenny Root447106f2011-03-23 11:00:15 -07009972 /*
9973 * TODO this next block probably shouldn't be inside the lock. We
9974 * can't guarantee these won't change after this is fired off
9975 * anyway.
9976 */
9977 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Amith Yamasani6ec10122012-08-23 13:49:25 -07009978 processPendingMove(new MoveParams(null, observer, 0, packageName,
9979 null, -1, user),
Kenny Root6dceb882012-04-12 14:23:49 -07009980 returnCode);
Kenny Root447106f2011-03-23 11:00:15 -07009981 } else {
9982 Message msg = mHandler.obtainMessage(INIT_COPY);
9983 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -07009984 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
Kenny Root447106f2011-03-23 11:00:15 -07009985 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
Amith Yamasani6ec10122012-08-23 13:49:25 -07009986 pkg.applicationInfo.dataDir, pkg.applicationInfo.uid, user);
Kenny Root447106f2011-03-23 11:00:15 -07009987 msg.obj = mp;
9988 mHandler.sendMessage(msg);
9989 }
9990 }
9991 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009992
Kenny Root447106f2011-03-23 11:00:15 -07009993 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9994 // Queue up an async operation since the package deletion may take a
9995 // little while.
9996 mHandler.post(new Runnable() {
9997 public void run() {
9998 // TODO fix this; this does nothing.
9999 mHandler.removeCallbacks(this);
10000 int returnCode = currentStatus;
10001 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
10002 int uidArr[] = null;
10003 ArrayList<String> pkgList = null;
10004 synchronized (mPackages) {
10005 PackageParser.Package pkg = mPackages.get(mp.packageName);
10006 if (pkg == null) {
10007 Slog.w(TAG, " Package " + mp.packageName
10008 + " doesn't exist. Aborting move");
10009 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
10010 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10011 Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
10012 + mp.srcArgs.getCodePath() + " to "
10013 + pkg.applicationInfo.sourceDir
10014 + " Aborting move and returning error");
10015 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10016 } else {
10017 uidArr = new int[] {
10018 pkg.applicationInfo.uid
10019 };
10020 pkgList = new ArrayList<String>();
10021 pkgList.add(mp.packageName);
10022 }
10023 }
10024 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10025 // Send resources unavailable broadcast
10026 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
10027 // Update package code and resource paths
10028 synchronized (mInstallLock) {
10029 synchronized (mPackages) {
10030 PackageParser.Package pkg = mPackages.get(mp.packageName);
10031 // Recheck for package again.
Kenny Root6a6b0072010-10-07 16:46:10 -070010032 if (pkg == null) {
10033 Slog.w(TAG, " Package " + mp.packageName
10034 + " doesn't exist. Aborting move");
10035 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Kenny Root447106f2011-03-23 11:00:15 -070010036 } else if (!mp.srcArgs.getCodePath().equals(
10037 pkg.applicationInfo.sourceDir)) {
10038 Slog.w(TAG, "Package " + mp.packageName
10039 + " code path changed from " + mp.srcArgs.getCodePath()
10040 + " to " + pkg.applicationInfo.sourceDir
10041 + " Aborting move and returning error");
10042 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10043 } else {
10044 final String oldCodePath = pkg.mPath;
10045 final String newCodePath = mp.targetArgs.getCodePath();
10046 final String newResPath = mp.targetArgs.getResourcePath();
10047 final String newNativePath = mp.targetArgs
10048 .getNativeLibraryPath();
Kenny Root6a6b0072010-10-07 16:46:10 -070010049
Kenny Rootddbe50d2012-09-06 13:18:37 -070010050 final File newNativeDir = new File(newNativePath);
Kenny Rootbf023582012-05-02 16:56:15 -070010051
Kenny Rootddbe50d2012-09-06 13:18:37 -070010052 if (!isForwardLocked(pkg) && !isExternal(pkg)) {
Kenny Roota3e90792012-10-18 10:58:36 -070010053 NativeLibraryHelper.copyNativeBinariesIfNeededLI(
10054 new File(newCodePath), newNativeDir);
10055 }
10056 final int[] users = sUserManager.getUserIds();
10057 for (int user : users) {
10058 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
10059 newNativePath, user) < 0) {
10060 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
Kenny Rootddbe50d2012-09-06 13:18:37 -070010061 }
Kenny Root6a6b0072010-10-07 16:46:10 -070010062 }
10063
10064 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10065 pkg.mPath = newCodePath;
10066 // Move dex files around
10067 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
10068 // Moving of dex files failed. Set
10069 // error code and abort move.
10070 pkg.mPath = pkg.mScanPath;
10071 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10072 }
10073 }
10074
10075 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
Kenny Root447106f2011-03-23 11:00:15 -070010076 pkg.mScanPath = newCodePath;
10077 pkg.applicationInfo.sourceDir = newCodePath;
10078 pkg.applicationInfo.publicSourceDir = newResPath;
10079 pkg.applicationInfo.nativeLibraryDir = newNativePath;
10080 PackageSetting ps = (PackageSetting) pkg.mExtras;
10081 ps.codePath = new File(pkg.applicationInfo.sourceDir);
10082 ps.codePathString = ps.codePath.getPath();
10083 ps.resourcePath = new File(
10084 pkg.applicationInfo.publicSourceDir);
10085 ps.resourcePathString = ps.resourcePath.getPath();
10086 ps.nativeLibraryPathString = newNativePath;
10087 // Set the application info flag
10088 // correctly.
10089 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
10090 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10091 } else {
10092 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10093 }
10094 ps.setFlags(pkg.applicationInfo.flags);
10095 mAppDirs.remove(oldCodePath);
10096 mAppDirs.put(newCodePath, pkg);
10097 // Persist settings
10098 mSettings.writeLPr();
10099 }
10100 }
10101 }
10102 }
10103 // Send resources available broadcast
10104 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
10105 }
10106 }
10107 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
10108 // Clean up failed installation
10109 if (mp.targetArgs != null) {
Kenny Root6dceb882012-04-12 14:23:49 -070010110 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
10111 -1);
Kenny Root447106f2011-03-23 11:00:15 -070010112 }
10113 } else {
10114 // Force a gc to clear things up.
10115 Runtime.getRuntime().gc();
10116 // Delete older code
10117 synchronized (mInstallLock) {
10118 mp.srcArgs.doPostDeleteLI(true);
10119 }
10120 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010121
Kenny Root447106f2011-03-23 11:00:15 -070010122 // Allow more operations on this file if we didn't fail because
10123 // an operation was already pending for this package.
10124 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
10125 synchronized (mPackages) {
10126 PackageParser.Package pkg = mPackages.get(mp.packageName);
10127 if (pkg != null) {
10128 pkg.mOperationPending = false;
Kenny Rootdeb11262010-08-02 11:36:21 -070010129 }
10130 }
Kenny Root447106f2011-03-23 11:00:15 -070010131 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010132
Kenny Root447106f2011-03-23 11:00:15 -070010133 IPackageMoveObserver observer = mp.observer;
10134 if (observer != null) {
10135 try {
10136 observer.packageMoved(mp.packageName, returnCode);
10137 } catch (RemoteException e) {
10138 Log.i(TAG, "Observer no longer exists.");
10139 }
10140 }
10141 }
10142 });
10143 }
10144
10145 public boolean setInstallLocation(int loc) {
10146 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
10147 null);
10148 if (getInstallLocation() == loc) {
10149 return true;
10150 }
10151 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
10152 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
Jeff Sharkey625239a2012-09-26 22:03:49 -070010153 android.provider.Settings.Global.putInt(mContext.getContentResolver(),
10154 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
Kenny Root447106f2011-03-23 11:00:15 -070010155 return true;
10156 }
10157 return false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010158 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070010159
Kenny Root447106f2011-03-23 11:00:15 -070010160 public int getInstallLocation() {
Jeff Sharkey625239a2012-09-26 22:03:49 -070010161 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10162 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
Kenny Root447106f2011-03-23 11:00:15 -070010163 PackageHelper.APP_INSTALL_AUTO);
10164 }
Amith Yamasani0b285492011-04-14 17:35:23 -070010165
Amith Yamasani258848d2012-08-10 17:06:33 -070010166 /** Called by UserManagerService */
Dianne Hackborn4428e172012-08-24 17:43:05 -070010167 void cleanUpUserLILPw(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -070010168 if (mDirtyUsers.remove(userHandle));
10169 mSettings.removeUserLPr(userHandle);
10170 if (mInstaller != null) {
10171 // Technically, we shouldn't be doing this with the package lock
10172 // held. However, this is very rare, and there is already so much
10173 // other disk I/O going on, that we'll let it slide for now.
10174 mInstaller.removeUserDataDirs(userHandle);
10175 }
10176 }
10177
10178 /** Called by UserManagerService */
10179 void createNewUserLILPw(int userHandle, File path) {
10180 if (mInstaller != null) {
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080010181 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
Amith Yamasani13593602012-03-22 16:16:17 -070010182 }
10183 }
10184
Kenny Root0aaa0d92011-09-12 16:42:55 -070010185 @Override
10186 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
10187 mContext.enforceCallingOrSelfPermission(
10188 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10189 "Only package verification agents can read the verifier device identity");
10190
10191 synchronized (mPackages) {
10192 return mSettings.getVerifierDeviceIdentityLPw();
10193 }
10194 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010195
Amith Yamasani13593602012-03-22 16:16:17 -070010196 @Override
Jeff Sharkey5d32e772012-04-12 15:59:23 -070010197 public void setPermissionEnforced(String permission, boolean enforced) {
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -070010198 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
10199 if (READ_EXTERNAL_STORAGE.equals(permission)) {
10200 synchronized (mPackages) {
Jeff Sharkeyf5385772012-05-11 14:04:41 -070010201 if (mSettings.mReadExternalStorageEnforced == null
10202 || mSettings.mReadExternalStorageEnforced != enforced) {
Jeff Sharkey5d32e772012-04-12 15:59:23 -070010203 mSettings.mReadExternalStorageEnforced = enforced;
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -070010204 mSettings.writeLPr();
Jeff Sharkeyb9a07012012-03-22 17:00:04 -070010205
10206 // kill any non-foreground processes so we restart them and
10207 // grant/revoke the GID.
10208 final IActivityManager am = ActivityManagerNative.getDefault();
10209 if (am != null) {
10210 final long token = Binder.clearCallingIdentity();
10211 try {
10212 am.killProcessesBelowForeground("setPermissionEnforcement");
10213 } catch (RemoteException e) {
10214 } finally {
10215 Binder.restoreCallingIdentity(token);
10216 }
10217 }
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -070010218 }
10219 }
10220 } else {
10221 throw new IllegalArgumentException("No selective enforcement for " + permission);
10222 }
10223 }
10224
10225 @Override
Jeff Sharkey5d32e772012-04-12 15:59:23 -070010226 public boolean isPermissionEnforced(String permission) {
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -070010227 final boolean enforcedDefault = isPermissionEnforcedDefault(permission);
Jeff Sharkey5d32e772012-04-12 15:59:23 -070010228 synchronized (mPackages) {
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -070010229 return isPermissionEnforcedLocked(permission, enforcedDefault);
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -070010230 }
10231 }
10232
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -070010233 /**
10234 * Check if given permission should be enforced by default. Should always be
10235 * called outside of {@link #mPackages} lock.
10236 */
10237 private boolean isPermissionEnforcedDefault(String permission) {
10238 if (READ_EXTERNAL_STORAGE.equals(permission)) {
Jeff Sharkey625239a2012-09-26 22:03:49 -070010239 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10240 android.provider.Settings.Global.READ_EXTERNAL_STORAGE_ENFORCED_DEFAULT, 0)
10241 != 0;
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -070010242 } else {
10243 return true;
10244 }
10245 }
10246
10247 /**
10248 * Check if user has requested that given permission be enforced, using
10249 * given default if undefined.
10250 */
10251 private boolean isPermissionEnforcedLocked(String permission, boolean enforcedDefault) {
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -070010252 if (READ_EXTERNAL_STORAGE.equals(permission)) {
Jeff Sharkeyf5385772012-05-11 14:04:41 -070010253 if (mSettings.mReadExternalStorageEnforced != null) {
10254 return mSettings.mReadExternalStorageEnforced;
10255 } else {
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -070010256 // User hasn't defined; fall back to secure default
10257 return enforcedDefault;
Jeff Sharkeyf5385772012-05-11 14:04:41 -070010258 }
Jeff Sharkey5d32e772012-04-12 15:59:23 -070010259 } else {
10260 return true;
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -070010261 }
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -070010262 }
Jeff Sharkeyf6f7f1d2012-06-12 17:12:08 -070010263
10264 public boolean isStorageLow() {
10265 final long token = Binder.clearCallingIdentity();
10266 try {
10267 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
10268 .getService(DeviceStorageMonitorService.SERVICE);
10269 return dsm.isMemoryLow();
10270 } finally {
10271 Binder.restoreCallingIdentity(token);
10272 }
10273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010274}