blob: 430edf725e43f721fc6e0d89e3b0119c8ce232da [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 Hackborn0ac30312011-06-17 14:49:23 -070023import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
Kenny Root27989422011-02-23 16:28:26 -080024import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
Jeff Sharkey854b2b12012-04-13 16:03:40 -070025import static com.android.internal.util.ArrayUtils.appendInt;
26import static com.android.internal.util.ArrayUtils.removeInt;
Kenny Root66269ea2011-07-12 14:14:01 -070027import static libcore.io.OsConstants.S_ISLNK;
Kenny Root27989422011-02-23 16:28:26 -080028
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080029import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import com.android.internal.app.ResolverActivity;
Kenny Root85387d72010-08-26 10:13:11 -070031import com.android.internal.content.NativeLibraryHelper;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080032import com.android.internal.content.PackageHelper;
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -070033import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080034import com.android.internal.util.XmlUtils;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070035import com.android.server.DeviceStorageMonitorService;
36import com.android.server.EventLogTags;
37import com.android.server.IntentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038
Jason parksa3cdaa52011-01-13 14:15:43 -060039import org.xmlpull.v1.XmlPullParser;
40import org.xmlpull.v1.XmlPullParserException;
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -070041import org.xmlpull.v1.XmlSerializer;
Jason parksa3cdaa52011-01-13 14:15:43 -060042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.app.ActivityManagerNative;
44import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080045import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080046import android.app.backup.IBackupManager;
Kenny Root5ab21572011-07-27 11:11:19 -070047import android.content.BroadcastReceiver;
Jason parksa3cdaa52011-01-13 14:15:43 -060048import android.content.ComponentName;
Kenny Root27989422011-02-23 16:28:26 -080049import android.content.Context;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070050import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.content.Intent;
52import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070053import android.content.IntentSender;
Jason parks1125d782011-01-12 09:47:26 -060054import android.content.ServiceConnection;
Jason parksa3cdaa52011-01-13 14:15:43 -060055import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.pm.ActivityInfo;
57import android.content.pm.ApplicationInfo;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -070058import android.content.pm.ContainerEncryptionParams;
Dianne Hackborn49237342009-08-27 20:08:01 -070059import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.content.pm.IPackageDataObserver;
61import android.content.pm.IPackageDeleteObserver;
62import android.content.pm.IPackageInstallObserver;
63import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080064import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.content.pm.IPackageStatsObserver;
66import android.content.pm.InstrumentationInfo;
67import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080068import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.content.pm.PackageManager;
Jason parksa3cdaa52011-01-13 14:15:43 -060070import android.content.pm.PackageParser;
Amith Yamasani258848d2012-08-10 17:06:33 -070071import android.content.pm.UserInfo;
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -070072import android.content.pm.PackageParser.ActivityIntentInfo;
Kenny Root27989422011-02-23 16:28:26 -080073import android.content.pm.PackageStats;
Kenny Root0e2c0f32011-04-15 17:50:10 -070074import android.content.pm.ParceledListSlice;
Jason parksa3cdaa52011-01-13 14:15:43 -060075import android.content.pm.PermissionGroupInfo;
Kenny Root27989422011-02-23 16:28:26 -080076import android.content.pm.PermissionInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.content.pm.ProviderInfo;
78import android.content.pm.ResolveInfo;
79import android.content.pm.ServiceInfo;
80import android.content.pm.Signature;
Kenny Root5ab21572011-07-27 11:11:19 -070081import android.content.pm.ManifestDigest;
Kenny Root0aaa0d92011-09-12 16:42:55 -070082import android.content.pm.VerifierDeviceIdentity;
Kenny Root05ca4c92011-09-15 10:36:25 -070083import android.content.pm.VerifierInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.net.Uri;
85import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070086import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.os.Bundle;
Kenny Root27989422011-02-23 16:28:26 -080088import android.os.Environment;
89import android.os.FileObserver;
90import android.os.FileUtils;
91import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080093import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070094import android.os.Looper;
95import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import android.os.Parcel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import android.os.ParcelFileDescriptor;
98import android.os.Process;
Kenny Root27989422011-02-23 16:28:26 -080099import android.os.RemoteException;
rpcraig554cb0c2012-07-05 06:41:43 -0400100import android.os.SELinux;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import android.os.ServiceManager;
102import android.os.SystemClock;
103import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700104import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700105import android.os.UserManager;
Jeff Sharkeyf5385772012-05-11 14:04:41 -0700106import android.provider.Settings.Secure;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800107import android.security.SystemKeyStore;
Kenny Root27989422011-02-23 16:28:26 -0800108import android.util.DisplayMetrics;
109import android.util.EventLog;
110import android.util.Log;
111import android.util.LogPrinter;
112import android.util.Slog;
113import android.util.SparseArray;
114import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import android.view.Display;
116import android.view.WindowManager;
117
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -0700118import java.io.BufferedOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119import java.io.File;
120import java.io.FileDescriptor;
121import java.io.FileInputStream;
122import java.io.FileNotFoundException;
123import java.io.FileOutputStream;
124import java.io.FileReader;
125import java.io.FilenameFilter;
126import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800128import java.security.NoSuchAlgorithmException;
Kenny Root05ca4c92011-09-15 10:36:25 -0700129import java.security.PublicKey;
130import java.security.cert.CertificateException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800131import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132import java.util.ArrayList;
133import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700134import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135import java.util.Collections;
136import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800137import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138import java.util.HashMap;
139import java.util.HashSet;
140import java.util.Iterator;
141import java.util.List;
142import java.util.Map;
Amith Yamasani13593602012-03-22 16:16:17 -0700143import java.util.Map.Entry;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145
Kenny Root66269ea2011-07-12 14:14:01 -0700146import libcore.io.ErrnoException;
Kenny Root3f99afc2012-04-14 10:13:10 -0700147import libcore.io.IoUtils;
Kenny Root66269ea2011-07-12 14:14:01 -0700148import libcore.io.Libcore;
Kenny Root786cbca2012-08-16 11:10:58 -0700149import libcore.io.StructStat;
Kenny Root66269ea2011-07-12 14:14:01 -0700150
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700151/**
152 * Keep track of all those .apks everywhere.
153 *
154 * This is very central to the platform's security; please run the unit
155 * tests whenever making modifications here:
156 *
157mmm frameworks/base/tests/AndroidTests
158adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
159adb 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 -0700160 *
161 * {@hide}
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700162 */
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700163public class PackageManagerService extends IPackageManager.Stub {
164 static final String TAG = "PackageManager";
165 static final boolean DEBUG_SETTINGS = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 private static final boolean DEBUG_PREFERRED = false;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700167 static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800168 private static final boolean DEBUG_INSTALL = false;
Kenny Root9718cf52011-02-23 16:45:26 -0800169 private static final boolean DEBUG_REMOVE = false;
170 private static final boolean DEBUG_SHOW_INFO = false;
171 private static final boolean DEBUG_PACKAGE_INFO = false;
172 private static final boolean DEBUG_INTENT_MATCHING = false;
173 private static final boolean DEBUG_PACKAGE_SCANNING = false;
174 private static final boolean DEBUG_APP_DIR_OBSERVER = false;
Kenny Root05ca4c92011-09-15 10:36:25 -0700175 private static final boolean DEBUG_VERIFY = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400178 private static final int LOG_UID = Process.LOG_UID;
Nick Pellycd0e8392010-10-13 17:25:24 -0700179 private static final int NFC_UID = Process.NFC_UID;
Jaikumar Ganesh1abb1cb2012-01-25 16:14:50 -0800180 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 private static final boolean GET_CERTIFICATES = true;
183
184 private static final int REMOVE_EVENTS =
185 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
186 private static final int ADD_EVENTS =
187 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
188
189 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800190 // Suffix used during package installation when copying/moving
191 // package apks to install directory.
192 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
194 static final int SCAN_MONITOR = 1<<0;
195 static final int SCAN_NO_DEX = 1<<1;
196 static final int SCAN_FORCE_DEX = 1<<2;
197 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800198 static final int SCAN_NEW_INSTALL = 1<<4;
199 static final int SCAN_NO_PATHS = 1<<5;
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700200 static final int SCAN_UPDATE_TIME = 1<<6;
Dianne Hackborn661cd522011-08-22 00:26:20 -0700201 static final int SCAN_DEFER_DEX = 1<<7;
Dianne Hackbornd0c5f512012-06-07 16:53:59 -0700202 static final int SCAN_BOOTING = 1<<8;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700204 static final int REMOVE_CHATTY = 1<<16;
Kenny Root11128572010-10-11 10:51:32 -0700205
Kenny Root5ab21572011-07-27 11:11:19 -0700206 /**
207 * Whether verification is enabled by default.
208 */
Brett Chabotae05e862011-08-24 18:38:26 -0700209 // STOPSHIP: change this to true
210 private static final boolean DEFAULT_VERIFY_ENABLE = false;
Kenny Root5ab21572011-07-27 11:11:19 -0700211
212 /**
213 * The default maximum time to wait for the verification agent to return in
214 * milliseconds.
215 */
rich canningsaa8513e2012-05-21 16:15:23 -0700216 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
Kenny Root5ab21572011-07-27 11:11:19 -0700217
rich canningsa6cfe522012-05-21 15:50:56 -0700218 /**
219 * The default response for package verification timeout.
220 *
221 * This can be either PackageManager.VERIFICATION_ALLOW or
222 * PackageManager.VERIFICATION_REJECT.
223 */
224 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
225
Kenny Root11128572010-10-11 10:51:32 -0700226 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
227
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800228 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
Kenny Root11128572010-10-11 10:51:32 -0700229 DEFAULT_CONTAINER_PACKAGE,
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800230 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700231
Kenny Root05ca4c92011-09-15 10:36:25 -0700232 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
233
Kenny Root85387d72010-08-26 10:13:11 -0700234 private static final String LIB_DIR_NAME = "lib";
235
Kenny Rootc78a8072010-07-27 15:18:38 -0700236 static final String mTempContainerPrefix = "smdl2tmp";
237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
239 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700240 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
Dianne Hackborn851a5412009-05-08 12:06:44 -0700242 final int mSdkVersion = Build.VERSION.SDK_INT;
243 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
244 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 final Context mContext;
247 final boolean mFactoryTest;
Dianne Hackbornd2509fd2011-09-12 12:29:43 -0700248 final boolean mOnlyCore;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700249 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 final DisplayMetrics mMetrics;
251 final int mDefParseFlags;
252 final String[] mSeparateProcesses;
253
254 // This is where all application persistent data goes.
255 final File mAppDataDir;
256
Amith Yamasani0b285492011-04-14 17:35:23 -0700257 // This is where all application persistent data goes for secondary users.
258 final File mUserAppDataDir;
259
Kenny Root51a573c2012-05-17 13:30:28 -0700260 /** The location for ASEC container files on internal storage. */
261 final String mAsecInternalPath;
262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 // This is the object monitoring the framework dir.
264 final FileObserver mFrameworkInstallObserver;
265
266 // This is the object monitoring the system app dir.
267 final FileObserver mSystemInstallObserver;
268
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700269 // This is the object monitoring the system app dir.
270 final FileObserver mVendorInstallObserver;
271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 // This is the object monitoring mAppInstallDir.
273 final FileObserver mAppInstallObserver;
274
275 // This is the object monitoring mDrmAppPrivateInstallDir.
276 final FileObserver mDrmAppInstallObserver;
277
278 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
279 // LOCK HELD. Can be called with mInstallLock held.
280 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 final File mFrameworkDir;
283 final File mSystemAppDir;
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700284 final File mVendorAppDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700286 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287
288 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
289 // apps.
290 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 // Lock for state used when installing and doing other long running
295 // operations. Methods that must be called with this lock held have
296 // the prefix "LI".
297 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 // These are the directories in the 3rd party applications installed dir
300 // that we have currently loaded packages from. Keys are the application's
301 // installed zip file (absolute codePath), and values are Package.
302 final HashMap<String, PackageParser.Package> mAppDirs =
303 new HashMap<String, PackageParser.Package>();
304
305 // Information for the parser to write more useful error messages.
306 File mScanningPath;
307 int mLastScanError;
308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800309 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 // Keys are String (package name), values are Package. This also serves
312 // as the lock for the global state. Methods that must be called with
313 // this lock held have the prefix "LP".
314 final HashMap<String, PackageParser.Package> mPackages =
315 new HashMap<String, PackageParser.Package>();
316
317 final Settings mSettings;
318 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319
320 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
321 int[] mGlobalGids;
322
323 // These are the built-in uid -> permission mappings that were read from the
324 // etc/permissions.xml file.
325 final SparseArray<HashSet<String>> mSystemPermissions =
326 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 // These are the built-in shared libraries that were read from the
329 // etc/permissions.xml file.
330 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800331
Dianne Hackborn49237342009-08-27 20:08:01 -0700332 // Temporary for building the final shared libraries for an .apk.
333 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800334
Dianne Hackborn49237342009-08-27 20:08:01 -0700335 // These are the features this devices supports that were read from the
336 // etc/permissions.xml file.
337 final HashMap<String, FeatureInfo> mAvailableFeatures =
338 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 // All available activities, for your resolving pleasure.
341 final ActivityIntentResolver mActivities =
342 new ActivityIntentResolver();
343
344 // All available receivers, for your resolving pleasure.
345 final ActivityIntentResolver mReceivers =
346 new ActivityIntentResolver();
347
348 // All available services, for your resolving pleasure.
349 final ServiceIntentResolver mServices = new ServiceIntentResolver();
350
351 // Keys are String (provider class name), values are Provider.
352 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
353 new HashMap<ComponentName, PackageParser.Provider>();
354
355 // Mapping from provider base names (first directory in content URI codePath)
356 // to the provider information.
357 final HashMap<String, PackageParser.Provider> mProviders =
358 new HashMap<String, PackageParser.Provider>();
359
360 // Mapping from instrumentation class names to info about them.
361 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
362 new HashMap<ComponentName, PackageParser.Instrumentation>();
363
364 // Mapping from permission names to info about them.
365 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
366 new HashMap<String, PackageParser.PermissionGroup>();
367
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800368 // Packages whose data we have transfered into another package, thus
369 // should no longer exist.
370 final HashSet<String> mTransferedPackages = new HashSet<String>();
371
Dianne Hackborn854060af2009-07-09 18:14:31 -0700372 // Broadcast actions that are only available to the system.
373 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800374
Kenny Root5ab21572011-07-27 11:11:19 -0700375 /** List of packages waiting for verification. */
Kenny Root05ca4c92011-09-15 10:36:25 -0700376 final SparseArray<PackageVerificationState> mPendingVerification
377 = new SparseArray<PackageVerificationState>();
Kenny Root5ab21572011-07-27 11:11:19 -0700378
Dianne Hackborn661cd522011-08-22 00:26:20 -0700379 final ArrayList<PackageParser.Package> mDeferredDexOpt =
380 new ArrayList<PackageParser.Package>();
381
Kenny Root5ab21572011-07-27 11:11:19 -0700382 /** Token for keys in mPendingVerification. */
383 private int mPendingVerificationToken = 0;
384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 boolean mSystemReady;
386 boolean mSafeMode;
387 boolean mHasSystemUidErrors;
388
389 ApplicationInfo mAndroidApplication;
390 final ActivityInfo mResolveActivity = new ActivityInfo();
391 final ResolveInfo mResolveInfo = new ResolveInfo();
392 ComponentName mResolveComponentName;
393 PackageParser.Package mPlatformPackage;
394
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700395 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800396 final HashMap<String, ArrayList<String>> mPendingBroadcasts
397 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800398 // Service Connection to remote media container service to copy
399 // package uri's from external media onto secure containers
400 // or internal storage.
401 private IMediaContainerService mContainerService = null;
402
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700403 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800404 static final int MCS_BOUND = 3;
405 static final int END_COPY = 4;
406 static final int INIT_COPY = 5;
407 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800408 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800409 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800410 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800411 static final int MCS_RECONNECT = 10;
412 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700413 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700414 static final int WRITE_SETTINGS = 13;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700415 static final int WRITE_PACKAGE_RESTRICTIONS = 14;
Kenny Root5ab21572011-07-27 11:11:19 -0700416 static final int PACKAGE_VERIFIED = 15;
417 static final int CHECK_PENDING_VERIFICATION = 16;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700418
419 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800420
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700421 // Delay time in millisecs
422 static final int BROADCAST_DELAY = 10 * 1000;
Kenny Root9718cf52011-02-23 16:45:26 -0800423
Amith Yamasani258848d2012-08-10 17:06:33 -0700424 static UserManagerService sUserManager;
Amith Yamasani0b285492011-04-14 17:35:23 -0700425
Amith Yamasani483f3b02012-03-13 16:08:00 -0700426 // Stores a list of users whose package restrictions file needs to be updated
427 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
428
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800429 final private DefaultContainerConnection mDefContainerConn =
430 new DefaultContainerConnection();
431 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800432 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800433 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800434 IMediaContainerService imcs =
435 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800436 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800437 }
438
439 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800440 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800441 }
442 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700443
Christopher Tate1bb69062010-02-19 17:02:12 -0800444 // Recordkeeping of restore-after-install operations that are currently in flight
445 // between the Package Manager and the Backup Manager
446 class PostInstallData {
447 public InstallArgs args;
448 public PackageInstalledInfo res;
449
450 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
451 args = _a;
452 res = _r;
453 }
454 };
455 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
456 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
457
Kenny Root05ca4c92011-09-15 10:36:25 -0700458 private final String mRequiredVerifierPackage;
459
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700460 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800461 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800462 final ArrayList<HandlerParams> mPendingInstalls =
463 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800464
465 private boolean connectToService() {
466 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
467 " DefaultContainerService");
468 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700469 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800470 if (mContext.bindService(service, mDefContainerConn,
471 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700472 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800473 mBound = true;
474 return true;
475 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700476 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800477 return false;
478 }
479
480 private void disconnectService() {
481 mContainerService = null;
482 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700483 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800484 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700485 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800486 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800487
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700488 PackageHandler(Looper looper) {
489 super(looper);
490 }
Dianne Hackborn7d608422011-08-07 16:24:18 -0700491
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700492 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700493 try {
494 doHandleMessage(msg);
495 } finally {
496 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
497 }
498 }
499
500 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700501 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800502 case INIT_COPY: {
Kenny Root5ab21572011-07-27 11:11:19 -0700503 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800504 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800505 int idx = mPendingInstalls.size();
Kenny Root5ab21572011-07-27 11:11:19 -0700506 if (DEBUG_INSTALL) Slog.i(TAG, "idx=" + idx);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800507 // If a bind was already initiated we dont really
508 // need to do anything. The pending install
509 // will be processed later on.
510 if (!mBound) {
511 // If this is the only one pending we might
512 // have to bind to the service again.
513 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800514 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800515 params.serviceError();
516 return;
517 } else {
518 // Once we bind to the service, the first
519 // pending request will be processed.
520 mPendingInstalls.add(idx, params);
521 }
522 } else {
523 mPendingInstalls.add(idx, params);
524 // Already bound to the service. Just make
525 // sure we trigger off processing the first request.
526 if (idx == 0) {
527 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800528 }
529 }
530 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800531 }
532 case MCS_BOUND: {
Kenny Root5ab21572011-07-27 11:11:19 -0700533 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800534 if (msg.obj != null) {
535 mContainerService = (IMediaContainerService) msg.obj;
536 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800537 if (mContainerService == null) {
538 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800539 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800540 for (HandlerParams params : mPendingInstalls) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800541 // Indicate service bind error
542 params.serviceError();
543 }
544 mPendingInstalls.clear();
545 } else if (mPendingInstalls.size() > 0) {
546 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800547 if (params != null) {
Dianne Hackborn7d608422011-08-07 16:24:18 -0700548 if (params.startCopy()) {
549 // We are done... look for more work or to
550 // go idle.
551 if (DEBUG_SD_INSTALL) Log.i(TAG,
552 "Checking for more work or unbind...");
553 // Delete pending install
554 if (mPendingInstalls.size() > 0) {
555 mPendingInstalls.remove(0);
556 }
557 if (mPendingInstalls.size() == 0) {
558 if (mBound) {
559 if (DEBUG_SD_INSTALL) Log.i(TAG,
560 "Posting delayed MCS_UNBIND");
561 removeMessages(MCS_UNBIND);
562 Message ubmsg = obtainMessage(MCS_UNBIND);
563 // Unbind after a little delay, to avoid
564 // continual thrashing.
565 sendMessageDelayed(ubmsg, 10000);
566 }
567 } else {
568 // There are more pending requests in queue.
569 // Just post MCS_BOUND message to trigger processing
570 // of next pending install.
571 if (DEBUG_SD_INSTALL) Log.i(TAG,
572 "Posting MCS_BOUND for next woek");
573 mHandler.sendEmptyMessage(MCS_BOUND);
574 }
575 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800576 }
577 } else {
578 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800579 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800580 }
581 break;
582 }
Kenny Root5ab21572011-07-27 11:11:19 -0700583 case MCS_RECONNECT: {
584 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800585 if (mPendingInstalls.size() > 0) {
586 if (mBound) {
587 disconnectService();
588 }
589 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800590 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800591 for (HandlerParams params : mPendingInstalls) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800592 // Indicate service bind error
593 params.serviceError();
594 }
595 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800596 }
597 }
598 break;
599 }
Kenny Root5ab21572011-07-27 11:11:19 -0700600 case MCS_UNBIND: {
Dianne Hackborn7d608422011-08-07 16:24:18 -0700601 // If there is no actual work left, then time to unbind.
Kenny Root5ab21572011-07-27 11:11:19 -0700602 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
603
604 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800605 if (mBound) {
Kenny Root5ab21572011-07-27 11:11:19 -0700606 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
607
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800608 disconnectService();
609 }
Kenny Root5ab21572011-07-27 11:11:19 -0700610 } else if (mPendingInstalls.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800611 // There are more pending requests in queue.
612 // Just post MCS_BOUND message to trigger processing
613 // of next pending install.
614 mHandler.sendEmptyMessage(MCS_BOUND);
615 }
Kenny Root5ab21572011-07-27 11:11:19 -0700616
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800617 break;
618 }
619 case MCS_GIVE_UP: {
Kenny Root5ab21572011-07-27 11:11:19 -0700620 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
Kenny Root60f7ad82011-03-22 12:49:06 -0700621 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800622 break;
623 }
Kenny Root5ab21572011-07-27 11:11:19 -0700624 case SEND_PENDING_BROADCAST: {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800625 String packages[];
Kenny Root60f7ad82011-03-22 12:49:06 -0700626 ArrayList<String> components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700627 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700628 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700629 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700630 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800631 if (mPendingBroadcasts == null) {
632 return;
633 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700634 size = mPendingBroadcasts.size();
635 if (size <= 0) {
636 // Nothing to be done. Just return
637 return;
638 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800639 packages = new String[size];
640 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700641 uids = new int[size];
Andy McFadden2f362292012-01-20 14:43:38 -0800642 Iterator<Map.Entry<String, ArrayList<String>>>
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800643 it = mPendingBroadcasts.entrySet().iterator();
644 int i = 0;
645 while (it.hasNext() && i < size) {
Andy McFadden2f362292012-01-20 14:43:38 -0800646 Map.Entry<String, ArrayList<String>> ent = it.next();
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800647 packages[i] = ent.getKey();
648 components[i] = ent.getValue();
649 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Amith Yamasani13593602012-03-22 16:16:17 -0700650 uids[i] = (ps != null) ? ps.appId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800651 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700652 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800653 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700654 mPendingBroadcasts.clear();
655 }
656 // Send broadcasts
657 for (int i = 0; i < size; i++) {
Kenny Root60f7ad82011-03-22 12:49:06 -0700658 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700659 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700660 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700661 break;
662 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800663 case START_CLEANING_PACKAGE: {
664 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700665 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800666 synchronized (mPackages) {
667 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
668 mSettings.mPackagesToBeCleaned.add(packageName);
669 }
670 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700671 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800672 startCleaningPackages();
673 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800674 case POST_INSTALL: {
675 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
676 PostInstallData data = mRunningInstalls.get(msg.arg1);
677 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700678 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800679
680 if (data != null) {
681 InstallArgs args = data.args;
682 PackageInstalledInfo res = data.res;
683
684 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700685 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800686 Bundle extras = new Bundle(1);
687 extras.putInt(Intent.EXTRA_UID, res.uid);
688 final boolean update = res.removedInfo.removedPackage != null;
689 if (update) {
690 extras.putBoolean(Intent.EXTRA_REPLACING, true);
691 }
692 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
693 res.pkg.applicationInfo.packageName,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700694 extras, null, null, UserHandle.USER_ALL);
Christopher Tate1bb69062010-02-19 17:02:12 -0800695 if (update) {
696 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
697 res.pkg.applicationInfo.packageName,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700698 extras, null, null, UserHandle.USER_ALL);
Dianne Hackborne7f97212011-02-24 14:40:20 -0800699 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
700 null, null,
Amith Yamasani13593602012-03-22 16:16:17 -0700701 res.pkg.applicationInfo.packageName, null,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700702 UserHandle.USER_ALL);
Christopher Tate1bb69062010-02-19 17:02:12 -0800703 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700704 if (res.removedInfo.args != null) {
705 // Remove the replaced package's older resources safely now
706 deleteOld = true;
707 }
Matt Finifterf8a98ed2012-05-14 15:43:34 -0700708
709 // Log current value of "unknown sources" setting
710 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
711 getUnknownSourcesSettings());
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700712 }
713 // Force a gc to clear up things
714 Runtime.getRuntime().gc();
715 // We delete after a gc for applications on sdcard.
716 if (deleteOld) {
717 synchronized (mInstallLock) {
718 res.removedInfo.args.doPostDeleteLI(true);
719 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800720 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800721 if (args.observer != null) {
722 try {
723 args.observer.packageInstalled(res.name, res.returnCode);
724 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800725 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800726 }
727 }
728 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800729 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800730 }
731 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700732 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700733 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
734 boolean reportStatus = msg.arg1 == 1;
735 boolean doGc = msg.arg2 == 1;
736 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
737 if (doGc) {
738 // Force a gc to clear up stale containers.
739 Runtime.getRuntime().gc();
740 }
741 if (msg.obj != null) {
Dianne Hackbornba24e4d2011-09-01 11:17:06 -0700742 @SuppressWarnings("unchecked")
Kenny Root6dceb882012-04-12 14:23:49 -0700743 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700744 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
745 // Unload containers
746 unloadAllContainers(args);
747 }
748 if (reportStatus) {
749 try {
750 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
751 PackageHelper.getMountService().finishMediaUpdate();
752 } catch (RemoteException e) {
753 Log.e(TAG, "MountService not running?");
754 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700755 }
756 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700757 case WRITE_SETTINGS: {
758 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
759 synchronized (mPackages) {
760 removeMessages(WRITE_SETTINGS);
Amith Yamasani483f3b02012-03-13 16:08:00 -0700761 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
Kenny Root447106f2011-03-23 11:00:15 -0700762 mSettings.writeLPr();
Amith Yamasani483f3b02012-03-13 16:08:00 -0700763 mDirtyUsers.clear();
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700764 }
765 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
766 } break;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700767 case WRITE_PACKAGE_RESTRICTIONS: {
Dianne Hackborne7f97212011-02-24 14:40:20 -0800768 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
769 synchronized (mPackages) {
Amith Yamasani483f3b02012-03-13 16:08:00 -0700770 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
771 for (int userId : mDirtyUsers) {
772 mSettings.writePackageRestrictionsLPr(userId);
773 }
774 mDirtyUsers.clear();
Dianne Hackborne7f97212011-02-24 14:40:20 -0800775 }
776 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
777 } break;
Kenny Root5ab21572011-07-27 11:11:19 -0700778 case CHECK_PENDING_VERIFICATION: {
779 final int verificationId = msg.arg1;
Kenny Root05ca4c92011-09-15 10:36:25 -0700780 final PackageVerificationState state = mPendingVerification.get(verificationId);
Kenny Root5ab21572011-07-27 11:11:19 -0700781
Kenny Root05ca4c92011-09-15 10:36:25 -0700782 if (state != null) {
783 final InstallArgs args = state.getInstallArgs();
Kenny Roota503a0f2011-10-03 14:45:28 -0700784 Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
Kenny Root5ab21572011-07-27 11:11:19 -0700785 mPendingVerification.remove(verificationId);
786
rich canningsa6cfe522012-05-21 15:50:56 -0700787 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
788
789 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
790 Slog.i(TAG, "Continuing with installation of " + args.packageURI.toString());
791 state.setVerifierResponse(Binder.getCallingUid(), PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
792 try {
793 ret = args.copyApk(mContainerService, true);
794 } catch (RemoteException e) {
795 Slog.e(TAG, "Could not contact the ContainerService");
796 }
797 }
798
Kenny Root5ab21572011-07-27 11:11:19 -0700799 processPendingInstall(args, ret);
800
801 mHandler.sendEmptyMessage(MCS_UNBIND);
802 }
803
804 break;
805 }
806 case PACKAGE_VERIFIED: {
807 final int verificationId = msg.arg1;
Kenny Root5ab21572011-07-27 11:11:19 -0700808
Kenny Root05ca4c92011-09-15 10:36:25 -0700809 final PackageVerificationState state = mPendingVerification.get(verificationId);
810 if (state == null) {
Kenny Roota503a0f2011-10-03 14:45:28 -0700811 Slog.w(TAG, "Invalid verification token " + verificationId + " received");
Kenny Root5ab21572011-07-27 11:11:19 -0700812 break;
813 }
814
Kenny Root05ca4c92011-09-15 10:36:25 -0700815 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
Kenny Root5ab21572011-07-27 11:11:19 -0700816
Kenny Root05ca4c92011-09-15 10:36:25 -0700817 state.setVerifierResponse(response.callerUid, response.code);
818
819 if (state.isVerificationComplete()) {
820 mPendingVerification.remove(verificationId);
821
822 final InstallArgs args = state.getInstallArgs();
823
824 int ret;
825 if (state.isInstallAllowed()) {
826 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
827 try {
828 ret = args.copyApk(mContainerService, true);
829 } catch (RemoteException e) {
830 Slog.e(TAG, "Could not contact the ContainerService");
831 }
832 } else {
833 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
Kenny Root5ab21572011-07-27 11:11:19 -0700834 }
Kenny Root05ca4c92011-09-15 10:36:25 -0700835
836 processPendingInstall(args, ret);
837
838 mHandler.sendEmptyMessage(MCS_UNBIND);
Kenny Root5ab21572011-07-27 11:11:19 -0700839 }
840
Kenny Root5ab21572011-07-27 11:11:19 -0700841 break;
842 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700843 }
844 }
845 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800846
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700847 void scheduleWriteSettingsLocked() {
848 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
849 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
850 }
851 }
Amith Yamasani483f3b02012-03-13 16:08:00 -0700852
853 void scheduleWritePackageRestrictionsLocked(int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -0700854 if (!sUserManager.exists(userId)) return;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700855 mDirtyUsers.add(userId);
856 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
857 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
Dianne Hackborne7f97212011-02-24 14:40:20 -0800858 }
859 }
860
Dianne Hackbornd2509fd2011-09-12 12:29:43 -0700861 public static final IPackageManager main(Context context, boolean factoryTest,
862 boolean onlyCore) {
863 PackageManagerService m = new PackageManagerService(context, factoryTest, onlyCore);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 ServiceManager.addService("package", m);
865 return m;
866 }
867
868 static String[] splitString(String str, char sep) {
869 int count = 1;
870 int i = 0;
871 while ((i=str.indexOf(sep, i)) >= 0) {
872 count++;
873 i++;
874 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800875
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 String[] res = new String[count];
877 i=0;
878 count = 0;
879 int lastI=0;
880 while ((i=str.indexOf(sep, i)) >= 0) {
881 res[count] = str.substring(lastI, i);
882 count++;
883 i++;
884 lastI = i;
885 }
886 res[count] = str.substring(lastI, str.length());
887 return res;
888 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800889
Dianne Hackbornd2509fd2011-09-12 12:29:43 -0700890 public PackageManagerService(Context context, boolean factoryTest, boolean onlyCore) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800891 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800895 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 mContext = context;
899 mFactoryTest = factoryTest;
Dianne Hackbornd2509fd2011-09-12 12:29:43 -0700900 mOnlyCore = onlyCore;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700901 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 mMetrics = new DisplayMetrics();
Amith Yamasani258848d2012-08-10 17:06:33 -0700903 mSettings = new Settings(context);
Kenny Root447106f2011-03-23 11:00:15 -0700904 mSettings.addSharedUserLPw("android.uid.system",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800906 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, ApplicationInfo.FLAG_SYSTEM);
907 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, ApplicationInfo.FLAG_SYSTEM);
908 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, ApplicationInfo.FLAG_SYSTEM);
Jaikumar Ganesh1abb1cb2012-01-25 16:14:50 -0800909 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910
911 String separateProcesses = SystemProperties.get("debug.separate_processes");
912 if (separateProcesses != null && separateProcesses.length() > 0) {
913 if ("*".equals(separateProcesses)) {
914 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
915 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800916 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 } else {
918 mDefParseFlags = 0;
919 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800920 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 + separateProcesses);
922 }
923 } else {
924 mDefParseFlags = 0;
925 mSeparateProcesses = null;
926 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800927
Jeff Brown5d6d90f2011-07-11 13:04:53 -0700928 mInstaller = new Installer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929
930 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
931 Display d = wm.getDefaultDisplay();
932 d.getMetrics(mMetrics);
933
934 synchronized (mInstallLock) {
Kenny Root447106f2011-03-23 11:00:15 -0700935 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 synchronized (mPackages) {
937 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700938 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 File dataDir = Environment.getDataDirectory();
941 mAppDataDir = new File(dataDir, "data");
Kenny Root51a573c2012-05-17 13:30:28 -0700942 mAsecInternalPath = new File(dataDir, "app-asec").getPath();
Amith Yamasani0b285492011-04-14 17:35:23 -0700943 mUserAppDataDir = new File(dataDir, "user");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
945
Amith Yamasani258848d2012-08-10 17:06:33 -0700946 sUserManager = UserManagerService.getInstance(context);
947 sUserManager.setInstaller(this, mInstaller);
Amith Yamasani0b285492011-04-14 17:35:23 -0700948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 readPermissions();
950
Amith Yamasani258848d2012-08-10 17:06:33 -0700951 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800953
954 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800956
Suchi Amalapurapudaec1722010-01-14 21:25:16 -0800957 // Set flag to monitor and not change apk file paths when
958 // scanning install directories.
Dianne Hackbornd0c5f512012-06-07 16:53:59 -0700959 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700960 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800961 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800962 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700963 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700968 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800969
Jeff Brown5d6d90f2011-07-11 13:04:53 -0700970 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800971
Jeff Brown5d6d90f2011-07-11 13:04:53 -0700972 /**
973 * Out of paranoia, ensure that everything in the boot class
974 * path has been dexed.
975 */
976 String bootClassPath = System.getProperty("java.boot.class.path");
977 if (bootClassPath != null) {
978 String[] paths = splitString(bootClassPath, ':');
979 for (int i=0; i<paths.length; i++) {
980 try {
981 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
982 libFiles.add(paths[i]);
983 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
984 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -0700986 } catch (FileNotFoundException e) {
987 Slog.w(TAG, "Boot class path not found: " + paths[i]);
988 } catch (IOException e) {
Kenny Rootfec5e752011-09-23 10:09:58 -0700989 Slog.w(TAG, "Cannot dexopt " + paths[i] + "; is it an APK or JAR? "
990 + e.getMessage());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 }
992 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -0700993 } else {
994 Slog.w(TAG, "No BOOTCLASSPATH found!");
995 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800996
Jeff Brown5d6d90f2011-07-11 13:04:53 -0700997 /**
998 * Also ensure all external libraries have had dexopt run on them.
999 */
1000 if (mSharedLibraries.size() > 0) {
1001 Iterator<String> libs = mSharedLibraries.values().iterator();
1002 while (libs.hasNext()) {
1003 String lib = libs.next();
1004 try {
1005 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
1006 libFiles.add(lib);
1007 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
1008 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001010 } catch (FileNotFoundException e) {
1011 Slog.w(TAG, "Library not found: " + lib);
1012 } catch (IOException e) {
Kenny Rootfec5e752011-09-23 10:09:58 -07001013 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1014 + e.getMessage());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 }
1016 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001017 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001018
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001019 // Gross hack for now: we know this file doesn't contain any
1020 // code, so don't dexopt it to avoid the resulting log spew.
1021 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
1022
1023 /**
1024 * And there are a number of commands implemented in Java, which
1025 * we currently need to do the dexopt on so that they can be
1026 * run from a non-root shell.
1027 */
1028 String[] frameworkFiles = mFrameworkDir.list();
1029 if (frameworkFiles != null) {
1030 for (int i=0; i<frameworkFiles.length; i++) {
1031 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
1032 String path = libPath.getPath();
1033 // Skip the file if we alrady did it.
1034 if (libFiles.contains(path)) {
1035 continue;
1036 }
1037 // Skip the file if it is not a type we want to dexopt.
1038 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1039 continue;
1040 }
1041 try {
1042 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
1043 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
1044 didDexOpt = true;
1045 }
1046 } catch (FileNotFoundException e) {
1047 Slog.w(TAG, "Jar not found: " + path);
1048 } catch (IOException e) {
1049 Slog.w(TAG, "Exception reading jar: " + path, e);
1050 }
1051 }
1052 }
1053
1054 if (didDexOpt) {
1055 // If we had to do a dexopt of one of the previous
1056 // things, then something on the system has changed.
1057 // Consider this significant, and wipe away all other
1058 // existing dexopt files to ensure we don't leave any
1059 // dangling around.
1060 String[] files = mDalvikCacheDir.list();
1061 if (files != null) {
1062 for (int i=0; i<files.length; i++) {
1063 String fn = files[i];
1064 if (fn.startsWith("data@app@")
1065 || fn.startsWith("data@app-private@")) {
1066 Slog.i(TAG, "Pruning dalvik file: " + fn);
1067 (new File(mDalvikCacheDir, fn)).delete();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001068 }
1069 }
1070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001072
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001073 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 mFrameworkInstallObserver = new AppDirObserver(
1075 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
1076 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -07001077 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
1078 | PackageParser.PARSE_IS_SYSTEM_DIR,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001079 scanMode | SCAN_NO_DEX, 0);
Kenny Root51a573c2012-05-17 13:30:28 -07001080
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001081 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
1083 mSystemInstallObserver = new AppDirObserver(
1084 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
1085 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -07001086 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001087 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Kenny Root208d3412012-05-07 19:42:35 -07001088
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07001089 // Collect all vendor packages.
1090 mVendorAppDir = new File("/vendor/app");
1091 mVendorInstallObserver = new AppDirObserver(
1092 mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
1093 mVendorInstallObserver.startWatching();
1094 scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001095 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07001096
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001097 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1098 mInstaller.moveFiles();
1099
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001100 // Prune any system packages that no longer exist.
Kenny Root87b5d7b2012-05-16 13:36:18 -07001101 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001102 if (!mOnlyCore) {
1103 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1104 while (psit.hasNext()) {
1105 PackageSetting ps = psit.next();
Kenny Root208d3412012-05-07 19:42:35 -07001106
1107 /*
1108 * If this is not a system app, it can't be a
1109 * disable system app.
1110 */
1111 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1112 continue;
1113 }
1114
1115 /*
1116 * If the package is scanned, it's not erased.
1117 */
Kenny Rooteca64b32012-06-25 16:37:32 -07001118 final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1119 if (scannedPkg != null) {
Kenny Root208d3412012-05-07 19:42:35 -07001120 /*
1121 * If the system app is both scanned and in the
1122 * disabled packages list, then it must have been
1123 * added via OTA. Remove it from the currently
1124 * scanned package so the previously user-installed
1125 * application can be scanned.
1126 */
1127 if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
Kenny Rooteca64b32012-06-25 16:37:32 -07001128 Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1129 + "; removing system app");
1130 removePackageLI(scannedPkg, true);
Kenny Root208d3412012-05-07 19:42:35 -07001131 }
1132
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001133 continue;
1134 }
1135
1136 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001137 psit.remove();
1138 String msg = "System package " + ps.name
1139 + " no longer exists; wiping its data";
1140 reportSettingsProblem(Log.WARN, msg);
1141 mInstaller.remove(ps.name, 0);
Amith Yamasani13593602012-03-22 16:16:17 -07001142 sUserManager.removePackageForAllUsers(ps.name);
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001143 } else {
Kenny Root87b5d7b2012-05-16 13:36:18 -07001144 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1145 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1146 possiblyDeletedUpdatedSystemApps.add(ps.name);
1147 }
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001148 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001149 }
1150 }
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 mAppInstallDir = new File(dataDir, "app");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 //look for any incomplete package installations
Kenny Root447106f2011-03-23 11:00:15 -07001154 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 //clean up list
1156 for(int i = 0; i < deletePkgsList.size(); i++) {
1157 //clean up here
1158 cleanupInstallFailedPackage(deletePkgsList.get(i));
1159 }
1160 //delete tmp files
1161 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001162
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001163 if (!mOnlyCore) {
1164 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1165 SystemClock.uptimeMillis());
1166 mAppInstallObserver = new AppDirObserver(
1167 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
1168 mAppInstallObserver.startWatching();
1169 scanDirLI(mAppInstallDir, 0, scanMode, 0);
1170
1171 mDrmAppInstallObserver = new AppDirObserver(
1172 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
1173 mDrmAppInstallObserver.startWatching();
1174 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1175 scanMode, 0);
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001176
1177 /**
Kenny Root87b5d7b2012-05-16 13:36:18 -07001178 * Remove disable package settings for any updated system
1179 * apps that were removed via an OTA. If they're not a
1180 * previously-updated app, remove them completely.
1181 * Otherwise, just revoke their system-level permissions.
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001182 */
Kenny Root87b5d7b2012-05-16 13:36:18 -07001183 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001184 PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
Kenny Root87b5d7b2012-05-16 13:36:18 -07001185 mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1186
1187 String msg;
1188 if (deletedPkg == null) {
1189 msg = "Updated system package " + deletedAppName
1190 + " no longer exists; wiping its data";
1191
1192 mInstaller.remove(deletedAppName, 0);
1193 sUserManager.removePackageForAllUsers(deletedAppName);
1194 } else {
1195 msg = "Updated system app + " + deletedAppName
1196 + " no longer present; removing system privileges for "
1197 + deletedAppName;
1198
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001199 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1200
1201 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1202 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1203 }
Kenny Root87b5d7b2012-05-16 13:36:18 -07001204 reportSettingsProblem(Log.WARN, msg);
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001205 }
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001206 } else {
1207 mAppInstallObserver = null;
1208 mDrmAppInstallObserver = null;
1209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001211 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001213 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 + ((SystemClock.uptimeMillis()-startTime)/1000f)
1215 + " seconds");
1216
Dianne Hackbornf22221f2010-04-05 18:35:42 -07001217 // If the platform SDK has changed since the last time we booted,
1218 // we need to re-grant app permission to catch any new ones that
1219 // appear. This is really a hack, and means that apps can in some
1220 // cases get permissions that the user didn't initially explicitly
1221 // allow... it would be nice to have some better way to handle
1222 // this situation.
1223 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1224 != mSdkVersion;
1225 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1226 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1227 + "; regranting permissions for internal storage");
1228 mSettings.mInternalSdkPlatform = mSdkVersion;
1229
Dianne Hackborne639da72012-02-21 15:11:13 -08001230 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1231 | (regrantPermissions
1232 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1233 : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234
Dianne Hackborn04505102012-02-29 12:34:04 -08001235 // Verify that all of the preferred activity components actually
1236 // exist. It is possible for applications to be updated and at
1237 // that point remove a previously declared activity component that
1238 // had been set as a preferred activity. We try to clean this up
1239 // the next time we encounter that preferred activity, but it is
1240 // possible for the user flow to never be able to return to that
1241 // situation so here we do a sanity check to make sure we haven't
1242 // left any junk around.
1243 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
1244 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
1245 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
1246 removed.add(pa);
1247 }
1248 }
1249 for (int i=0; i<removed.size(); i++) {
1250 PreferredActivity pa = removed.get(i);
1251 Slog.w(TAG, "Removing dangling preferred activity: "
1252 + pa.mPref.mComponent);
1253 mSettings.mPreferredActivities.removeFilter(pa);
1254 }
1255
Kenny Root447106f2011-03-23 11:00:15 -07001256 // can downgrade to reader
1257 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001259 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 // Now after opening every single application zip, make sure they
1263 // are all flushed. Not really needed, but keeps things nice and
1264 // tidy.
1265 Runtime.getRuntime().gc();
Kenny Root05ca4c92011-09-15 10:36:25 -07001266
1267 mRequiredVerifierPackage = getRequiredVerifierLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 } // synchronized (mPackages)
1269 } // synchronized (mInstallLock)
1270 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001271
Dianne Hackborn58f42a52011-10-10 13:46:34 -07001272 public boolean isFirstBoot() {
1273 return !mRestoredSettings;
1274 }
1275
Kenny Root05ca4c92011-09-15 10:36:25 -07001276 private String getRequiredVerifierLPr() {
1277 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1278 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
Amith Yamasani483f3b02012-03-13 16:08:00 -07001279 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
Kenny Root05ca4c92011-09-15 10:36:25 -07001280
1281 String requiredVerifier = null;
1282
1283 final int N = receivers.size();
1284 for (int i = 0; i < N; i++) {
1285 final ResolveInfo info = receivers.get(i);
1286
1287 if (info.activityInfo == null) {
1288 continue;
1289 }
1290
1291 final String packageName = info.activityInfo.packageName;
1292
1293 final PackageSetting ps = mSettings.mPackages.get(packageName);
1294 if (ps == null) {
1295 continue;
1296 }
1297
1298 if (!ps.grantedPermissions
1299 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1300 continue;
1301 }
1302
1303 if (requiredVerifier != null) {
1304 throw new RuntimeException("There can be only one required verifier");
1305 }
1306
1307 requiredVerifier = packageName;
1308 }
1309
1310 return requiredVerifier;
1311 }
1312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 @Override
1314 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1315 throws RemoteException {
1316 try {
1317 return super.onTransact(code, data, reply, flags);
1318 } catch (RuntimeException e) {
1319 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001320 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 }
1322 throw e;
1323 }
1324 }
1325
Dianne Hackborne6620b22010-01-22 14:46:21 -08001326 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001327 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001328 int retCode = mInstaller.remove(ps.name, 0);
1329 if (retCode < 0) {
1330 Slog.w(TAG, "Couldn't remove app data directory for package: "
1331 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 } else {
Amith Yamasani13593602012-03-22 16:16:17 -07001333 sUserManager.removePackageForAllUsers(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001335 if (ps.codePath != null) {
1336 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001337 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001338 }
1339 }
1340 if (ps.resourcePath != null) {
1341 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001342 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001343 }
1344 }
Kenny Root447106f2011-03-23 11:00:15 -07001345 mSettings.removePackageLPw(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 }
1347
1348 void readPermissions() {
1349 // Read permissions from .../etc/permission directory.
1350 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1351 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001352 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 return;
1354 }
1355 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001356 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 return;
1358 }
1359
1360 // Iterate over the files in the directory and scan .xml files
1361 for (File f : libraryDir.listFiles()) {
1362 // We'll read platform.xml last
1363 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1364 continue;
1365 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001368 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 continue;
1370 }
1371 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001372 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 continue;
1374 }
1375
1376 readPermissionsFromXml(f);
1377 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1380 final File permFile = new File(Environment.getRootDirectory(),
1381 "etc/permissions/platform.xml");
1382 readPermissionsFromXml(permFile);
1383 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001384
1385 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 FileReader permReader = null;
1387 try {
1388 permReader = new FileReader(permFile);
1389 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001390 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 return;
1392 }
1393
1394 try {
1395 XmlPullParser parser = Xml.newPullParser();
1396 parser.setInput(permReader);
1397
1398 XmlUtils.beginDocument(parser, "permissions");
1399
1400 while (true) {
1401 XmlUtils.nextElement(parser);
1402 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1403 break;
1404 }
1405
1406 String name = parser.getName();
1407 if ("group".equals(name)) {
1408 String gidStr = parser.getAttributeValue(null, "gid");
1409 if (gidStr != null) {
1410 int gid = Integer.parseInt(gidStr);
1411 mGlobalGids = appendInt(mGlobalGids, gid);
1412 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001413 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 + parser.getPositionDescription());
1415 }
1416
1417 XmlUtils.skipCurrentTag(parser);
1418 continue;
1419 } else if ("permission".equals(name)) {
1420 String perm = parser.getAttributeValue(null, "name");
1421 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001422 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 + parser.getPositionDescription());
1424 XmlUtils.skipCurrentTag(parser);
1425 continue;
1426 }
1427 perm = perm.intern();
1428 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 } else if ("assign-permission".equals(name)) {
1431 String perm = parser.getAttributeValue(null, "name");
1432 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001433 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 + parser.getPositionDescription());
1435 XmlUtils.skipCurrentTag(parser);
1436 continue;
1437 }
1438 String uidStr = parser.getAttributeValue(null, "uid");
1439 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001440 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 + parser.getPositionDescription());
1442 XmlUtils.skipCurrentTag(parser);
1443 continue;
1444 }
1445 int uid = Process.getUidForName(uidStr);
1446 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001447 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 + uidStr + "\" at "
1449 + parser.getPositionDescription());
1450 XmlUtils.skipCurrentTag(parser);
1451 continue;
1452 }
1453 perm = perm.intern();
1454 HashSet<String> perms = mSystemPermissions.get(uid);
1455 if (perms == null) {
1456 perms = new HashSet<String>();
1457 mSystemPermissions.put(uid, perms);
1458 }
1459 perms.add(perm);
1460 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 } else if ("library".equals(name)) {
1463 String lname = parser.getAttributeValue(null, "name");
1464 String lfile = parser.getAttributeValue(null, "file");
1465 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001466 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 + parser.getPositionDescription());
1468 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001469 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 + parser.getPositionDescription());
1471 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001472 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001473 mSharedLibraries.put(lname, lfile);
1474 }
1475 XmlUtils.skipCurrentTag(parser);
1476 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001477
Dianne Hackborn49237342009-08-27 20:08:01 -07001478 } else if ("feature".equals(name)) {
1479 String fname = parser.getAttributeValue(null, "name");
1480 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001481 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001482 + parser.getPositionDescription());
1483 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001484 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001485 FeatureInfo fi = new FeatureInfo();
1486 fi.name = fname;
1487 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 }
1489 XmlUtils.skipCurrentTag(parser);
1490 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 } else {
1493 XmlUtils.skipCurrentTag(parser);
1494 continue;
1495 }
1496
1497 }
Brian Carlstromfd9ddd12010-11-04 11:24:58 -07001498 permReader.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001500 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001502 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 }
1504 }
1505
1506 void readPermission(XmlPullParser parser, String name)
1507 throws IOException, XmlPullParserException {
1508
1509 name = name.intern();
1510
1511 BasePermission bp = mSettings.mPermissions.get(name);
1512 if (bp == null) {
1513 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1514 mSettings.mPermissions.put(name, bp);
1515 }
1516 int outerDepth = parser.getDepth();
1517 int type;
1518 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1519 && (type != XmlPullParser.END_TAG
1520 || parser.getDepth() > outerDepth)) {
1521 if (type == XmlPullParser.END_TAG
1522 || type == XmlPullParser.TEXT) {
1523 continue;
1524 }
1525
1526 String tagName = parser.getName();
1527 if ("group".equals(tagName)) {
1528 String gidStr = parser.getAttributeValue(null, "gid");
1529 if (gidStr != null) {
1530 int gid = Process.getGidForName(gidStr);
1531 bp.gids = appendInt(bp.gids, gid);
1532 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001533 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 + parser.getPositionDescription());
1535 }
1536 }
1537 XmlUtils.skipCurrentTag(parser);
1538 }
1539 }
1540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 static int[] appendInts(int[] cur, int[] add) {
1542 if (add == null) return cur;
1543 if (cur == null) return add;
1544 final int N = add.length;
1545 for (int i=0; i<N; i++) {
1546 cur = appendInt(cur, add[i]);
1547 }
1548 return cur;
1549 }
1550
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001551 static int[] removeInts(int[] cur, int[] rem) {
1552 if (rem == null) return cur;
1553 if (cur == null) return cur;
1554 final int N = rem.length;
1555 for (int i=0; i<N; i++) {
1556 cur = removeInt(cur, rem[i]);
1557 }
1558 return cur;
1559 }
1560
Amith Yamasani13593602012-03-22 16:16:17 -07001561 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1562 if (!sUserManager.exists(userId)) return null;
1563 PackageInfo pi;
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001564 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1565 // The package has been uninstalled but has retained data and resources.
Amith Yamasani13593602012-03-22 16:16:17 -07001566 pi = PackageParser.generatePackageInfo(p, null, flags, 0, 0, null, false, 0, userId);
1567 } else {
1568 final PackageSetting ps = (PackageSetting) p.mExtras;
1569 if (ps == null) {
1570 return null;
1571 }
1572 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1573 pi = PackageParser.generatePackageInfo(p, gp.gids, flags,
1574 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1575 ps.getStopped(userId), ps.getEnabled(userId), userId);
1576 pi.applicationInfo.enabledSetting = ps.getEnabled(userId);
1577 pi.applicationInfo.enabled =
1578 pi.applicationInfo.enabledSetting == COMPONENT_ENABLED_STATE_DEFAULT
1579 || pi.applicationInfo.enabledSetting == COMPONENT_ENABLED_STATE_ENABLED;
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001580 }
Amith Yamasani13593602012-03-22 16:16:17 -07001581 return pi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 }
1583
Amith Yamasani483f3b02012-03-13 16:08:00 -07001584 @Override
1585 public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001586 if (!sUserManager.exists(userId)) return null;
Kenny Root447106f2011-03-23 11:00:15 -07001587 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 synchronized (mPackages) {
1589 PackageParser.Package p = mPackages.get(packageName);
Kenny Root9718cf52011-02-23 16:45:26 -08001590 if (DEBUG_PACKAGE_INFO)
1591 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 if (p != null) {
Amith Yamasani13593602012-03-22 16:16:17 -07001593 return generatePackageInfo(p, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 }
1595 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001596 return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 }
1598 }
1599 return null;
1600 }
1601
Dianne Hackborn47096932010-02-11 15:57:09 -08001602 public String[] currentToCanonicalPackageNames(String[] names) {
1603 String[] out = new String[names.length];
Kenny Root447106f2011-03-23 11:00:15 -07001604 // reader
Dianne Hackborn47096932010-02-11 15:57:09 -08001605 synchronized (mPackages) {
1606 for (int i=names.length-1; i>=0; i--) {
1607 PackageSetting ps = mSettings.mPackages.get(names[i]);
1608 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1609 }
1610 }
1611 return out;
1612 }
1613
1614 public String[] canonicalToCurrentPackageNames(String[] names) {
1615 String[] out = new String[names.length];
Kenny Root447106f2011-03-23 11:00:15 -07001616 // reader
Dianne Hackborn47096932010-02-11 15:57:09 -08001617 synchronized (mPackages) {
1618 for (int i=names.length-1; i>=0; i--) {
1619 String cur = mSettings.mRenamedPackages.get(names[i]);
1620 out[i] = cur != null ? cur : names[i];
1621 }
1622 }
1623 return out;
1624 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07001625
1626 @Override
1627 public int getPackageUid(String packageName, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001628 if (!sUserManager.exists(userId)) return -1;
Kenny Root447106f2011-03-23 11:00:15 -07001629 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 synchronized (mPackages) {
1631 PackageParser.Package p = mPackages.get(packageName);
1632 if(p != null) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001633 return UserHandle.getUid(userId, p.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 }
1635 PackageSetting ps = mSettings.mPackages.get(packageName);
1636 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1637 return -1;
1638 }
1639 p = ps.pkg;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001640 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 }
1642 }
1643
1644 public int[] getPackageGids(String packageName) {
Kenny Root447106f2011-03-23 11:00:15 -07001645 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 synchronized (mPackages) {
1647 PackageParser.Package p = mPackages.get(packageName);
Kenny Root9718cf52011-02-23 16:45:26 -08001648 if (DEBUG_PACKAGE_INFO)
1649 Log.v(TAG, "getPackageGids" + packageName + ": " + p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 if (p != null) {
1651 final PackageSetting ps = (PackageSetting)p.mExtras;
1652 final SharedUserSetting suid = ps.sharedUser;
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07001653 int[] gids = suid != null ? suid.gids : ps.gids;
1654
1655 // include GIDs for any unenforced permissions
1656 if (!isPermissionEnforcedLocked(READ_EXTERNAL_STORAGE)) {
1657 final BasePermission basePerm = mSettings.mPermissions.get(
1658 READ_EXTERNAL_STORAGE);
1659 gids = appendInts(gids, basePerm.gids);
1660 }
1661
1662 return gids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 }
1664 }
1665 // stupid thing to indicate an error.
1666 return new int[0];
1667 }
1668
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001669 static final PermissionInfo generatePermissionInfo(
1670 BasePermission bp, int flags) {
1671 if (bp.perm != null) {
1672 return PackageParser.generatePermissionInfo(bp.perm, flags);
1673 }
1674 PermissionInfo pi = new PermissionInfo();
1675 pi.name = bp.name;
1676 pi.packageName = bp.sourcePackage;
1677 pi.nonLocalizedLabel = bp.name;
1678 pi.protectionLevel = bp.protectionLevel;
1679 return pi;
1680 }
1681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 public PermissionInfo getPermissionInfo(String name, int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001683 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 synchronized (mPackages) {
1685 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001686 if (p != null) {
1687 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 }
1689 return null;
1690 }
1691 }
1692
1693 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001694 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 synchronized (mPackages) {
1696 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1697 for (BasePermission p : mSettings.mPermissions.values()) {
1698 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001699 if (p.perm == null || p.perm.info.group == null) {
1700 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 }
1702 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001703 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1705 }
1706 }
1707 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 if (out.size() > 0) {
1710 return out;
1711 }
1712 return mPermissionGroups.containsKey(group) ? out : null;
1713 }
1714 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001717 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 synchronized (mPackages) {
1719 return PackageParser.generatePermissionGroupInfo(
1720 mPermissionGroups.get(name), flags);
1721 }
1722 }
1723
1724 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001725 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 synchronized (mPackages) {
1727 final int N = mPermissionGroups.size();
1728 ArrayList<PermissionGroupInfo> out
1729 = new ArrayList<PermissionGroupInfo>(N);
1730 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1731 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1732 }
1733 return out;
1734 }
1735 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001736
Amith Yamasani483f3b02012-03-13 16:08:00 -07001737 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
1738 int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001739 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 PackageSetting ps = mSettings.mPackages.get(packageName);
Kenny Root447106f2011-03-23 11:00:15 -07001741 if (ps != null) {
1742 if (ps.pkg == null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001743 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, flags, userId);
Kenny Root447106f2011-03-23 11:00:15 -07001744 if (pInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 return pInfo.applicationInfo;
1746 }
1747 return null;
1748 }
Amith Yamasani13593602012-03-22 16:16:17 -07001749 return PackageParser.generateApplicationInfo(ps.pkg, flags, ps.getStopped(userId),
1750 ps.getEnabled(userId), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 }
1752 return null;
1753 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001754
Amith Yamasani483f3b02012-03-13 16:08:00 -07001755 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
1756 int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001757 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 PackageSetting ps = mSettings.mPackages.get(packageName);
Kenny Root447106f2011-03-23 11:00:15 -07001759 if (ps != null) {
Amith Yamasani13593602012-03-22 16:16:17 -07001760 PackageParser.Package pkg = new PackageParser.Package(packageName);
Kenny Root447106f2011-03-23 11:00:15 -07001761 if (ps.pkg == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 ps.pkg = new PackageParser.Package(packageName);
1763 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001764 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1765 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1766 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
Amith Yamasani0b285492011-04-14 17:35:23 -07001767 ps.pkg.applicationInfo.dataDir =
1768 getDataPathForPackage(ps.pkg.packageName, 0).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001769 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 }
Amith Yamasani13593602012-03-22 16:16:17 -07001771 // ps.pkg.mSetEnabled = ps.getEnabled(userId);
1772 // ps.pkg.mSetStopped = ps.getStopped(userId);
1773 return generatePackageInfo(ps.pkg, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 }
1775 return null;
1776 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001777
Amith Yamasani483f3b02012-03-13 16:08:00 -07001778 @Override
1779 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001780 if (!sUserManager.exists(userId)) return null;
Kenny Root447106f2011-03-23 11:00:15 -07001781 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 synchronized (mPackages) {
1783 PackageParser.Package p = mPackages.get(packageName);
Kenny Root9718cf52011-02-23 16:45:26 -08001784 if (DEBUG_PACKAGE_INFO) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 TAG, "getApplicationInfo " + packageName
1786 + ": " + p);
1787 if (p != null) {
Amith Yamasani13593602012-03-22 16:16:17 -07001788 PackageSetting ps = mSettings.mPackages.get(packageName);
1789 if (ps == null) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 // Note: isEnabledLP() does not apply here - always return info
Amith Yamasani13593602012-03-22 16:16:17 -07001791 return PackageParser.generateApplicationInfo(p, flags, ps.getStopped(userId),
1792 ps.getEnabled(userId));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 }
1794 if ("android".equals(packageName)||"system".equals(packageName)) {
1795 return mAndroidApplication;
1796 }
1797 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001798 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 }
1800 }
1801 return null;
1802 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001803
1804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1806 mContext.enforceCallingOrSelfPermission(
1807 android.Manifest.permission.CLEAR_APP_CACHE, null);
1808 // Queue up an async operation since clearing cache may take a little while.
1809 mHandler.post(new Runnable() {
1810 public void run() {
1811 mHandler.removeCallbacks(this);
1812 int retCode = -1;
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001813 retCode = mInstaller.freeCache(freeStorageSize);
1814 if (retCode < 0) {
1815 Slog.w(TAG, "Couldn't clear application caches");
1816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 if (observer != null) {
1818 try {
1819 observer.onRemoveCompleted(null, (retCode >= 0));
1820 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001821 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 }
1823 }
1824 }
1825 });
1826 }
1827
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001828 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001829 mContext.enforceCallingOrSelfPermission(
1830 android.Manifest.permission.CLEAR_APP_CACHE, null);
1831 // Queue up an async operation since clearing cache may take a little while.
1832 mHandler.post(new Runnable() {
1833 public void run() {
1834 mHandler.removeCallbacks(this);
1835 int retCode = -1;
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001836 retCode = mInstaller.freeCache(freeStorageSize);
1837 if (retCode < 0) {
1838 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001839 }
1840 if(pi != null) {
1841 try {
1842 // Callback via pending intent
1843 int code = (retCode >= 0) ? 1 : 0;
1844 pi.sendIntent(null, code, null,
1845 null, null);
1846 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001847 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001848 }
1849 }
1850 }
1851 });
1852 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001853
Amith Yamasani483f3b02012-03-13 16:08:00 -07001854 @Override
1855 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001856 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 synchronized (mPackages) {
1858 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001859
Kenny Root9718cf52011-02-23 16:45:26 -08001860 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001861 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
Amith Yamasani13593602012-03-22 16:16:17 -07001862 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
1863 if (ps == null) return null;
1864 return PackageParser.generateActivityInfo(a, flags, ps.getStopped(userId),
1865 ps.getEnabled(userId), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 }
1867 if (mResolveComponentName.equals(component)) {
1868 return mResolveActivity;
1869 }
1870 }
1871 return null;
1872 }
1873
Amith Yamasani483f3b02012-03-13 16:08:00 -07001874 @Override
1875 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001876 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 synchronized (mPackages) {
1878 PackageParser.Activity a = mReceivers.mActivities.get(component);
Kenny Root9718cf52011-02-23 16:45:26 -08001879 if (DEBUG_PACKAGE_INFO) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 TAG, "getReceiverInfo " + component + ": " + a);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001881 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
Amith Yamasani13593602012-03-22 16:16:17 -07001882 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
1883 if (ps == null) return null;
1884 return PackageParser.generateActivityInfo(a, flags, ps.getStopped(userId),
1885 ps.getEnabled(userId), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 }
1887 }
1888 return null;
1889 }
1890
Amith Yamasani483f3b02012-03-13 16:08:00 -07001891 @Override
1892 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001893 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 synchronized (mPackages) {
1895 PackageParser.Service s = mServices.mServices.get(component);
Kenny Root9718cf52011-02-23 16:45:26 -08001896 if (DEBUG_PACKAGE_INFO) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 TAG, "getServiceInfo " + component + ": " + s);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001898 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
Amith Yamasani13593602012-03-22 16:16:17 -07001899 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
1900 if (ps == null) return null;
1901 return PackageParser.generateServiceInfo(s, flags, ps.getStopped(userId),
1902 ps.getEnabled(userId), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903 }
1904 }
1905 return null;
1906 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001907
Amith Yamasani483f3b02012-03-13 16:08:00 -07001908 @Override
1909 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001910 if (!sUserManager.exists(userId)) return null;
Dianne Hackborn361199b2010-08-30 17:42:07 -07001911 synchronized (mPackages) {
1912 PackageParser.Provider p = mProvidersByComponent.get(component);
Kenny Root9718cf52011-02-23 16:45:26 -08001913 if (DEBUG_PACKAGE_INFO) Log.v(
Dianne Hackborn361199b2010-08-30 17:42:07 -07001914 TAG, "getProviderInfo " + component + ": " + p);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001915 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
Amith Yamasani13593602012-03-22 16:16:17 -07001916 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
1917 if (ps == null) return null;
1918 return PackageParser.generateProviderInfo(p, flags, ps.getStopped(userId),
1919 ps.getEnabled(userId), userId);
Dianne Hackborn361199b2010-08-30 17:42:07 -07001920 }
1921 }
1922 return null;
1923 }
1924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 public String[] getSystemSharedLibraryNames() {
1926 Set<String> libSet;
1927 synchronized (mPackages) {
1928 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001929 int size = libSet.size();
1930 if (size > 0) {
1931 String[] libs = new String[size];
1932 libSet.toArray(libs);
1933 return libs;
1934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001936 return null;
1937 }
1938
1939 public FeatureInfo[] getSystemAvailableFeatures() {
1940 Collection<FeatureInfo> featSet;
1941 synchronized (mPackages) {
1942 featSet = mAvailableFeatures.values();
1943 int size = featSet.size();
1944 if (size > 0) {
1945 FeatureInfo[] features = new FeatureInfo[size+1];
1946 featSet.toArray(features);
1947 FeatureInfo fi = new FeatureInfo();
1948 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1949 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1950 features[size] = fi;
1951 return features;
1952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 }
1954 return null;
1955 }
1956
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001957 public boolean hasSystemFeature(String name) {
1958 synchronized (mPackages) {
1959 return mAvailableFeatures.containsKey(name);
1960 }
1961 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001962
Amith Yamasani483f3b02012-03-13 16:08:00 -07001963 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001964 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
Amith Yamasani483f3b02012-03-13 16:08:00 -07001965 return;
1966
1967 throw new SecurityException("Caller uid=" + uid
1968 + " is not privileged to communicate with user=" + userId);
1969 }
1970
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 public int checkPermission(String permName, String pkgName) {
1972 synchronized (mPackages) {
1973 PackageParser.Package p = mPackages.get(pkgName);
1974 if (p != null && p.mExtras != null) {
1975 PackageSetting ps = (PackageSetting)p.mExtras;
1976 if (ps.sharedUser != null) {
1977 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1978 return PackageManager.PERMISSION_GRANTED;
1979 }
1980 } else if (ps.grantedPermissions.contains(permName)) {
1981 return PackageManager.PERMISSION_GRANTED;
1982 }
1983 }
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07001984 if (!isPermissionEnforcedLocked(permName)) {
1985 return PackageManager.PERMISSION_GRANTED;
1986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 }
1988 return PackageManager.PERMISSION_DENIED;
1989 }
1990
1991 public int checkUidPermission(String permName, int uid) {
1992 synchronized (mPackages) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001993 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001995 GrantedPermissions gp = (GrantedPermissions)obj;
1996 if (gp.grantedPermissions.contains(permName)) {
1997 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 }
1999 } else {
2000 HashSet<String> perms = mSystemPermissions.get(uid);
2001 if (perms != null && perms.contains(permName)) {
2002 return PackageManager.PERMISSION_GRANTED;
2003 }
2004 }
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07002005 if (!isPermissionEnforcedLocked(permName)) {
2006 return PackageManager.PERMISSION_GRANTED;
2007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 }
2009 return PackageManager.PERMISSION_DENIED;
2010 }
2011
2012 private BasePermission findPermissionTreeLP(String permName) {
2013 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2014 if (permName.startsWith(bp.name) &&
2015 permName.length() > bp.name.length() &&
2016 permName.charAt(bp.name.length()) == '.') {
2017 return bp;
2018 }
2019 }
2020 return null;
2021 }
2022
2023 private BasePermission checkPermissionTreeLP(String permName) {
2024 if (permName != null) {
2025 BasePermission bp = findPermissionTreeLP(permName);
2026 if (bp != null) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002027 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 return bp;
2029 }
2030 throw new SecurityException("Calling uid "
2031 + Binder.getCallingUid()
2032 + " is not allowed to add to permission tree "
2033 + bp.name + " owned by uid " + bp.uid);
2034 }
2035 }
2036 throw new SecurityException("No permission tree found for " + permName);
2037 }
2038
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002039 static boolean compareStrings(CharSequence s1, CharSequence s2) {
2040 if (s1 == null) {
2041 return s2 == null;
2042 }
2043 if (s2 == null) {
2044 return false;
2045 }
2046 if (s1.getClass() != s2.getClass()) {
2047 return false;
2048 }
2049 return s1.equals(s2);
2050 }
2051
2052 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2053 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07002054 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002055 if (pi1.protectionLevel != pi2.protectionLevel) return false;
2056 if (!compareStrings(pi1.name, pi2.name)) return false;
2057 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2058 // We'll take care of setting this one.
2059 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2060 // These are not currently stored in settings.
2061 //if (!compareStrings(pi1.group, pi2.group)) return false;
2062 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2063 //if (pi1.labelRes != pi2.labelRes) return false;
2064 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2065 return true;
2066 }
2067
2068 boolean addPermissionLocked(PermissionInfo info, boolean async) {
2069 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2070 throw new SecurityException("Label must be specified in permission");
2071 }
2072 BasePermission tree = checkPermissionTreeLP(info.name);
2073 BasePermission bp = mSettings.mPermissions.get(info.name);
2074 boolean added = bp == null;
2075 boolean changed = true;
Dianne Hackborne639da72012-02-21 15:11:13 -08002076 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002077 if (added) {
2078 bp = new BasePermission(info.name, tree.sourcePackage,
2079 BasePermission.TYPE_DYNAMIC);
2080 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2081 throw new SecurityException(
2082 "Not allowed to modify non-dynamic permission "
2083 + info.name);
2084 } else {
Dianne Hackborne639da72012-02-21 15:11:13 -08002085 if (bp.protectionLevel == fixedLevel
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002086 && bp.perm.owner.equals(tree.perm.owner)
2087 && bp.uid == tree.uid
2088 && comparePermissionInfos(bp.perm.info, info)) {
2089 changed = false;
2090 }
2091 }
Dianne Hackborne639da72012-02-21 15:11:13 -08002092 bp.protectionLevel = fixedLevel;
2093 info = new PermissionInfo(info);
2094 info.protectionLevel = fixedLevel;
2095 bp.perm = new PackageParser.Permission(tree.perm.owner, info);
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002096 bp.perm.info.packageName = tree.perm.info.packageName;
2097 bp.uid = tree.uid;
2098 if (added) {
2099 mSettings.mPermissions.put(info.name, bp);
2100 }
2101 if (changed) {
2102 if (!async) {
Kenny Root447106f2011-03-23 11:00:15 -07002103 mSettings.writeLPr();
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002104 } else {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002105 scheduleWriteSettingsLocked();
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002106 }
2107 }
2108 return added;
2109 }
2110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 public boolean addPermission(PermissionInfo info) {
2112 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002113 return addPermissionLocked(info, false);
2114 }
2115 }
2116
2117 public boolean addPermissionAsync(PermissionInfo info) {
2118 synchronized (mPackages) {
2119 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 }
2121 }
2122
2123 public void removePermission(String name) {
2124 synchronized (mPackages) {
2125 checkPermissionTreeLP(name);
2126 BasePermission bp = mSettings.mPermissions.get(name);
2127 if (bp != null) {
2128 if (bp.type != BasePermission.TYPE_DYNAMIC) {
2129 throw new SecurityException(
2130 "Not allowed to modify non-dynamic permission "
2131 + name);
2132 }
2133 mSettings.mPermissions.remove(name);
Kenny Root447106f2011-03-23 11:00:15 -07002134 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 }
2136 }
2137 }
2138
Dianne Hackborne639da72012-02-21 15:11:13 -08002139 public void grantPermission(String packageName, String permissionName) {
2140 mContext.enforceCallingOrSelfPermission(
2141 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2142 synchronized (mPackages) {
2143 final PackageParser.Package pkg = mPackages.get(packageName);
2144 if (pkg == null) {
2145 throw new IllegalArgumentException("Unknown package: " + packageName);
2146 }
2147 final BasePermission bp = mSettings.mPermissions.get(permissionName);
2148 if (bp == null) {
2149 throw new IllegalArgumentException("Unknown permission: " + packageName);
2150 }
2151 if (!pkg.requestedPermissions.contains(permissionName)) {
2152 throw new SecurityException("Package " + packageName
2153 + " has not requested permission " + permissionName);
2154 }
2155 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) == 0) {
2156 throw new SecurityException("Permission " + permissionName
2157 + " is not a development permission");
2158 }
2159 final PackageSetting ps = (PackageSetting) pkg.mExtras;
2160 if (ps == null) {
2161 return;
2162 }
2163 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2164 if (gp.grantedPermissions.add(permissionName)) {
2165 if (ps.haveGids) {
2166 gp.gids = appendInts(gp.gids, bp.gids);
2167 }
2168 mSettings.writeLPr();
2169 }
2170 }
2171 }
2172
2173 public void revokePermission(String packageName, String permissionName) {
2174 synchronized (mPackages) {
2175 final PackageParser.Package pkg = mPackages.get(packageName);
2176 if (pkg == null) {
2177 throw new IllegalArgumentException("Unknown package: " + packageName);
2178 }
2179 if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2180 mContext.enforceCallingOrSelfPermission(
2181 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2182 }
2183 final BasePermission bp = mSettings.mPermissions.get(permissionName);
2184 if (bp == null) {
2185 throw new IllegalArgumentException("Unknown permission: " + packageName);
2186 }
2187 if (!pkg.requestedPermissions.contains(permissionName)) {
2188 throw new SecurityException("Package " + packageName
2189 + " has not requested permission " + permissionName);
2190 }
2191 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) == 0) {
2192 throw new SecurityException("Permission " + permissionName
2193 + " is not a development permission");
2194 }
2195 final PackageSetting ps = (PackageSetting) pkg.mExtras;
2196 if (ps == null) {
2197 return;
2198 }
2199 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2200 if (gp.grantedPermissions.remove(permissionName)) {
2201 gp.grantedPermissions.remove(permissionName);
2202 if (ps.haveGids) {
2203 gp.gids = removeInts(gp.gids, bp.gids);
2204 }
2205 mSettings.writeLPr();
2206 }
2207 }
2208 }
2209
Dianne Hackborn854060af2009-07-09 18:14:31 -07002210 public boolean isProtectedBroadcast(String actionName) {
2211 synchronized (mPackages) {
2212 return mProtectedBroadcasts.contains(actionName);
2213 }
2214 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 public int checkSignatures(String pkg1, String pkg2) {
2217 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002218 final PackageParser.Package p1 = mPackages.get(pkg1);
2219 final PackageParser.Package p2 = mPackages.get(pkg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002220 if (p1 == null || p1.mExtras == null
2221 || p2 == null || p2.mExtras == null) {
2222 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2223 }
Kenny Root447106f2011-03-23 11:00:15 -07002224 return compareSignatures(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002225 }
2226 }
2227
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002228 public int checkUidSignatures(int uid1, int uid2) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002229 // Map to base uids.
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002230 uid1 = UserHandle.getAppId(uid1);
2231 uid2 = UserHandle.getAppId(uid2);
Kenny Root447106f2011-03-23 11:00:15 -07002232 // reader
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002233 synchronized (mPackages) {
2234 Signature[] s1;
2235 Signature[] s2;
Kenny Root447106f2011-03-23 11:00:15 -07002236 Object obj = mSettings.getUserIdLPr(uid1);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002237 if (obj != null) {
2238 if (obj instanceof SharedUserSetting) {
2239 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2240 } else if (obj instanceof PackageSetting) {
2241 s1 = ((PackageSetting)obj).signatures.mSignatures;
2242 } else {
2243 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2244 }
2245 } else {
2246 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2247 }
Kenny Root447106f2011-03-23 11:00:15 -07002248 obj = mSettings.getUserIdLPr(uid2);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002249 if (obj != null) {
2250 if (obj instanceof SharedUserSetting) {
2251 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2252 } else if (obj instanceof PackageSetting) {
2253 s2 = ((PackageSetting)obj).signatures.mSignatures;
2254 } else {
2255 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2256 }
2257 } else {
2258 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2259 }
Kenny Root447106f2011-03-23 11:00:15 -07002260 return compareSignatures(s1, s2);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002261 }
2262 }
2263
Kenny Root447106f2011-03-23 11:00:15 -07002264 static int compareSignatures(Signature[] s1, Signature[] s2) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002265 if (s1 == null) {
2266 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 ? PackageManager.SIGNATURE_NEITHER_SIGNED
2268 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2269 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002270 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2272 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002273 HashSet<Signature> set1 = new HashSet<Signature>();
2274 for (Signature sig : s1) {
2275 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002277 HashSet<Signature> set2 = new HashSet<Signature>();
2278 for (Signature sig : s2) {
2279 set2.add(sig);
2280 }
2281 // Make sure s2 contains all signatures in s1.
2282 if (set1.equals(set2)) {
2283 return PackageManager.SIGNATURE_MATCH;
2284 }
2285 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002286 }
2287
2288 public String[] getPackagesForUid(int uid) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002289 uid = UserHandle.getAppId(uid);
Kenny Root447106f2011-03-23 11:00:15 -07002290 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002292 Object obj = mSettings.getUserIdLPr(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002293 if (obj instanceof SharedUserSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002294 final SharedUserSetting sus = (SharedUserSetting) obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002295 final int N = sus.packages.size();
Kenny Root447106f2011-03-23 11:00:15 -07002296 final String[] res = new String[N];
2297 final Iterator<PackageSetting> it = sus.packages.iterator();
2298 int i = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002299 while (it.hasNext()) {
2300 res[i++] = it.next().name;
2301 }
2302 return res;
2303 } else if (obj instanceof PackageSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002304 final PackageSetting ps = (PackageSetting) obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002305 return new String[] { ps.name };
2306 }
2307 }
2308 return null;
2309 }
2310
2311 public String getNameForUid(int uid) {
Kenny Root447106f2011-03-23 11:00:15 -07002312 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002313 synchronized (mPackages) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002314 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 if (obj instanceof SharedUserSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002316 final SharedUserSetting sus = (SharedUserSetting) obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 return sus.name + ":" + sus.userId;
2318 } else if (obj instanceof PackageSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002319 final PackageSetting ps = (PackageSetting) obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002320 return ps.name;
2321 }
2322 }
2323 return null;
2324 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002326 public int getUidForSharedUser(String sharedUserName) {
2327 if(sharedUserName == null) {
2328 return -1;
2329 }
Kenny Root447106f2011-03-23 11:00:15 -07002330 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002332 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
Amith Yamasani742a6712011-05-04 14:49:28 -07002333 if (suid == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002334 return -1;
2335 }
2336 return suid.userId;
2337 }
2338 }
2339
Amith Yamasani483f3b02012-03-13 16:08:00 -07002340 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002341 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002342 int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002343 if (!sUserManager.exists(userId)) return null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07002344 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2345 return chooseBestActivity(intent, resolvedType, flags, query, userId);
Mihai Predaeae850c2009-05-13 10:13:48 +02002346 }
2347
Mihai Predaeae850c2009-05-13 10:13:48 +02002348 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002349 int flags, List<ResolveInfo> query, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002350 if (query != null) {
2351 final int N = query.size();
2352 if (N == 1) {
2353 return query.get(0);
2354 } else if (N > 1) {
2355 // If there is more than one activity with the same priority,
2356 // then let the user decide between them.
2357 ResolveInfo r0 = query.get(0);
2358 ResolveInfo r1 = query.get(1);
Kenny Root4dfe6ff2011-02-23 17:00:43 -08002359 if (DEBUG_INTENT_MATCHING) {
2360 Log.d(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2361 + r1.activityInfo.name + "=" + r1.priority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002362 }
2363 // If the first activity has a higher priority, or a different
2364 // default, then it is always desireable to pick it.
2365 if (r0.priority != r1.priority
2366 || r0.preferredOrder != r1.preferredOrder
2367 || r0.isDefault != r1.isDefault) {
2368 return query.get(0);
2369 }
2370 // If we have saved a preference for a preferred activity for
2371 // this Intent, use that.
2372 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002373 flags, query, r0.priority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374 if (ri != null) {
2375 return ri;
2376 }
2377 return mResolveInfo;
2378 }
2379 }
2380 return null;
2381 }
2382
2383 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002384 int flags, List<ResolveInfo> query, int priority, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002385 if (!sUserManager.exists(userId)) return null;
Kenny Root447106f2011-03-23 11:00:15 -07002386 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002387 synchronized (mPackages) {
Dianne Hackbornf5b86712011-12-05 17:42:41 -08002388 if (intent.getSelector() != null) {
2389 intent = intent.getSelector();
2390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
2392 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02002393 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002394 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002395 if (prefs != null && prefs.size() > 0) {
2396 // First figure out how good the original match set is.
2397 // We will only allow preferred activities that came
2398 // from the same match quality.
2399 int match = 0;
Kenny Root447106f2011-03-23 11:00:15 -07002400
2401 if (DEBUG_PREFERRED) {
2402 Log.v(TAG, "Figuring out best match...");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 }
Kenny Root447106f2011-03-23 11:00:15 -07002404
2405 final int N = query.size();
2406 for (int j=0; j<N; j++) {
2407 final ResolveInfo ri = query.get(j);
2408 if (DEBUG_PREFERRED) {
2409 Log.v(TAG, "Match for " + ri.activityInfo + ": 0x"
2410 + Integer.toHexString(match));
2411 }
2412 if (ri.match > match) {
2413 match = ri.match;
2414 }
2415 }
2416
2417 if (DEBUG_PREFERRED) {
2418 Log.v(TAG, "Best match: 0x" + Integer.toHexString(match));
2419 }
2420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002421 match &= IntentFilter.MATCH_CATEGORY_MASK;
2422 final int M = prefs.size();
2423 for (int i=0; i<M; i++) {
Kenny Root447106f2011-03-23 11:00:15 -07002424 final PreferredActivity pa = prefs.get(i);
Amith Yamasania3f133a2012-08-09 17:11:28 -07002425 if (pa.mUserId != userId) {
2426 continue;
2427 }
Dianne Hackbornf8b8a3f2011-03-04 00:05:31 -08002428 if (pa.mPref.mMatch != match) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 continue;
2430 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07002431 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 if (DEBUG_PREFERRED) {
2433 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002434 if (ai != null) {
2435 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2436 } else {
2437 Log.v(TAG, " null");
2438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 }
Dianne Hackborn04505102012-02-29 12:34:04 -08002440 if (ai == null) {
2441 // This previously registered preferred activity
2442 // component is no longer known. Most likely an update
2443 // to the app was installed and in the new version this
2444 // component no longer exists. Clean it up by removing
2445 // it from the preferred activities list, and skip it.
2446 Slog.w(TAG, "Removing dangling preferred activity: "
2447 + pa.mPref.mComponent);
2448 mSettings.mPreferredActivities.removeFilter(pa);
2449 continue;
2450 }
2451 for (int j=0; j<N; j++) {
2452 final ResolveInfo ri = query.get(j);
2453 if (!ri.activityInfo.applicationInfo.packageName
2454 .equals(ai.applicationInfo.packageName)) {
2455 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 }
Dianne Hackborn04505102012-02-29 12:34:04 -08002457 if (!ri.activityInfo.name.equals(ai.name)) {
2458 continue;
2459 }
2460
2461 // Okay we found a previously set preferred app.
2462 // If the result set is different from when this
2463 // was created, we need to clear it and re-ask the
2464 // user their preference.
2465 if (!pa.mPref.sameSet(query, priority)) {
2466 Slog.i(TAG, "Result set changed, dropping preferred activity for "
2467 + intent + " type " + resolvedType);
2468 mSettings.mPreferredActivities.removeFilter(pa);
2469 return null;
2470 }
2471
2472 // Yay!
2473 return ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474 }
2475 }
2476 }
2477 }
2478 return null;
2479 }
2480
Amith Yamasani483f3b02012-03-13 16:08:00 -07002481 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 public List<ResolveInfo> queryIntentActivities(Intent intent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002483 String resolvedType, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002484 if (!sUserManager.exists(userId)) return null;
Dianne Hackbornf5b86712011-12-05 17:42:41 -08002485 ComponentName comp = intent.getComponent();
2486 if (comp == null) {
2487 if (intent.getSelector() != null) {
2488 intent = intent.getSelector();
2489 comp = intent.getComponent();
2490 }
2491 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 if (comp != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002494 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
Amith Yamasani483f3b02012-03-13 16:08:00 -07002495 final ActivityInfo ai = getActivityInfo(comp, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002496 if (ai != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002497 final ResolveInfo ri = new ResolveInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 ri.activityInfo = ai;
2499 list.add(ri);
2500 }
2501 return list;
2502 }
2503
Kenny Root447106f2011-03-23 11:00:15 -07002504 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002506 final String pkgName = intent.getPackage();
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002507 if (pkgName == null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002508 return mActivities.queryIntent(intent, resolvedType, flags, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002509 }
Kenny Root447106f2011-03-23 11:00:15 -07002510 final PackageParser.Package pkg = mPackages.get(pkgName);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002511 if (pkg != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002512 return mActivities.queryIntentForPackage(intent, resolvedType, flags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002513 pkg.activities, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002514 }
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002515 return new ArrayList<ResolveInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 }
2517 }
2518
Amith Yamasani483f3b02012-03-13 16:08:00 -07002519 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2521 Intent[] specifics, String[] specificTypes, Intent intent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002522 String resolvedType, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002523 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 final String resultsAction = intent.getAction();
2525
Kenny Root447106f2011-03-23 11:00:15 -07002526 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
Amith Yamasani483f3b02012-03-13 16:08:00 -07002527 | PackageManager.GET_RESOLVED_FILTER, userId);
Kenny Root447106f2011-03-23 11:00:15 -07002528
2529 if (DEBUG_INTENT_MATCHING) {
2530 Log.v(TAG, "Query " + intent + ": " + results);
2531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532
2533 int specificsPos = 0;
2534 int N;
2535
2536 // todo: note that the algorithm used here is O(N^2). This
2537 // isn't a problem in our current environment, but if we start running
2538 // into situations where we have more than 5 or 10 matches then this
2539 // should probably be changed to something smarter...
2540
2541 // First we go through and resolve each of the specific items
2542 // that were supplied, taking care of removing any corresponding
2543 // duplicate items in the generic resolve list.
2544 if (specifics != null) {
2545 for (int i=0; i<specifics.length; i++) {
2546 final Intent sintent = specifics[i];
2547 if (sintent == null) {
2548 continue;
2549 }
2550
Kenny Root447106f2011-03-23 11:00:15 -07002551 if (DEBUG_INTENT_MATCHING) {
2552 Log.v(TAG, "Specific #" + i + ": " + sintent);
2553 }
2554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 String action = sintent.getAction();
2556 if (resultsAction != null && resultsAction.equals(action)) {
2557 // If this action was explicitly requested, then don't
2558 // remove things that have it.
2559 action = null;
2560 }
Kenny Root447106f2011-03-23 11:00:15 -07002561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 ResolveInfo ri = null;
2563 ActivityInfo ai = null;
Kenny Root447106f2011-03-23 11:00:15 -07002564
2565 ComponentName comp = sintent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 if (comp == null) {
2567 ri = resolveIntent(
2568 sintent,
2569 specificTypes != null ? specificTypes[i] : null,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002570 flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 if (ri == null) {
2572 continue;
2573 }
2574 if (ri == mResolveInfo) {
2575 // ACK! Must do something better with this.
2576 }
2577 ai = ri.activityInfo;
2578 comp = new ComponentName(ai.applicationInfo.packageName,
2579 ai.name);
2580 } else {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002581 ai = getActivityInfo(comp, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 if (ai == null) {
2583 continue;
2584 }
2585 }
2586
2587 // Look for any generic query activities that are duplicates
2588 // of this specific one, and remove them from the results.
Kenny Root9718cf52011-02-23 16:45:26 -08002589 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 N = results.size();
2591 int j;
2592 for (j=specificsPos; j<N; j++) {
2593 ResolveInfo sri = results.get(j);
2594 if ((sri.activityInfo.name.equals(comp.getClassName())
2595 && sri.activityInfo.applicationInfo.packageName.equals(
2596 comp.getPackageName()))
2597 || (action != null && sri.filter.matchAction(action))) {
2598 results.remove(j);
Kenny Root9718cf52011-02-23 16:45:26 -08002599 if (DEBUG_INTENT_MATCHING) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 TAG, "Removing duplicate item from " + j
2601 + " due to specific " + specificsPos);
2602 if (ri == null) {
2603 ri = sri;
2604 }
2605 j--;
2606 N--;
2607 }
2608 }
2609
2610 // Add this specific item to its proper place.
2611 if (ri == null) {
2612 ri = new ResolveInfo();
2613 ri.activityInfo = ai;
2614 }
2615 results.add(specificsPos, ri);
2616 ri.specificIndex = i;
2617 specificsPos++;
2618 }
2619 }
2620
2621 // Now we go through the remaining generic results and remove any
2622 // duplicate actions that are found here.
2623 N = results.size();
2624 for (int i=specificsPos; i<N-1; i++) {
2625 final ResolveInfo rii = results.get(i);
2626 if (rii.filter == null) {
2627 continue;
2628 }
2629
2630 // Iterate over all of the actions of this result's intent
2631 // filter... typically this should be just one.
2632 final Iterator<String> it = rii.filter.actionsIterator();
2633 if (it == null) {
2634 continue;
2635 }
2636 while (it.hasNext()) {
2637 final String action = it.next();
2638 if (resultsAction != null && resultsAction.equals(action)) {
2639 // If this action was explicitly requested, then don't
2640 // remove things that have it.
2641 continue;
2642 }
2643 for (int j=i+1; j<N; j++) {
2644 final ResolveInfo rij = results.get(j);
2645 if (rij.filter != null && rij.filter.hasAction(action)) {
2646 results.remove(j);
Kenny Root9718cf52011-02-23 16:45:26 -08002647 if (DEBUG_INTENT_MATCHING) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002648 TAG, "Removing duplicate item from " + j
2649 + " due to action " + action + " at " + i);
2650 j--;
2651 N--;
2652 }
2653 }
2654 }
2655
2656 // If the caller didn't request filter information, drop it now
2657 // so we don't have to marshall/unmarshall it.
2658 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2659 rii.filter = null;
2660 }
2661 }
2662
2663 // Filter out the caller activity if so requested.
2664 if (caller != null) {
2665 N = results.size();
2666 for (int i=0; i<N; i++) {
2667 ActivityInfo ainfo = results.get(i).activityInfo;
2668 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2669 && caller.getClassName().equals(ainfo.name)) {
2670 results.remove(i);
2671 break;
2672 }
2673 }
2674 }
2675
2676 // If the caller didn't request filter information,
2677 // drop them now so we don't have to
2678 // marshall/unmarshall it.
2679 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2680 N = results.size();
2681 for (int i=0; i<N; i++) {
2682 results.get(i).filter = null;
2683 }
2684 }
2685
Kenny Root9718cf52011-02-23 16:45:26 -08002686 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687 return results;
2688 }
2689
Amith Yamasani483f3b02012-03-13 16:08:00 -07002690 @Override
2691 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
2692 int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002693 if (!sUserManager.exists(userId)) return null;
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002694 ComponentName comp = intent.getComponent();
Dianne Hackbornf5b86712011-12-05 17:42:41 -08002695 if (comp == null) {
2696 if (intent.getSelector() != null) {
2697 intent = intent.getSelector();
2698 comp = intent.getComponent();
2699 }
2700 }
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002701 if (comp != null) {
2702 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
Amith Yamasani483f3b02012-03-13 16:08:00 -07002703 ActivityInfo ai = getReceiverInfo(comp, flags, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002704 if (ai != null) {
2705 ResolveInfo ri = new ResolveInfo();
2706 ri.activityInfo = ai;
2707 list.add(ri);
2708 }
2709 return list;
2710 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002711
Kenny Root447106f2011-03-23 11:00:15 -07002712 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 synchronized (mPackages) {
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002714 String pkgName = intent.getPackage();
2715 if (pkgName == null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002716 return mReceivers.queryIntent(intent, resolvedType, flags, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002717 }
Kenny Root447106f2011-03-23 11:00:15 -07002718 final PackageParser.Package pkg = mPackages.get(pkgName);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002719 if (pkg != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002720 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
2721 userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002722 }
2723 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 }
2725 }
2726
Amith Yamasani483f3b02012-03-13 16:08:00 -07002727 @Override
2728 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
2729 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
Amith Yamasani13593602012-03-22 16:16:17 -07002730 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 if (query != null) {
2732 if (query.size() >= 1) {
2733 // If there is more than one service with the same priority,
2734 // just arbitrarily pick the first one.
2735 return query.get(0);
2736 }
2737 }
2738 return null;
2739 }
2740
Amith Yamasani483f3b02012-03-13 16:08:00 -07002741 @Override
2742 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
2743 int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002744 if (!sUserManager.exists(userId)) return null;
Dianne Hackbornf5b86712011-12-05 17:42:41 -08002745 ComponentName comp = intent.getComponent();
2746 if (comp == null) {
2747 if (intent.getSelector() != null) {
2748 intent = intent.getSelector();
2749 comp = intent.getComponent();
2750 }
2751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 if (comp != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002753 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
Amith Yamasani483f3b02012-03-13 16:08:00 -07002754 final ServiceInfo si = getServiceInfo(comp, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 if (si != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002756 final ResolveInfo ri = new ResolveInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002757 ri.serviceInfo = si;
2758 list.add(ri);
2759 }
2760 return list;
2761 }
2762
Kenny Root447106f2011-03-23 11:00:15 -07002763 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764 synchronized (mPackages) {
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002765 String pkgName = intent.getPackage();
2766 if (pkgName == null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002767 return mServices.queryIntent(intent, resolvedType, flags, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002768 }
Kenny Root447106f2011-03-23 11:00:15 -07002769 final PackageParser.Package pkg = mPackages.get(pkgName);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002770 if (pkg != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002771 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
2772 userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002773 }
2774 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 }
2776 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002777
Kenny Root0e2c0f32011-04-15 17:50:10 -07002778 private static final int getContinuationPoint(final String[] keys, final String key) {
2779 final int index;
2780 if (key == null) {
2781 index = 0;
2782 } else {
2783 final int insertPoint = Arrays.binarySearch(keys, key);
2784 if (insertPoint < 0) {
2785 index = -insertPoint;
2786 } else {
2787 index = insertPoint + 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002788 }
2789 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002790 return index;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 }
2792
Kenny Root0e2c0f32011-04-15 17:50:10 -07002793 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, String lastRead) {
2794 final ParceledListSlice<PackageInfo> list = new ParceledListSlice<PackageInfo>();
2795 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
2796 final String[] keys;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002797 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798
Kenny Root447106f2011-03-23 11:00:15 -07002799 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800 synchronized (mPackages) {
Kenny Root0e2c0f32011-04-15 17:50:10 -07002801 if (listUninstalled) {
2802 keys = mSettings.mPackages.keySet().toArray(new String[mSettings.mPackages.size()]);
2803 } else {
2804 keys = mPackages.keySet().toArray(new String[mPackages.size()]);
2805 }
2806
2807 Arrays.sort(keys);
2808 int i = getContinuationPoint(keys, lastRead);
2809 final int N = keys.length;
2810
2811 while (i < N) {
2812 final String packageName = keys[i++];
2813
2814 PackageInfo pi = null;
2815 if (listUninstalled) {
2816 final PackageSetting ps = mSettings.mPackages.get(packageName);
2817 if (ps != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002818 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002820 } else {
2821 final PackageParser.Package p = mPackages.get(packageName);
2822 if (p != null) {
Amith Yamasani13593602012-03-22 16:16:17 -07002823 pi = generatePackageInfo(p, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 }
2825 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002826
Henrik Engström9771a312012-02-21 09:05:17 +01002827 if (pi != null && list.append(pi)) {
Kenny Root0e2c0f32011-04-15 17:50:10 -07002828 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 }
2830 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002831
2832 if (i == N) {
2833 list.setLastSlice(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002836
2837 return list;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 }
2839
Amith Yamasani483f3b02012-03-13 16:08:00 -07002840 @Override
Kenny Root0e2c0f32011-04-15 17:50:10 -07002841 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002842 String lastRead, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002843 if (!sUserManager.exists(userId)) return null;
Kenny Root0e2c0f32011-04-15 17:50:10 -07002844 final ParceledListSlice<ApplicationInfo> list = new ParceledListSlice<ApplicationInfo>();
2845 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
2846 final String[] keys;
2847
Kenny Root447106f2011-03-23 11:00:15 -07002848 // writer
Kenny Root0e2c0f32011-04-15 17:50:10 -07002849 synchronized (mPackages) {
2850 if (listUninstalled) {
2851 keys = mSettings.mPackages.keySet().toArray(new String[mSettings.mPackages.size()]);
2852 } else {
2853 keys = mPackages.keySet().toArray(new String[mPackages.size()]);
2854 }
2855
2856 Arrays.sort(keys);
2857 int i = getContinuationPoint(keys, lastRead);
2858 final int N = keys.length;
2859
2860 while (i < N) {
2861 final String packageName = keys[i++];
2862
2863 ApplicationInfo ai = null;
Amith Yamasani13593602012-03-22 16:16:17 -07002864 final PackageSetting ps = mSettings.mPackages.get(packageName);
Kenny Root0e2c0f32011-04-15 17:50:10 -07002865 if (listUninstalled) {
Kenny Root0e2c0f32011-04-15 17:50:10 -07002866 if (ps != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002867 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
Kenny Root0e2c0f32011-04-15 17:50:10 -07002868 }
2869 } else {
2870 final PackageParser.Package p = mPackages.get(packageName);
Amith Yamasani13593602012-03-22 16:16:17 -07002871 if (p != null && ps != null) {
2872 ai = PackageParser.generateApplicationInfo(p, flags, ps.getStopped(userId),
2873 ps.getEnabled(userId), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 }
2875 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002876
Henrik Engström9771a312012-02-21 09:05:17 +01002877 if (ai != null && list.append(ai)) {
Kenny Root0e2c0f32011-04-15 17:50:10 -07002878 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 }
2880 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002881
2882 if (i == N) {
2883 list.setLastSlice(true);
2884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002886
2887 return list;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 }
2889
2890 public List<ApplicationInfo> getPersistentApplications(int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07002891 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892
Kenny Root447106f2011-03-23 11:00:15 -07002893 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002895 final Iterator<PackageParser.Package> i = mPackages.values().iterator();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002896 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 while (i.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07002898 final PackageParser.Package p = i.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002899 if (p.applicationInfo != null
2900 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002901 && (!mSafeMode || isSystemApp(p))) {
Amith Yamasani13593602012-03-22 16:16:17 -07002902 PackageSetting ps = mSettings.mPackages.get(p.packageName);
2903 finalList.add(PackageParser.generateApplicationInfo(p, flags,
2904 ps != null ? ps.getStopped(userId) : false,
2905 ps != null ? ps.getEnabled(userId) : COMPONENT_ENABLED_STATE_DEFAULT,
2906 userId));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 }
2908 }
2909 }
2910
2911 return finalList;
2912 }
2913
Amith Yamasani483f3b02012-03-13 16:08:00 -07002914 @Override
2915 public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002916 if (!sUserManager.exists(userId)) return null;
Kenny Root447106f2011-03-23 11:00:15 -07002917 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 synchronized (mPackages) {
2919 final PackageParser.Provider provider = mProviders.get(name);
Amith Yamasani13593602012-03-22 16:16:17 -07002920 PackageSetting ps = provider != null
2921 ? mSettings.mPackages.get(provider.owner.packageName)
2922 : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 return provider != null
Amith Yamasani483f3b02012-03-13 16:08:00 -07002924 && mSettings.isEnabledLPr(provider.info, flags, userId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 && (!mSafeMode || (provider.info.applicationInfo.flags
2926 &ApplicationInfo.FLAG_SYSTEM) != 0)
Amith Yamasani13593602012-03-22 16:16:17 -07002927 ? PackageParser.generateProviderInfo(provider, flags,
2928 ps != null ? ps.getStopped(userId) : false,
2929 ps != null ? ps.getEnabled(userId) : COMPONENT_ENABLED_STATE_DEFAULT,
2930 userId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 : null;
2932 }
2933 }
2934
Fred Quintana718d8a22009-04-29 17:53:20 -07002935 /**
2936 * @deprecated
2937 */
Kenny Root60f7ad82011-03-22 12:49:06 -07002938 @Deprecated
2939 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
Kenny Root447106f2011-03-23 11:00:15 -07002940 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002941 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002942 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProviders.entrySet()
2943 .iterator();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002944 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 while (i.hasNext()) {
2946 Map.Entry<String, PackageParser.Provider> entry = i.next();
2947 PackageParser.Provider p = entry.getValue();
Amith Yamasani13593602012-03-22 16:16:17 -07002948 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002949
2950 if (p.syncable
2951 && (!mSafeMode || (p.info.applicationInfo.flags
2952 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2953 outNames.add(entry.getKey());
Amith Yamasani13593602012-03-22 16:16:17 -07002954 outInfo.add(PackageParser.generateProviderInfo(p, 0,
2955 ps != null ? ps.getStopped(userId) : false,
2956 ps != null ? ps.getEnabled(userId) : COMPONENT_ENABLED_STATE_DEFAULT,
2957 userId));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 }
2959 }
2960 }
2961 }
2962
2963 public List<ProviderInfo> queryContentProviders(String processName,
2964 int uid, int flags) {
2965 ArrayList<ProviderInfo> finalList = null;
2966
Kenny Root447106f2011-03-23 11:00:15 -07002967 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002968 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002969 final Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
Amith Yamasani483f3b02012-03-13 16:08:00 -07002970 final int userId = processName != null ?
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002971 UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002972 while (i.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07002973 final PackageParser.Provider p = i.next();
Amith Yamasani13593602012-03-22 16:16:17 -07002974 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002975 if (p.info.authority != null
Kenny Root447106f2011-03-23 11:00:15 -07002976 && (processName == null
2977 || (p.info.processName.equals(processName)
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002978 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
Amith Yamasani483f3b02012-03-13 16:08:00 -07002979 && mSettings.isEnabledLPr(p.info, flags, userId)
Kenny Root447106f2011-03-23 11:00:15 -07002980 && (!mSafeMode
2981 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982 if (finalList == null) {
2983 finalList = new ArrayList<ProviderInfo>(3);
2984 }
Amith Yamasani13593602012-03-22 16:16:17 -07002985 finalList.add(PackageParser.generateProviderInfo(p, flags,
2986 ps != null ? ps.getStopped(userId) : false,
2987 ps != null ? ps.getEnabled(userId) : COMPONENT_ENABLED_STATE_DEFAULT,
2988 userId));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002989 }
2990 }
2991 }
2992
2993 if (finalList != null) {
2994 Collections.sort(finalList, mProviderInitOrderSorter);
2995 }
2996
2997 return finalList;
2998 }
2999
3000 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3001 int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07003002 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003 synchronized (mPackages) {
3004 final PackageParser.Instrumentation i = mInstrumentation.get(name);
3005 return PackageParser.generateInstrumentationInfo(i, flags);
3006 }
3007 }
3008
3009 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3010 int flags) {
3011 ArrayList<InstrumentationInfo> finalList =
3012 new ArrayList<InstrumentationInfo>();
3013
Kenny Root447106f2011-03-23 11:00:15 -07003014 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003015 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07003016 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 while (i.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07003018 final PackageParser.Instrumentation p = i.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003019 if (targetPackage == null
3020 || targetPackage.equals(p.info.targetPackage)) {
3021 finalList.add(PackageParser.generateInstrumentationInfo(p,
3022 flags));
3023 }
3024 }
3025 }
3026
3027 return finalList;
3028 }
3029
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003030 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 String[] files = dir.list();
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07003032 if (files == null) {
3033 Log.d(TAG, "No files in app dir " + dir);
3034 return;
3035 }
3036
Kenny Root4dfe6ff2011-02-23 17:00:43 -08003037 if (DEBUG_PACKAGE_SCANNING) {
Joe Onorato431bb222010-10-18 19:13:23 -04003038 Log.d(TAG, "Scanning app dir " + dir);
3039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040
3041 int i;
3042 for (i=0; i<files.length; i++) {
3043 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003044 if (!isPackageFilename(files[i])) {
3045 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08003046 continue;
3047 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003048 PackageParser.Package pkg = scanPackageLI(file,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003049 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003050 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08003051 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
3052 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003053 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003054 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003055 file.delete();
3056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 }
3058 }
3059
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003060 private static File getSettingsProblemFile() {
3061 File dataDir = Environment.getDataDirectory();
3062 File systemDir = new File(dataDir, "system");
3063 File fname = new File(systemDir, "uiderrors.txt");
3064 return fname;
3065 }
3066
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003067 static void reportSettingsProblem(int priority, String msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003068 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003069 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 FileOutputStream out = new FileOutputStream(fname, true);
3071 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003072 SimpleDateFormat formatter = new SimpleDateFormat();
3073 String dateString = formatter.format(new Date(System.currentTimeMillis()));
3074 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075 pw.close();
3076 FileUtils.setPermissions(
3077 fname.toString(),
3078 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
3079 -1, -1);
3080 } catch (java.io.IOException e) {
3081 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003082 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003083 }
3084
3085 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
3086 PackageParser.Package pkg, File srcFile, int parseFlags) {
3087 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07003088 if (ps != null
3089 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07003090 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07003091 if (ps.signatures.mSignatures != null
3092 && ps.signatures.mSignatures.length != 0) {
3093 // Optimization: reuse the existing cached certificates
3094 // if the package appears to be unchanged.
3095 pkg.mSignatures = ps.signatures.mSignatures;
3096 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 }
Jeff Browne7600722010-04-07 18:28:23 -07003098
3099 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003100 } else {
Jeff Browne7600722010-04-07 18:28:23 -07003101 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
3102 }
3103
3104 if (!pp.collectCertificates(pkg, parseFlags)) {
3105 mLastScanError = pp.getParseError();
3106 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003107 }
3108 }
3109 return true;
3110 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003112 /*
3113 * Scan a package and return the newly parsed package.
3114 * Returns null in case of errors and the error code is stored in mLastScanError
3115 */
3116 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003117 int parseFlags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003118 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003119 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003120 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003121 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003122 pp.setSeparateProcesses(mSeparateProcesses);
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07003123 pp.setOnlyCoreApps(mOnlyCore);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003124 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003125 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 if (pkg == null) {
3127 mLastScanError = pp.getParseError();
3128 return null;
3129 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003130 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003131 PackageSetting updatedPkg;
Kenny Root447106f2011-03-23 11:00:15 -07003132 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003133 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003134 // Look to see if we already know about this package.
3135 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08003136 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003137 // This package has been renamed to its original name. Let's
3138 // use that.
Kenny Root447106f2011-03-23 11:00:15 -07003139 ps = mSettings.peekPackageLPr(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003140 }
3141 // If there was no original package, see one for the real package name.
3142 if (ps == null) {
Kenny Root447106f2011-03-23 11:00:15 -07003143 ps = mSettings.peekPackageLPr(pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003144 }
3145 // Check to see if this package could be hiding/updating a system
3146 // package. Must look for it either under the original or real
3147 // package name depending on our state.
Kenny Rootc52d6fd2012-05-07 23:04:52 -07003148 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003149 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003150 // First check if this is a system package that may involve an update
3151 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07003152 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003153 // The path has changed from what was last scanned... check the
3154 // version of the new path against what we have stored to determine
3155 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003156 if (pkg.mVersionCode < ps.versionCode) {
3157 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003158 // Ignore entry. Skip it.
3159 Log.i(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborncef65ee2010-09-30 18:27:22 -07003160 + " ignored: updated version " + ps.versionCode
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003161 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003162 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3163 return null;
3164 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003165 // The current app on the system partion is better than
3166 // what we have updated to on the data partition; switch
3167 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003168 // At this point, its safely assumed that package installation for
3169 // apps in system partition will go through. If not there won't be a working
3170 // version of the app
Kenny Root447106f2011-03-23 11:00:15 -07003171 // writer
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003172 synchronized (mPackages) {
3173 // Just remove the loaded entries from package lists.
3174 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003175 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003176 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003177 + "reverting from " + ps.codePathString
3178 + ": new version " + pkg.mVersionCode
3179 + " better than installed " + ps.versionCode);
Kenny Root88670d82012-05-09 15:47:35 -07003180
3181 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3182 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
Kenny Root208d3412012-05-07 19:42:35 -07003183 synchronized (mInstaller) {
3184 args.cleanUpResourcesLI();
3185 }
3186 synchronized (mPackages) {
3187 mSettings.enableSystemPackageLPw(ps.name);
3188 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 }
3191 }
Kenny Root208d3412012-05-07 19:42:35 -07003192
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003193 if (updatedPkg != null) {
Kenny Root208d3412012-05-07 19:42:35 -07003194 // An updated system app will not have the PARSE_IS_SYSTEM flag set
3195 // initially
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003196 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
3197 }
3198 // Verify certificates against what was last scanned
3199 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003200 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003201 return null;
3202 }
Kenny Root208d3412012-05-07 19:42:35 -07003203
3204 /*
3205 * A new system app appeared, but we already had a non-system one of the
3206 * same name installed earlier.
3207 */
3208 boolean shouldHideSystemApp = false;
3209 if (updatedPkg == null && ps != null
3210 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
3211 /*
3212 * Check to make sure the signatures match first. If they don't,
3213 * wipe the installed application and its data.
3214 */
3215 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
3216 != PackageManager.SIGNATURE_MATCH) {
3217 deletePackageLI(pkg.packageName, true, 0, null, false);
3218 ps = null;
3219 } else {
3220 /*
3221 * If the newly-added system app is an older version than the
3222 * already installed version, hide it. It will be scanned later
3223 * and re-added like an update.
3224 */
3225 if (pkg.mVersionCode < ps.versionCode) {
3226 shouldHideSystemApp = true;
3227 } else {
3228 /*
3229 * The newly found system app is a newer version that the
3230 * one previously installed. Simply remove the
3231 * already-installed application and replace it with our own
3232 * while keeping the application data.
3233 */
3234 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
3235 + ps.codePathString + ": new version " + pkg.mVersionCode
3236 + " better than installed " + ps.versionCode);
Kenny Root88670d82012-05-09 15:47:35 -07003237 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3238 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
Kenny Root208d3412012-05-07 19:42:35 -07003239 synchronized (mInstaller) {
3240 args.cleanUpResourcesLI();
3241 }
3242 }
3243 }
3244 }
3245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 // The apk is forward locked (not public) if its code and resources
3247 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003248 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003250 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07003251 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003252
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003253 String codePath = null;
3254 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003255 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
3256 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003257 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003258 } else {
3259 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003260 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003261 }
3262 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003263 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003264 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003265 codePath = pkg.mScanPath;
3266 // Set application objects path explicitly.
3267 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003268 // Note that we invoke the following method only if we are about to unpack an application
Kenny Root208d3412012-05-07 19:42:35 -07003269 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
3270 | SCAN_UPDATE_SIGNATURE, currentTime);
3271
3272 /*
3273 * If the system app should be overridden by a previously installed
3274 * data, hide the system app now and let the /data/app scan pick it up
3275 * again.
3276 */
3277 if (shouldHideSystemApp) {
3278 synchronized (mPackages) {
3279 /*
3280 * We have to grant systems permissions before we hide, because
3281 * grantPermissions will assume the package update is trying to
3282 * expand its permissions.
3283 */
3284 grantPermissionsLPw(pkg, true);
3285 mSettings.disableSystemPackageLPw(pkg.packageName);
3286 }
3287 }
3288
3289 return scannedPkg;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003290 }
3291
Kenny Root85387d72010-08-26 10:13:11 -07003292 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
3293 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003294 pkg.mPath = pkg.mScanPath = destCodePath;
3295 pkg.applicationInfo.sourceDir = destCodePath;
3296 pkg.applicationInfo.publicSourceDir = destResPath;
3297 }
3298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 private static String fixProcessName(String defProcessName,
3300 String processName, int uid) {
3301 if (processName == null) {
3302 return defProcessName;
3303 }
3304 return processName;
3305 }
3306
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003307 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003308 PackageParser.Package pkg) {
3309 if (pkgSetting.signatures.mSignatures != null) {
3310 // Already existing package. Make sure signatures match
Kenny Root447106f2011-03-23 11:00:15 -07003311 if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003312 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003313 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003314 + " signatures do not match the previously installed version; ignoring!");
3315 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 return false;
3317 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003318 }
3319 // Check for shared user signatures
3320 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
Kenny Root447106f2011-03-23 11:00:15 -07003321 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003322 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3323 Slog.e(TAG, "Package " + pkg.packageName
3324 + " has no signatures that match those in shared user "
3325 + pkgSetting.sharedUser.name + "; ignoring!");
3326 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
3327 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 }
3330 return true;
3331 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003332
Kenny Root461ff1f2011-08-09 09:43:03 -07003333 /**
3334 * Enforces that only the system UID or root's UID can call a method exposed
3335 * via Binder.
3336 *
3337 * @param message used as message if SecurityException is thrown
3338 * @throws SecurityException if the caller is not system or root
3339 */
3340 private static final void enforceSystemOrRoot(String message) {
3341 final int uid = Binder.getCallingUid();
3342 if (uid != Process.SYSTEM_UID && uid != 0) {
3343 throw new SecurityException(message);
3344 }
3345 }
3346
Dianne Hackborn661cd522011-08-22 00:26:20 -07003347 public void performBootDexOpt() {
3348 ArrayList<PackageParser.Package> pkgs = null;
3349 synchronized (mPackages) {
3350 if (mDeferredDexOpt.size() > 0) {
3351 pkgs = new ArrayList<PackageParser.Package>(mDeferredDexOpt);
3352 mDeferredDexOpt.clear();
3353 }
3354 }
3355 if (pkgs != null) {
3356 for (int i=0; i<pkgs.size(); i++) {
Dianne Hackborn58f42a52011-10-10 13:46:34 -07003357 if (!isFirstBoot()) {
3358 try {
3359 ActivityManagerNative.getDefault().showBootMessage(
3360 mContext.getResources().getString(
3361 com.android.internal.R.string.android_upgrading_apk,
3362 i+1, pkgs.size()), true);
3363 } catch (RemoteException e) {
3364 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07003365 }
3366 PackageParser.Package p = pkgs.get(i);
3367 synchronized (mInstallLock) {
3368 if (!p.mDidDexOpt) {
3369 performDexOptLI(p, false, false);
3370 }
3371 }
3372 }
3373 }
3374 }
3375
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003376 public boolean performDexOpt(String packageName) {
Kenny Root461ff1f2011-08-09 09:43:03 -07003377 enforceSystemOrRoot("Only the system can request dexopt be performed");
3378
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003379 if (!mNoDexOpt) {
3380 return false;
3381 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003382
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003383 PackageParser.Package p;
3384 synchronized (mPackages) {
3385 p = mPackages.get(packageName);
3386 if (p == null || p.mDidDexOpt) {
3387 return false;
3388 }
3389 }
3390 synchronized (mInstallLock) {
Dianne Hackborn661cd522011-08-22 00:26:20 -07003391 return performDexOptLI(p, false, false) == DEX_OPT_PERFORMED;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003392 }
3393 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003394
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003395 static final int DEX_OPT_SKIPPED = 0;
3396 static final int DEX_OPT_PERFORMED = 1;
Dianne Hackborn661cd522011-08-22 00:26:20 -07003397 static final int DEX_OPT_DEFERRED = 2;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003398 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003399
Dianne Hackborn661cd522011-08-22 00:26:20 -07003400 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003401 boolean performed = false;
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003402 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003403 String path = pkg.mScanPath;
3404 int ret = 0;
3405 try {
3406 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Dianne Hackborn661cd522011-08-22 00:26:20 -07003407 if (!forceDex && defer) {
3408 mDeferredDexOpt.add(pkg);
3409 return DEX_OPT_DEFERRED;
3410 } else {
3411 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
3412 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
3413 !isForwardLocked(pkg));
3414 pkg.mDidDexOpt = true;
3415 performed = true;
3416 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003417 }
3418 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003419 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003420 ret = -1;
3421 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07003422 Slog.w(TAG, "IOException reading apk: " + path, e);
3423 ret = -1;
3424 } catch (dalvik.system.StaleDexCacheError e) {
3425 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
3426 ret = -1;
3427 } catch (Exception e) {
3428 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003429 ret = -1;
3430 }
3431 if (ret < 0) {
3432 //error from installer
3433 return DEX_OPT_FAILED;
3434 }
3435 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003436
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003437 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
3438 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08003439
Kenny Root447106f2011-03-23 11:00:15 -07003440 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003441 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003442 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003443 + " to " + newPkg.packageName
3444 + ": old package not in system partition");
3445 return false;
3446 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003447 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003448 + " to " + newPkg.packageName
3449 + ": old package still exists");
3450 return false;
3451 }
3452 return true;
3453 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003454
Amith Yamasani0b285492011-04-14 17:35:23 -07003455 File getDataPathForUser(int userId) {
3456 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003457 }
Amith Yamasani0b285492011-04-14 17:35:23 -07003458
3459 private File getDataPathForPackage(String packageName, int userId) {
Kenny Root9c8625e2011-07-25 09:42:22 -07003460 /*
3461 * Until we fully support multiple users, return the directory we
3462 * previously would have. The PackageManagerTests will need to be
3463 * revised when this is changed back..
3464 */
3465 if (userId == 0) {
3466 return new File(mAppDataDir, packageName);
3467 } else {
3468 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
Amith Yamasani0f3f29b2011-05-09 14:17:14 -07003469 + File.separator + packageName);
Kenny Root9c8625e2011-07-25 09:42:22 -07003470 }
Amith Yamasani0b285492011-04-14 17:35:23 -07003471 }
3472
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003473 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003474 int parseFlags, int scanMode, long currentTime) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003475 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08003476 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
3477 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003478 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003479 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003480 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
3481 return null;
3482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003483 mScanningPath = scanFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3486 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
3487 }
3488
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003489 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003490 synchronized (mPackages) {
3491 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003492 Slog.w(TAG, "*************************************************");
3493 Slog.w(TAG, "Core android package being redefined. Skipping.");
3494 Slog.w(TAG, " file=" + mScanningPath);
3495 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003496 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3497 return null;
3498 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500 // Set up information for our fall-back user intent resolution
3501 // activity.
3502 mPlatformPackage = pkg;
3503 pkg.mVersionCode = mSdkVersion;
3504 mAndroidApplication = pkg.applicationInfo;
3505 mResolveActivity.applicationInfo = mAndroidApplication;
3506 mResolveActivity.name = ResolverActivity.class.getName();
3507 mResolveActivity.packageName = mAndroidApplication.packageName;
3508 mResolveActivity.processName = mAndroidApplication.processName;
3509 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
3510 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
Joe Onorato646f46e2010-11-08 15:08:56 -08003511 mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003512 mResolveActivity.exported = true;
3513 mResolveActivity.enabled = true;
3514 mResolveInfo.activityInfo = mResolveActivity;
3515 mResolveInfo.priority = 0;
3516 mResolveInfo.preferredOrder = 0;
3517 mResolveInfo.match = 0;
3518 mResolveComponentName = new ComponentName(
3519 mAndroidApplication.packageName, mResolveActivity.name);
3520 }
3521 }
3522
Kenny Root4dfe6ff2011-02-23 17:00:43 -08003523 if (DEBUG_PACKAGE_SCANNING) {
3524 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
3525 Log.d(TAG, "Scanning package " + pkg.packageName);
3526 }
3527
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003528 if (mPackages.containsKey(pkg.packageName)
3529 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003530 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 + " already installed. Skipping duplicate.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3533 return null;
3534 }
3535
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003536 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003537 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
3538 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003540 SharedUserSetting suid = null;
3541 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003542
Kenny Root502e9a42011-01-10 13:48:15 -08003543 if (!isSystemApp(pkg)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003544 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08003545 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003546 pkg.mRealPackage = null;
3547 pkg.mAdoptPermissions = null;
3548 }
Kenny Root502e9a42011-01-10 13:48:15 -08003549
Kenny Root447106f2011-03-23 11:00:15 -07003550 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551 synchronized (mPackages) {
3552 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07003553 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
3554 if (mTmpSharedLibraries == null ||
3555 mTmpSharedLibraries.length < mSharedLibraries.size()) {
3556 mTmpSharedLibraries = new String[mSharedLibraries.size()];
3557 }
3558 int num = 0;
3559 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
3560 for (int i=0; i<N; i++) {
Kenny Root447106f2011-03-23 11:00:15 -07003561 final String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003562 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003563 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003564 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07003565 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
3567 return null;
3568 }
Dianne Hackborn49237342009-08-27 20:08:01 -07003569 mTmpSharedLibraries[num] = file;
3570 num++;
3571 }
3572 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
3573 for (int i=0; i<N; i++) {
Kenny Root447106f2011-03-23 11:00:15 -07003574 final String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
Dianne Hackborn49237342009-08-27 20:08:01 -07003575 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003576 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07003577 + " desires unavailable shared library "
3578 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
3579 } else {
3580 mTmpSharedLibraries[num] = file;
3581 num++;
3582 }
3583 }
3584 if (num > 0) {
3585 pkg.usesLibraryFiles = new String[num];
3586 System.arraycopy(mTmpSharedLibraries, 0,
3587 pkg.usesLibraryFiles, 0, num);
3588 }
Kenny Root1683afa2011-01-07 14:27:50 -08003589 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003591 if (pkg.mSharedUserId != null) {
Kenny Root447106f2011-03-23 11:00:15 -07003592 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003593 pkg.applicationInfo.flags, true);
3594 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003595 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 + " for shared user failed");
3597 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3598 return null;
3599 }
Kenny Root4dfe6ff2011-02-23 17:00:43 -08003600 if (DEBUG_PACKAGE_SCANNING) {
3601 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
3602 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
3603 + "): packages=" + suid.packages);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003604 }
3605 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003606
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003607 // Check if we are renaming from an original package name.
3608 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003609 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08003610 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003611 // This package may need to be renamed to a previously
3612 // installed name. Let's check on that...
Kenny Root447106f2011-03-23 11:00:15 -07003613 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08003614 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003615 // This package had originally been installed as the
3616 // original name, and we have already taken care of
3617 // transitioning to the new one. Just update the new
3618 // one to continue using the old name.
3619 realName = pkg.mRealPackage;
3620 if (!pkg.packageName.equals(renamed)) {
3621 // Callers into this function may have already taken
3622 // care of renaming the package; only do it here if
3623 // it is not already done.
3624 pkg.setPackageName(renamed);
3625 }
3626
Dianne Hackbornc1552392010-03-03 16:19:01 -08003627 } else {
3628 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
Kenny Root447106f2011-03-23 11:00:15 -07003629 if ((origPackage = mSettings.peekPackageLPr(
Dianne Hackbornc1552392010-03-03 16:19:01 -08003630 pkg.mOriginalPackages.get(i))) != null) {
3631 // We do have the package already installed under its
3632 // original name... should we use it?
Kenny Root447106f2011-03-23 11:00:15 -07003633 if (!verifyPackageUpdateLPr(origPackage, pkg)) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08003634 // New package is not compatible with original.
3635 origPackage = null;
3636 continue;
3637 } else if (origPackage.sharedUser != null) {
3638 // Make sure uid is compatible between packages.
3639 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003640 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003641 + " to " + pkg.packageName + ": old uid "
3642 + origPackage.sharedUser.name
3643 + " differs from " + pkg.mSharedUserId);
3644 origPackage = null;
3645 continue;
3646 }
3647 } else {
3648 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3649 + pkg.packageName + " to old name " + origPackage.name);
3650 }
3651 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003652 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003653 }
3654 }
3655 }
3656
3657 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003658 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003659 + " was transferred to another, but its .apk remains");
3660 }
3661
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003662 // Just create the setting, don't add it yet. For already existing packages
3663 // the PkgSetting exists already and doesn't have to be created.
Kenny Root447106f2011-03-23 11:00:15 -07003664 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07003665 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3666 pkg.applicationInfo.flags, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003668 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3670 return null;
3671 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003672
3673 if (pkgSetting.origPackage != null) {
3674 // If we are first transitioning from an original package,
3675 // fix up the new package's name now. We need to do this after
3676 // looking up the package under its new name, so getPackageLP
3677 // can take care of fiddling things correctly.
3678 pkg.setPackageName(origPackage.name);
3679
3680 // File a report about this.
3681 String msg = "New package " + pkgSetting.realName
3682 + " renamed to replace old package " + pkgSetting.name;
3683 reportSettingsProblem(Log.WARN, msg);
3684
3685 // Make a note of it.
3686 mTransferedPackages.add(origPackage.name);
3687
3688 // No longer need to retain this.
3689 pkgSetting.origPackage = null;
3690 }
3691
3692 if (realName != null) {
3693 // Make a note of it.
3694 mTransferedPackages.add(pkg.packageName);
3695 }
3696
Kenny Rootc52d6fd2012-05-07 23:04:52 -07003697 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003698 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3699 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003700
Amith Yamasani13593602012-03-22 16:16:17 -07003701 pkg.applicationInfo.uid = pkgSetting.appId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003702 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003703
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003704 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003705 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003706 return null;
3707 }
3708 // The signature has changed, but this package is in the system
3709 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003710 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003711 // However... if this package is part of a shared user, but it
3712 // doesn't match the signature of the shared user, let's fail.
3713 // What this means is that you can't change the signatures
3714 // associated with an overall shared user, which doesn't seem all
3715 // that unreasonable.
3716 if (pkgSetting.sharedUser != null) {
Kenny Root447106f2011-03-23 11:00:15 -07003717 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003718 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3719 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3721 return null;
3722 }
3723 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003724 // File a report about this.
3725 String msg = "System package " + pkg.packageName
3726 + " signature changed; retaining data.";
3727 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003728 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003729
The Android Open Source Project10592532009-03-18 17:39:46 -07003730 // Verify that this new package doesn't have any content providers
3731 // that conflict with existing packages. Only do this if the
3732 // package isn't already installed, since we don't want to break
3733 // things that are installed.
3734 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
Kenny Root62cc6902011-02-23 16:49:21 -08003735 final int N = pkg.providers.size();
The Android Open Source Project10592532009-03-18 17:39:46 -07003736 int i;
3737 for (i=0; i<N; i++) {
3738 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003739 if (p.info.authority != null) {
3740 String names[] = p.info.authority.split(";");
3741 for (int j = 0; j < names.length; j++) {
3742 if (mProviders.containsKey(names[j])) {
3743 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003744 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003745 " (in package " + pkg.applicationInfo.packageName +
3746 ") is already used by "
3747 + ((other != null && other.getComponentName() != null)
3748 ? other.getComponentName().getPackageName() : "?"));
3749 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3750 return null;
3751 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003752 }
3753 }
3754 }
3755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756
Kenny Root447106f2011-03-23 11:00:15 -07003757 if (pkg.mAdoptPermissions != null) {
3758 // This package wants to adopt ownership of permissions from
3759 // another package.
3760 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
3761 final String origName = pkg.mAdoptPermissions.get(i);
3762 final PackageSetting orig = mSettings.peekPackageLPr(origName);
3763 if (orig != null) {
3764 if (verifyPackageUpdateLPr(orig, pkg)) {
3765 Slog.i(TAG, "Adopting permissions from " + origName + " to "
3766 + pkg.packageName);
3767 mSettings.transferPermissionsLPw(origName, pkg.packageName);
3768 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003769 }
3770 }
3771 }
3772 }
Kenny Root447106f2011-03-23 11:00:15 -07003773
3774 final String pkgName = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003775
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003776 final long scanFileTime = scanFile.lastModified();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003777 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 pkg.applicationInfo.processName = fixProcessName(
3779 pkg.applicationInfo.packageName,
3780 pkg.applicationInfo.processName,
3781 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003782
3783 File dataPath;
3784 if (mPlatformPackage == pkg) {
3785 // The system package is special.
3786 dataPath = new File (Environment.getDataDirectory(), "system");
3787 pkg.applicationInfo.dataDir = dataPath.getPath();
3788 } else {
3789 // This is a normal package, need to make its data directory.
Amith Yamasani0b285492011-04-14 17:35:23 -07003790 dataPath = getDataPathForPackage(pkg.packageName, 0);
Dianne Hackbornd0c5f512012-06-07 16:53:59 -07003791
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003792 boolean uidError = false;
Dianne Hackbornd0c5f512012-06-07 16:53:59 -07003793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794 if (dataPath.exists()) {
Kenny Root786cbca2012-08-16 11:10:58 -07003795 int currentUid = 0;
3796 try {
3797 StructStat stat = Libcore.os.stat(dataPath.getPath());
3798 currentUid = stat.st_uid;
3799 } catch (ErrnoException e) {
3800 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
3801 }
Kenny Root85387d72010-08-26 10:13:11 -07003802
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003803 // If we have mismatched owners for the data path, we have a problem.
Kenny Root786cbca2012-08-16 11:10:58 -07003804 if (currentUid != pkg.applicationInfo.uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 boolean recovered = false;
Kenny Root786cbca2012-08-16 11:10:58 -07003806 if (currentUid == 0) {
Dianne Hackbornd0c5f512012-06-07 16:53:59 -07003807 // The directory somehow became owned by root. Wow.
3808 // This is probably because the system was stopped while
3809 // installd was in the middle of messing with its libs
3810 // directory. Ask installd to fix that.
3811 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
3812 pkg.applicationInfo.uid);
3813 if (ret >= 0) {
3814 recovered = true;
3815 String msg = "Package " + pkg.packageName
3816 + " unexpectedly changed to uid 0; recovered to " +
3817 + pkg.applicationInfo.uid;
3818 reportSettingsProblem(Log.WARN, msg);
3819 }
3820 }
3821 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
3822 || (scanMode&SCAN_BOOTING) != 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823 // If this is a system app, we can at least delete its
3824 // current data so the application will still work.
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003825 int ret = mInstaller.remove(pkgName, 0);
3826 if (ret >= 0) {
3827 // TODO: Kill the processes first
3828 // Remove the data directories for all users
Amith Yamasani13593602012-03-22 16:16:17 -07003829 sUserManager.removePackageForAllUsers(pkgName);
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003830 // Old data gone!
Dianne Hackbornd0c5f512012-06-07 16:53:59 -07003831 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
3832 ? "System package " : "Third party package ";
3833 String msg = prefix + pkg.packageName
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003834 + " has changed from uid: "
Kenny Root786cbca2012-08-16 11:10:58 -07003835 + currentUid + " to "
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003836 + pkg.applicationInfo.uid + "; old data erased";
3837 reportSettingsProblem(Log.WARN, msg);
3838 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003839
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003840 // And now re-install the app.
3841 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
3842 pkg.applicationInfo.uid);
3843 if (ret == -1) {
3844 // Ack should not happen!
Dianne Hackbornd0c5f512012-06-07 16:53:59 -07003845 msg = prefix + pkg.packageName
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003846 + " could not have data directory re-created after delete.";
3847 reportSettingsProblem(Log.WARN, msg);
3848 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3849 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003850 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003851 // Create data directories for all users
Amith Yamasani13593602012-03-22 16:16:17 -07003852 sUserManager.installPackageForAllUsers(pkgName,
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003853 pkg.applicationInfo.uid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003855 if (!recovered) {
3856 mHasSystemUidErrors = true;
3857 }
Dianne Hackbornd0c5f512012-06-07 16:53:59 -07003858 } else if (!recovered) {
3859 // If we allow this install to proceed, we will be broken.
3860 // Abort, abort!
3861 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
3862 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003863 }
3864 if (!recovered) {
3865 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3866 + pkg.applicationInfo.uid + "/fs_"
Kenny Root786cbca2012-08-16 11:10:58 -07003867 + currentUid;
Kenny Root85387d72010-08-26 10:13:11 -07003868 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003869 String msg = "Package " + pkg.packageName
3870 + " has mismatched uid: "
Kenny Root786cbca2012-08-16 11:10:58 -07003871 + currentUid + " on disk, "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003872 + pkg.applicationInfo.uid + " in settings";
Kenny Root447106f2011-03-23 11:00:15 -07003873 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003874 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003875 mSettings.mReadMessages.append(msg);
3876 mSettings.mReadMessages.append('\n');
3877 uidError = true;
3878 if (!pkgSetting.uidError) {
3879 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003881 }
3882 }
3883 }
3884 pkg.applicationInfo.dataDir = dataPath.getPath();
3885 } else {
Kenny Root4dfe6ff2011-02-23 17:00:43 -08003886 if (DEBUG_PACKAGE_SCANNING) {
3887 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
3888 Log.v(TAG, "Want this data dir: " + dataPath);
3889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003890 //invoke installer to do the actual installation
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003891 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
3892 pkg.applicationInfo.uid);
3893 if (ret < 0) {
3894 // Error from installer
3895 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3896 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003898 // Create data directories for all users
Amith Yamasani13593602012-03-22 16:16:17 -07003899 sUserManager.installPackageForAllUsers(pkgName, pkg.applicationInfo.uid);
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901 if (dataPath.exists()) {
3902 pkg.applicationInfo.dataDir = dataPath.getPath();
3903 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003904 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 pkg.applicationInfo.dataDir = null;
3906 }
3907 }
Kenny Root85387d72010-08-26 10:13:11 -07003908
3909 /*
3910 * Set the data dir to the default "/data/data/<package name>/lib"
3911 * if we got here without anyone telling us different (e.g., apps
3912 * stored on SD card have their native libraries stored in the ASEC
3913 * container with the APK).
Kenny Root806cc132010-09-12 08:34:19 -07003914 *
3915 * This happens during an upgrade from a package settings file that
3916 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07003917 */
Kenny Rootbd135c12010-10-05 12:26:27 -07003918 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
3919 if (pkgSetting.nativeLibraryPathString == null) {
3920 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
3921 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
3922 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
3923 } else {
3924 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
3925 }
Kenny Root85387d72010-08-26 10:13:11 -07003926 }
3927
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003928 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003929 }
3930
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003931 String path = scanFile.getPath();
3932 /* Note: We don't want to unpack the native binaries for
3933 * system applications, unless they have been updated
3934 * (the binaries are already under /system/lib).
3935 * Also, don't unpack libs for apps on the external card
3936 * since they should have their libraries in the ASEC
3937 * container already.
3938 *
3939 * In other words, we're going to unpack the binaries
3940 * only for non-system apps and system app upgrades.
3941 */
3942 if (pkg.applicationInfo.nativeLibraryDir != null) {
3943 try {
3944 final File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
Kenny Root5832ead2011-08-02 15:47:08 -07003945 final String dataPathString = dataPath.getCanonicalPath();
Kenny Roote68d58a2010-10-18 16:08:54 -07003946
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003947 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
3948 /*
3949 * Upgrading from a previous version of the OS sometimes
3950 * leaves native libraries in the /data/data/<app>/lib
3951 * directory for system apps even when they shouldn't be.
3952 * Recent changes in the JNI library search path
3953 * necessitates we remove those to match previous behavior.
3954 */
3955 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
3956 Log.i(TAG, "removed obsolete native libraries for system package "
3957 + path);
Kenny Root831baa22010-10-05 12:29:25 -07003958 }
Kenny Root5832ead2011-08-02 15:47:08 -07003959 } else if (nativeLibraryDir.getParentFile().getCanonicalPath()
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003960 .equals(dataPathString)) {
3961 /*
Kenny Root66269ea2011-07-12 14:14:01 -07003962 * Make sure the native library dir isn't a symlink to
3963 * something. If it is, ask installd to remove it and create
3964 * a directory so we can copy to it afterwards.
3965 */
3966 boolean isSymLink;
3967 try {
3968 isSymLink = S_ISLNK(Libcore.os.lstat(nativeLibraryDir.getPath()).st_mode);
3969 } catch (ErrnoException e) {
3970 // This shouldn't happen, but we'll fail-safe.
3971 isSymLink = true;
3972 }
3973 if (isSymLink) {
3974 mInstaller.unlinkNativeLibraryDirectory(dataPathString);
3975 }
3976
3977 /*
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003978 * If this is an internal application or our
3979 * nativeLibraryPath points to our data directory, unpack
Kenny Root66269ea2011-07-12 14:14:01 -07003980 * the libraries if necessary.
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003981 */
Kenny Root66269ea2011-07-12 14:14:01 -07003982 NativeLibraryHelper.copyNativeBinariesIfNeededLI(scanFile, nativeLibraryDir);
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003983 } else {
3984 Slog.i(TAG, "Linking native library dir for " + path);
3985 mInstaller.linkNativeLibraryDirectory(dataPathString,
3986 pkg.applicationInfo.nativeLibraryDir);
Kenny Root831baa22010-10-05 12:29:25 -07003987 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003988 } catch (IOException ioe) {
3989 Log.e(TAG, "Unable to get canonical file " + ioe.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003990 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003991 }
3992 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003993
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003994 if ((scanMode&SCAN_NO_DEX) == 0) {
Dianne Hackborn661cd522011-08-22 00:26:20 -07003995 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0)
3996 == DEX_OPT_FAILED) {
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003997 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3998 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 }
4000 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004002 if (mFactoryTest && pkg.requestedPermissions.contains(
4003 android.Manifest.permission.FACTORY_TEST)) {
4004 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
4005 }
4006
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004007 // Request the ActivityManager to kill the process(only for existing packages)
4008 // so that we do not end up in a confused state while the user is still using the older
4009 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004010 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004011 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004012 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004013 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004014
Kenny Root447106f2011-03-23 11:00:15 -07004015 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004017 // We don't expect installation to fail beyond this point,
4018 if ((scanMode&SCAN_MONITOR) != 0) {
4019 mAppDirs.put(pkg.mPath, pkg);
4020 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 // Add the new setting to mSettings
Kenny Root447106f2011-03-23 11:00:15 -07004022 mSettings.insertPackageSettingLPw(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004023 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07004024 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004025 // Make sure we don't accidentally delete its data.
4026 mSettings.mPackagesToBeCleaned.remove(pkgName);
4027
Dianne Hackborn78d6883692010-10-07 01:12:46 -07004028 // Take care of first install / last update times.
4029 if (currentTime != 0) {
4030 if (pkgSetting.firstInstallTime == 0) {
4031 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
4032 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
4033 pkgSetting.lastUpdateTime = currentTime;
4034 }
4035 } else if (pkgSetting.firstInstallTime == 0) {
4036 // We need *something*. Take time time stamp of the file.
4037 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
4038 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
4039 if (scanFileTime != pkgSetting.timeStamp) {
4040 // A package on the system image has changed; consider this
4041 // to be an update.
4042 pkgSetting.lastUpdateTime = scanFileTime;
4043 }
4044 }
4045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 int N = pkg.providers.size();
4047 StringBuilder r = null;
4048 int i;
4049 for (i=0; i<N; i++) {
4050 PackageParser.Provider p = pkg.providers.get(i);
4051 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
4052 p.info.processName, pkg.applicationInfo.uid);
4053 mProvidersByComponent.put(new ComponentName(p.info.packageName,
4054 p.info.name), p);
4055 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08004056 if (p.info.authority != null) {
4057 String names[] = p.info.authority.split(";");
4058 p.info.authority = null;
4059 for (int j = 0; j < names.length; j++) {
4060 if (j == 1 && p.syncable) {
4061 // We only want the first authority for a provider to possibly be
4062 // syncable, so if we already added this provider using a different
4063 // authority clear the syncable flag. We copy the provider before
4064 // changing it because the mProviders object contains a reference
4065 // to a provider that we don't want to change.
4066 // Only do this for the second authority since the resulting provider
4067 // object can be the same for all future authorities for this provider.
4068 p = new PackageParser.Provider(p);
4069 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004070 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08004071 if (!mProviders.containsKey(names[j])) {
4072 mProviders.put(names[j], p);
4073 if (p.info.authority == null) {
4074 p.info.authority = names[j];
4075 } else {
4076 p.info.authority = p.info.authority + ";" + names[j];
4077 }
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004078 if (DEBUG_PACKAGE_SCANNING) {
4079 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4080 Log.d(TAG, "Registered content provider: " + names[j]
4081 + ", className = " + p.info.name + ", isSyncable = "
4082 + p.info.isSyncable);
4083 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08004084 } else {
4085 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004086 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08004087 " (in package " + pkg.applicationInfo.packageName +
4088 "): name already used by "
4089 + ((other != null && other.getComponentName() != null)
4090 ? other.getComponentName().getPackageName() : "?"));
4091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004092 }
4093 }
4094 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4095 if (r == null) {
4096 r = new StringBuilder(256);
4097 } else {
4098 r.append(' ');
4099 }
4100 r.append(p.info.name);
4101 }
4102 }
4103 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004104 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004107 N = pkg.services.size();
4108 r = null;
4109 for (i=0; i<N; i++) {
4110 PackageParser.Service s = pkg.services.get(i);
4111 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
4112 s.info.processName, pkg.applicationInfo.uid);
4113 mServices.addService(s);
4114 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4115 if (r == null) {
4116 r = new StringBuilder(256);
4117 } else {
4118 r.append(' ');
4119 }
4120 r.append(s.info.name);
4121 }
4122 }
4123 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004124 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004125 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004127 N = pkg.receivers.size();
4128 r = null;
4129 for (i=0; i<N; i++) {
4130 PackageParser.Activity a = pkg.receivers.get(i);
4131 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
4132 a.info.processName, pkg.applicationInfo.uid);
4133 mReceivers.addActivity(a, "receiver");
4134 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4135 if (r == null) {
4136 r = new StringBuilder(256);
4137 } else {
4138 r.append(' ');
4139 }
4140 r.append(a.info.name);
4141 }
4142 }
4143 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004144 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004147 N = pkg.activities.size();
4148 r = null;
4149 for (i=0; i<N; i++) {
4150 PackageParser.Activity a = pkg.activities.get(i);
4151 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
4152 a.info.processName, pkg.applicationInfo.uid);
4153 mActivities.addActivity(a, "activity");
4154 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4155 if (r == null) {
4156 r = new StringBuilder(256);
4157 } else {
4158 r.append(' ');
4159 }
4160 r.append(a.info.name);
4161 }
4162 }
4163 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004164 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004165 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167 N = pkg.permissionGroups.size();
4168 r = null;
4169 for (i=0; i<N; i++) {
4170 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
4171 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
4172 if (cur == null) {
4173 mPermissionGroups.put(pg.info.name, pg);
4174 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4175 if (r == null) {
4176 r = new StringBuilder(256);
4177 } else {
4178 r.append(' ');
4179 }
4180 r.append(pg.info.name);
4181 }
4182 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004183 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004184 + pg.info.packageName + " ignored: original from "
4185 + cur.info.packageName);
4186 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4187 if (r == null) {
4188 r = new StringBuilder(256);
4189 } else {
4190 r.append(' ');
4191 }
4192 r.append("DUP:");
4193 r.append(pg.info.name);
4194 }
4195 }
4196 }
4197 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004198 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004201 N = pkg.permissions.size();
4202 r = null;
4203 for (i=0; i<N; i++) {
4204 PackageParser.Permission p = pkg.permissions.get(i);
4205 HashMap<String, BasePermission> permissionMap =
4206 p.tree ? mSettings.mPermissionTrees
4207 : mSettings.mPermissions;
4208 p.group = mPermissionGroups.get(p.info.group);
4209 if (p.info.group == null || p.group != null) {
4210 BasePermission bp = permissionMap.get(p.info.name);
4211 if (bp == null) {
4212 bp = new BasePermission(p.info.name, p.info.packageName,
4213 BasePermission.TYPE_NORMAL);
4214 permissionMap.put(p.info.name, bp);
4215 }
4216 if (bp.perm == null) {
4217 if (bp.sourcePackage == null
4218 || bp.sourcePackage.equals(p.info.packageName)) {
4219 BasePermission tree = findPermissionTreeLP(p.info.name);
4220 if (tree == null
4221 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004222 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004223 bp.perm = p;
4224 bp.uid = pkg.applicationInfo.uid;
4225 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4226 if (r == null) {
4227 r = new StringBuilder(256);
4228 } else {
4229 r.append(' ');
4230 }
4231 r.append(p.info.name);
4232 }
4233 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004234 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004235 + p.info.packageName + " ignored: base tree "
4236 + tree.name + " is from package "
4237 + tree.sourcePackage);
4238 }
4239 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004240 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241 + p.info.packageName + " ignored: original from "
4242 + bp.sourcePackage);
4243 }
4244 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4245 if (r == null) {
4246 r = new StringBuilder(256);
4247 } else {
4248 r.append(' ');
4249 }
4250 r.append("DUP:");
4251 r.append(p.info.name);
4252 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004253 if (bp.perm == p) {
4254 bp.protectionLevel = p.info.protectionLevel;
4255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004256 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004257 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 + p.info.packageName + " ignored: no group "
4259 + p.group);
4260 }
4261 }
4262 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004263 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004264 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004266 N = pkg.instrumentation.size();
4267 r = null;
4268 for (i=0; i<N; i++) {
4269 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
4270 a.info.packageName = pkg.applicationInfo.packageName;
4271 a.info.sourceDir = pkg.applicationInfo.sourceDir;
4272 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
4273 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07004274 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004275 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4277 if (r == null) {
4278 r = new StringBuilder(256);
4279 } else {
4280 r.append(' ');
4281 }
4282 r.append(a.info.name);
4283 }
4284 }
4285 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004286 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004287 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004288
Dianne Hackborn854060af2009-07-09 18:14:31 -07004289 if (pkg.protectedBroadcasts != null) {
4290 N = pkg.protectedBroadcasts.size();
4291 for (i=0; i<N; i++) {
4292 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
4293 }
4294 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 pkgSetting.setTimeStamp(scanFileTime);
4297 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 return pkg;
4300 }
4301
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004302 private void killApplication(String pkgName, int uid) {
4303 // Request the ActivityManager to kill the process(only for existing packages)
4304 // so that we do not end up in a confused state while the user is still using the older
4305 // version of the application while the new one gets installed.
4306 IActivityManager am = ActivityManagerNative.getDefault();
4307 if (am != null) {
4308 try {
4309 am.killApplicationWithUid(pkgName, uid);
4310 } catch (RemoteException e) {
4311 }
4312 }
4313 }
4314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004315 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004316 if (DEBUG_INSTALL) {
4317 if (chatty)
4318 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
4319 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004320
Kenny Root447106f2011-03-23 11:00:15 -07004321 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004322 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004323 mPackages.remove(pkg.applicationInfo.packageName);
4324 if (pkg.mPath != null) {
4325 mAppDirs.remove(pkg.mPath);
4326 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004328 int N = pkg.providers.size();
4329 StringBuilder r = null;
4330 int i;
4331 for (i=0; i<N; i++) {
4332 PackageParser.Provider p = pkg.providers.get(i);
4333 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
4334 p.info.name));
4335 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004337 /* The is another ContentProvider with this authority when
4338 * this app was installed so this authority is null,
4339 * Ignore it as we don't have to unregister the provider.
4340 */
4341 continue;
4342 }
4343 String names[] = p.info.authority.split(";");
4344 for (int j = 0; j < names.length; j++) {
4345 if (mProviders.get(names[j]) == p) {
4346 mProviders.remove(names[j]);
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004347 if (DEBUG_REMOVE) {
4348 if (chatty)
4349 Log.d(TAG, "Unregistered content provider: " + names[j]
4350 + ", className = " + p.info.name + ", isSyncable = "
4351 + p.info.isSyncable);
4352 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004353 }
4354 }
4355 if (chatty) {
4356 if (r == null) {
4357 r = new StringBuilder(256);
4358 } else {
4359 r.append(' ');
4360 }
4361 r.append(p.info.name);
4362 }
4363 }
4364 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004365 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004366 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004368 N = pkg.services.size();
4369 r = null;
4370 for (i=0; i<N; i++) {
4371 PackageParser.Service s = pkg.services.get(i);
4372 mServices.removeService(s);
4373 if (chatty) {
4374 if (r == null) {
4375 r = new StringBuilder(256);
4376 } else {
4377 r.append(' ');
4378 }
4379 r.append(s.info.name);
4380 }
4381 }
4382 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004383 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004384 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004386 N = pkg.receivers.size();
4387 r = null;
4388 for (i=0; i<N; i++) {
4389 PackageParser.Activity a = pkg.receivers.get(i);
4390 mReceivers.removeActivity(a, "receiver");
4391 if (chatty) {
4392 if (r == null) {
4393 r = new StringBuilder(256);
4394 } else {
4395 r.append(' ');
4396 }
4397 r.append(a.info.name);
4398 }
4399 }
4400 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004401 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004402 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004404 N = pkg.activities.size();
4405 r = null;
4406 for (i=0; i<N; i++) {
4407 PackageParser.Activity a = pkg.activities.get(i);
4408 mActivities.removeActivity(a, "activity");
4409 if (chatty) {
4410 if (r == null) {
4411 r = new StringBuilder(256);
4412 } else {
4413 r.append(' ');
4414 }
4415 r.append(a.info.name);
4416 }
4417 }
4418 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004419 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004420 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004422 N = pkg.permissions.size();
4423 r = null;
4424 for (i=0; i<N; i++) {
4425 PackageParser.Permission p = pkg.permissions.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004426 BasePermission bp = mSettings.mPermissions.get(p.info.name);
4427 if (bp == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004428 bp = mSettings.mPermissionTrees.get(p.info.name);
4429 }
4430 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004431 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004432 if (chatty) {
4433 if (r == null) {
4434 r = new StringBuilder(256);
4435 } else {
4436 r.append(' ');
4437 }
4438 r.append(p.info.name);
4439 }
4440 }
4441 }
4442 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004443 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004444 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004446 N = pkg.instrumentation.size();
4447 r = null;
4448 for (i=0; i<N; i++) {
4449 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004450 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004451 if (chatty) {
4452 if (r == null) {
4453 r = new StringBuilder(256);
4454 } else {
4455 r.append(' ');
4456 }
4457 r.append(a.info.name);
4458 }
4459 }
4460 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004461 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004462 }
4463 }
4464 }
4465
4466 private static final boolean isPackageFilename(String name) {
4467 return name != null && name.endsWith(".apk");
4468 }
4469
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004470 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
4471 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
4472 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
4473 return true;
4474 }
4475 }
4476 return false;
4477 }
Dianne Hackborne639da72012-02-21 15:11:13 -08004478
4479 static final int UPDATE_PERMISSIONS_ALL = 1<<0;
4480 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
4481 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
4482
Kenny Root447106f2011-03-23 11:00:15 -07004483 private void updatePermissionsLPw(String changingPkg,
Dianne Hackborne639da72012-02-21 15:11:13 -08004484 PackageParser.Package pkgInfo, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485 // Make sure there are no dangling permission trees.
Kenny Root447106f2011-03-23 11:00:15 -07004486 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004487 while (it.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07004488 final BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004489 if (bp.packageSetting == null) {
4490 // We may not yet have parsed the package, so just see if
4491 // we still know about its settings.
4492 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4493 }
4494 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004495 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004496 + " from package " + bp.sourcePackage);
4497 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004498 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4499 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4500 Slog.i(TAG, "Removing old permission tree: " + bp.name
4501 + " from package " + bp.sourcePackage);
Dianne Hackborne639da72012-02-21 15:11:13 -08004502 flags |= UPDATE_PERMISSIONS_ALL;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004503 it.remove();
4504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004505 }
4506 }
4507
4508 // Make sure all dynamic permissions have been assigned to a package,
4509 // and make sure there are no dangling permissions.
4510 it = mSettings.mPermissions.values().iterator();
4511 while (it.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07004512 final BasePermission bp = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004513 if (bp.type == BasePermission.TYPE_DYNAMIC) {
4514 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
4515 + bp.name + " pkg=" + bp.sourcePackage
4516 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004517 if (bp.packageSetting == null && bp.pendingInfo != null) {
Kenny Root447106f2011-03-23 11:00:15 -07004518 final BasePermission tree = findPermissionTreeLP(bp.name);
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07004519 if (tree != null && tree.perm != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004520 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004521 bp.perm = new PackageParser.Permission(tree.perm.owner,
4522 new PermissionInfo(bp.pendingInfo));
4523 bp.perm.info.packageName = tree.perm.info.packageName;
4524 bp.perm.info.name = bp.name;
4525 bp.uid = tree.uid;
4526 }
4527 }
4528 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004529 if (bp.packageSetting == null) {
4530 // We may not yet have parsed the package, so just see if
4531 // we still know about its settings.
4532 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4533 }
4534 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004535 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004536 + " from package " + bp.sourcePackage);
4537 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004538 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4539 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4540 Slog.i(TAG, "Removing old permission: " + bp.name
4541 + " from package " + bp.sourcePackage);
Dianne Hackborne639da72012-02-21 15:11:13 -08004542 flags |= UPDATE_PERMISSIONS_ALL;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004543 it.remove();
4544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004545 }
4546 }
4547
4548 // Now update the permissions for all packages, in particular
4549 // replace the granted permissions of the system packages.
Dianne Hackborne639da72012-02-21 15:11:13 -08004550 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004551 for (PackageParser.Package pkg : mPackages.values()) {
4552 if (pkg != pkgInfo) {
Dianne Hackborne639da72012-02-21 15:11:13 -08004553 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004554 }
4555 }
4556 }
4557
4558 if (pkgInfo != null) {
Dianne Hackborne639da72012-02-21 15:11:13 -08004559 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004560 }
4561 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004562
Kenny Root447106f2011-03-23 11:00:15 -07004563 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
4564 final PackageSetting ps = (PackageSetting) pkg.mExtras;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004565 if (ps == null) {
4566 return;
4567 }
4568 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackborne639da72012-02-21 15:11:13 -08004569 HashSet<String> origPermissions = gp.grantedPermissions;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004570 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004572 if (replace) {
4573 ps.permissionsFixed = false;
4574 if (gp == ps) {
Dianne Hackborne639da72012-02-21 15:11:13 -08004575 origPermissions = new HashSet<String>(gp.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004576 gp.grantedPermissions.clear();
4577 gp.gids = mGlobalGids;
4578 }
4579 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004581 if (gp.gids == null) {
4582 gp.gids = mGlobalGids;
4583 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004585 final int N = pkg.requestedPermissions.size();
4586 for (int i=0; i<N; i++) {
Kenny Root447106f2011-03-23 11:00:15 -07004587 final String name = pkg.requestedPermissions.get(i);
Dianne Hackborne639da72012-02-21 15:11:13 -08004588 //final boolean required = pkg.requestedPermssionsRequired.get(i);
Kenny Root447106f2011-03-23 11:00:15 -07004589 final BasePermission bp = mSettings.mPermissions.get(name);
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004590 if (DEBUG_INSTALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004591 if (gp != ps) {
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004592 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004593 }
4594 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004595 if (bp != null && bp.packageSetting != null) {
4596 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004597 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004598 boolean allowedSig = false;
Dianne Hackborne639da72012-02-21 15:11:13 -08004599 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
4600 if (level == PermissionInfo.PROTECTION_NORMAL
4601 || level == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004602 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07004603 } else if (bp.packageSetting == null) {
4604 // This permission is invalid; skip it.
4605 allowed = false;
Dianne Hackborne639da72012-02-21 15:11:13 -08004606 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
Kenny Root447106f2011-03-23 11:00:15 -07004607 allowed = (compareSignatures(
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07004608 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004609 == PackageManager.SIGNATURE_MATCH)
Kenny Root447106f2011-03-23 11:00:15 -07004610 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004611 == PackageManager.SIGNATURE_MATCH);
Dianne Hackborne639da72012-02-21 15:11:13 -08004612 if (!allowed && (bp.protectionLevel
4613 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
Kenny Root85387d72010-08-26 10:13:11 -07004614 if (isSystemApp(pkg)) {
Dianne Hackborne639da72012-02-21 15:11:13 -08004615 // For updated system applications, a system permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004616 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07004617 if (isUpdatedSystemApp(pkg)) {
Kenny Root447106f2011-03-23 11:00:15 -07004618 final PackageSetting sysPs = mSettings
4619 .getDisabledSystemPkgLPr(pkg.packageName);
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07004620 final GrantedPermissions origGp = sysPs.sharedUser != null
4621 ? sysPs.sharedUser : sysPs;
4622 if (origGp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004623 allowed = true;
4624 } else {
4625 allowed = false;
4626 }
4627 } else {
4628 allowed = true;
4629 }
4630 }
4631 }
Dianne Hackborne639da72012-02-21 15:11:13 -08004632 if (!allowed && (bp.protectionLevel
4633 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
4634 // For development permissions, a development permission
4635 // is granted only if it was already granted.
4636 if (origPermissions.contains(perm)) {
4637 allowed = true;
4638 } else {
4639 allowed = false;
4640 }
4641 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004642 if (allowed) {
4643 allowedSig = true;
4644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004645 } else {
4646 allowed = false;
4647 }
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004648 if (DEBUG_INSTALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004649 if (gp != ps) {
4650 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4651 }
4652 }
4653 if (allowed) {
4654 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4655 && ps.permissionsFixed) {
4656 // If this is an existing, non-system package, then
4657 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004658 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004659 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004660 // Except... if this is a permission that was added
4661 // to the platform (note: need to only do this when
4662 // updating the platform).
4663 final int NP = PackageParser.NEW_PERMISSIONS.length;
4664 for (int ip=0; ip<NP; ip++) {
4665 final PackageParser.NewPermissionInfo npi
4666 = PackageParser.NEW_PERMISSIONS[ip];
4667 if (npi.name.equals(perm)
4668 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4669 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004670 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004671 + pkg.packageName);
4672 break;
4673 }
4674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004675 }
4676 }
4677 if (allowed) {
4678 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004679 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004680 gp.grantedPermissions.add(perm);
4681 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004682 } else if (!ps.haveGids) {
4683 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004684 }
4685 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004686 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004687 + " to package " + pkg.packageName
4688 + " because it was previously installed without");
4689 }
4690 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004691 if (gp.grantedPermissions.remove(perm)) {
4692 changedPermission = true;
4693 gp.gids = removeInts(gp.gids, bp.gids);
4694 Slog.i(TAG, "Un-granting permission " + perm
4695 + " from package " + pkg.packageName
4696 + " (protectionLevel=" + bp.protectionLevel
4697 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4698 + ")");
4699 } else {
4700 Slog.w(TAG, "Not granting permission " + perm
4701 + " to package " + pkg.packageName
4702 + " (protectionLevel=" + bp.protectionLevel
4703 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4704 + ")");
4705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004706 }
4707 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004708 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004709 + " in package " + pkg.packageName);
4710 }
4711 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004712
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004713 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004714 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4715 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004716 // This is the first that we have heard about this package, so the
4717 // permissions we have now selected are fixed until explicitly
4718 // changed.
4719 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004720 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004721 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004722 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004724 private final class ActivityIntentResolver
4725 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Kenny Root60f7ad82011-03-22 12:49:06 -07004726 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004727 boolean defaultOnly, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07004728 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004729 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Amith Yamasani483f3b02012-03-13 16:08:00 -07004730 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004731 }
4732
Amith Yamasani483f3b02012-03-13 16:08:00 -07004733 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
4734 int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07004735 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004736 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004737 return super.queryIntent(intent, resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004738 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004739 }
4740
Kenny Root60f7ad82011-03-22 12:49:06 -07004741 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004742 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07004743 if (!sUserManager.exists(userId)) return null;
Mihai Predaeae850c2009-05-13 10:13:48 +02004744 if (packageActivities == null) {
4745 return null;
4746 }
4747 mFlags = flags;
4748 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
Kenny Root62cc6902011-02-23 16:49:21 -08004749 final int N = packageActivities.size();
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07004750 ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
4751 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004752
4753 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004754 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004755 intentFilters = packageActivities.get(i).intents;
4756 if (intentFilters != null && intentFilters.size() > 0) {
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07004757 PackageParser.ActivityIntentInfo[] array =
4758 new PackageParser.ActivityIntentInfo[intentFilters.size()];
4759 intentFilters.toArray(array);
4760 listCut.add(array);
Mihai Predac3320db2009-05-18 20:15:32 +02004761 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004762 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07004763 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
Mihai Predaeae850c2009-05-13 10:13:48 +02004764 }
4765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004766 public final void addActivity(PackageParser.Activity a, String type) {
Kenny Root502e9a42011-01-10 13:48:15 -08004767 final boolean systemApp = isSystemApp(a.info.applicationInfo);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004768 mActivities.put(a.getComponentName(), a);
Kenny Root9718cf52011-02-23 16:45:26 -08004769 if (DEBUG_SHOW_INFO)
4770 Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004771 TAG, " " + type + " " +
4772 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
Kenny Root9718cf52011-02-23 16:45:26 -08004773 if (DEBUG_SHOW_INFO)
4774 Log.v(TAG, " Class=" + a.info.name);
Kenny Root62cc6902011-02-23 16:49:21 -08004775 final int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004776 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004777 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
Kenny Root502e9a42011-01-10 13:48:15 -08004778 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
4779 intent.setPriority(0);
4780 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
4781 + a.className + " with priority > 0, forcing to 0");
4782 }
Kenny Root9718cf52011-02-23 16:45:26 -08004783 if (DEBUG_SHOW_INFO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004784 Log.v(TAG, " IntentFilter:");
4785 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4786 }
4787 if (!intent.debugCheck()) {
4788 Log.w(TAG, "==> For Activity " + a.info.name);
4789 }
4790 addFilter(intent);
4791 }
4792 }
4793
4794 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004795 mActivities.remove(a.getComponentName());
Kenny Root9718cf52011-02-23 16:45:26 -08004796 if (DEBUG_SHOW_INFO) {
4797 Log.v(TAG, " " + type + " "
4798 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
4799 : a.info.name) + ":");
4800 Log.v(TAG, " Class=" + a.info.name);
4801 }
4802 final int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004803 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004804 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
Kenny Root9718cf52011-02-23 16:45:26 -08004805 if (DEBUG_SHOW_INFO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004806 Log.v(TAG, " IntentFilter:");
4807 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4808 }
4809 removeFilter(intent);
4810 }
4811 }
4812
4813 @Override
4814 protected boolean allowFilterResult(
4815 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4816 ActivityInfo filterAi = filter.activity.info;
4817 for (int i=dest.size()-1; i>=0; i--) {
4818 ActivityInfo destAi = dest.get(i).activityInfo;
4819 if (destAi.name == filterAi.name
4820 && destAi.packageName == filterAi.packageName) {
4821 return false;
4822 }
4823 }
4824 return true;
4825 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004827 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07004828 protected ActivityIntentInfo[] newArray(int size) {
4829 return new ActivityIntentInfo[size];
4830 }
4831
4832 @Override
Amith Yamasani483f3b02012-03-13 16:08:00 -07004833 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07004834 if (!sUserManager.exists(userId)) return true;
Dianne Hackborne7f97212011-02-24 14:40:20 -08004835 PackageParser.Package p = filter.activity.owner;
4836 if (p != null) {
4837 PackageSetting ps = (PackageSetting)p.mExtras;
4838 if (ps != null) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07004839 // System apps are never considered stopped for purposes of
4840 // filtering, because there may be no way for the user to
4841 // actually re-launch them.
Amith Yamasani483f3b02012-03-13 16:08:00 -07004842 return ps.getStopped(userId) && (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0;
Dianne Hackborne7f97212011-02-24 14:40:20 -08004843 }
4844 }
4845 return false;
4846 }
4847
4848 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004849 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4850 return info.activity.owner.packageName;
4851 }
4852
4853 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004854 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004855 int match, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07004856 if (!sUserManager.exists(userId)) return null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07004857 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004858 return null;
4859 }
4860 final PackageParser.Activity activity = info.activity;
4861 if (mSafeMode && (activity.info.applicationInfo.flags
4862 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4863 return null;
4864 }
4865 final ResolveInfo res = new ResolveInfo();
Amith Yamasani13593602012-03-22 16:16:17 -07004866 PackageSetting ps = (PackageSetting) activity.owner.mExtras;
4867 res.activityInfo = PackageParser.generateActivityInfo(activity, mFlags,
4868 ps != null ? ps.getStopped(userId) : false,
4869 ps != null ? ps.getEnabled(userId) : COMPONENT_ENABLED_STATE_DEFAULT,
4870 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004871 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4872 res.filter = info;
4873 }
4874 res.priority = info.getPriority();
4875 res.preferredOrder = activity.owner.mPreferredOrder;
4876 //System.out.println("Result: " + res.activityInfo.className +
4877 // " = " + res.priority);
4878 res.match = match;
4879 res.isDefault = info.hasDefault;
4880 res.labelRes = info.labelRes;
4881 res.nonLocalizedLabel = info.nonLocalizedLabel;
4882 res.icon = info.icon;
Dianne Hackbornd99b2932011-08-18 14:39:58 -07004883 res.system = isSystemApp(res.activityInfo.applicationInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004884 return res;
4885 }
4886
4887 @Override
4888 protected void sortResults(List<ResolveInfo> results) {
4889 Collections.sort(results, mResolvePrioritySorter);
4890 }
4891
4892 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004893 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004894 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004895 out.print(prefix); out.print(
4896 Integer.toHexString(System.identityHashCode(filter.activity)));
4897 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004898 out.print(filter.activity.getComponentShortName());
4899 out.print(" filter ");
4900 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004901 }
4902
4903// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4904// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4905// final List<ResolveInfo> retList = Lists.newArrayList();
4906// while (i.hasNext()) {
4907// final ResolveInfo resolveInfo = i.next();
4908// if (isEnabledLP(resolveInfo.activityInfo)) {
4909// retList.add(resolveInfo);
4910// }
4911// }
4912// return retList;
4913// }
4914
4915 // Keys are String (activity class name), values are Activity.
4916 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4917 = new HashMap<ComponentName, PackageParser.Activity>();
4918 private int mFlags;
4919 }
4920
4921 private final class ServiceIntentResolver
4922 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Kenny Root60f7ad82011-03-22 12:49:06 -07004923 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004924 boolean defaultOnly, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004925 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Amith Yamasani483f3b02012-03-13 16:08:00 -07004926 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004927 }
4928
Amith Yamasani483f3b02012-03-13 16:08:00 -07004929 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
4930 int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07004931 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004932 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004933 return super.queryIntent(intent, resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004934 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004935 }
4936
Kenny Root60f7ad82011-03-22 12:49:06 -07004937 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004938 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07004939 if (!sUserManager.exists(userId)) return null;
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07004940 if (packageServices == null) {
4941 return null;
4942 }
4943 mFlags = flags;
4944 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
Kenny Root62cc6902011-02-23 16:49:21 -08004945 final int N = packageServices.size();
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07004946 ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
4947 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07004948
4949 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4950 for (int i = 0; i < N; ++i) {
4951 intentFilters = packageServices.get(i).intents;
4952 if (intentFilters != null && intentFilters.size() > 0) {
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07004953 PackageParser.ServiceIntentInfo[] array =
4954 new PackageParser.ServiceIntentInfo[intentFilters.size()];
4955 intentFilters.toArray(array);
4956 listCut.add(array);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07004957 }
4958 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07004959 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07004960 }
4961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004962 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004963 mServices.put(s.getComponentName(), s);
Kenny Root9718cf52011-02-23 16:45:26 -08004964 if (DEBUG_SHOW_INFO) {
4965 Log.v(TAG, " "
4966 + (s.info.nonLocalizedLabel != null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004967 ? s.info.nonLocalizedLabel : s.info.name) + ":");
Kenny Root9718cf52011-02-23 16:45:26 -08004968 Log.v(TAG, " Class=" + s.info.name);
4969 }
4970 final int NI = s.intents.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004971 int j;
4972 for (j=0; j<NI; j++) {
4973 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
Kenny Root9718cf52011-02-23 16:45:26 -08004974 if (DEBUG_SHOW_INFO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004975 Log.v(TAG, " IntentFilter:");
4976 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4977 }
4978 if (!intent.debugCheck()) {
4979 Log.w(TAG, "==> For Service " + s.info.name);
4980 }
4981 addFilter(intent);
4982 }
4983 }
4984
4985 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004986 mServices.remove(s.getComponentName());
Kenny Root9718cf52011-02-23 16:45:26 -08004987 if (DEBUG_SHOW_INFO) {
4988 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004989 ? s.info.nonLocalizedLabel : s.info.name) + ":");
Kenny Root9718cf52011-02-23 16:45:26 -08004990 Log.v(TAG, " Class=" + s.info.name);
4991 }
4992 final int NI = s.intents.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004993 int j;
4994 for (j=0; j<NI; j++) {
4995 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
Kenny Root9718cf52011-02-23 16:45:26 -08004996 if (DEBUG_SHOW_INFO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004997 Log.v(TAG, " IntentFilter:");
4998 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4999 }
5000 removeFilter(intent);
5001 }
5002 }
5003
5004 @Override
5005 protected boolean allowFilterResult(
5006 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
5007 ServiceInfo filterSi = filter.service.info;
5008 for (int i=dest.size()-1; i>=0; i--) {
5009 ServiceInfo destAi = dest.get(i).serviceInfo;
5010 if (destAi.name == filterSi.name
5011 && destAi.packageName == filterSi.packageName) {
5012 return false;
5013 }
5014 }
5015 return true;
5016 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005018 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07005019 protected PackageParser.ServiceIntentInfo[] newArray(int size) {
5020 return new PackageParser.ServiceIntentInfo[size];
5021 }
5022
5023 @Override
Amith Yamasani483f3b02012-03-13 16:08:00 -07005024 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005025 if (!sUserManager.exists(userId)) return true;
Dianne Hackborne7f97212011-02-24 14:40:20 -08005026 PackageParser.Package p = filter.service.owner;
5027 if (p != null) {
5028 PackageSetting ps = (PackageSetting)p.mExtras;
5029 if (ps != null) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07005030 // System apps are never considered stopped for purposes of
5031 // filtering, because there may be no way for the user to
5032 // actually re-launch them.
Amith Yamasani483f3b02012-03-13 16:08:00 -07005033 return ps.getStopped(userId)
5034 && (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0;
Dianne Hackborne7f97212011-02-24 14:40:20 -08005035 }
5036 }
5037 return false;
5038 }
5039
5040 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005041 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
5042 return info.service.owner.packageName;
5043 }
5044
5045 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005046 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005047 int match, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005048 if (!sUserManager.exists(userId)) return null;
Jason parksa3cdaa52011-01-13 14:15:43 -06005049 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005050 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005051 return null;
5052 }
5053 final PackageParser.Service service = info.service;
5054 if (mSafeMode && (service.info.applicationInfo.flags
5055 &ApplicationInfo.FLAG_SYSTEM) == 0) {
5056 return null;
5057 }
5058 final ResolveInfo res = new ResolveInfo();
Amith Yamasani13593602012-03-22 16:16:17 -07005059 PackageSetting ps = (PackageSetting) service.owner.mExtras;
5060 res.serviceInfo = PackageParser.generateServiceInfo(service, mFlags,
5061 ps != null ? ps.getStopped(userId) : false,
5062 ps != null ? ps.getEnabled(userId) : COMPONENT_ENABLED_STATE_DEFAULT,
5063 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005064 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
5065 res.filter = filter;
5066 }
5067 res.priority = info.getPriority();
5068 res.preferredOrder = service.owner.mPreferredOrder;
5069 //System.out.println("Result: " + res.activityInfo.className +
5070 // " = " + res.priority);
5071 res.match = match;
5072 res.isDefault = info.hasDefault;
5073 res.labelRes = info.labelRes;
5074 res.nonLocalizedLabel = info.nonLocalizedLabel;
5075 res.icon = info.icon;
Dianne Hackbornd99b2932011-08-18 14:39:58 -07005076 res.system = isSystemApp(res.serviceInfo.applicationInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005077 return res;
5078 }
5079
5080 @Override
5081 protected void sortResults(List<ResolveInfo> results) {
5082 Collections.sort(results, mResolvePrioritySorter);
5083 }
5084
5085 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005086 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005087 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005088 out.print(prefix); out.print(
5089 Integer.toHexString(System.identityHashCode(filter.service)));
5090 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005091 out.print(filter.service.getComponentShortName());
5092 out.print(" filter ");
5093 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005094 }
5095
5096// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
5097// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
5098// final List<ResolveInfo> retList = Lists.newArrayList();
5099// while (i.hasNext()) {
5100// final ResolveInfo resolveInfo = (ResolveInfo) i;
5101// if (isEnabledLP(resolveInfo.serviceInfo)) {
5102// retList.add(resolveInfo);
5103// }
5104// }
5105// return retList;
5106// }
5107
5108 // Keys are String (activity class name), values are Activity.
5109 private final HashMap<ComponentName, PackageParser.Service> mServices
5110 = new HashMap<ComponentName, PackageParser.Service>();
5111 private int mFlags;
5112 };
5113
5114 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
5115 new Comparator<ResolveInfo>() {
5116 public int compare(ResolveInfo r1, ResolveInfo r2) {
5117 int v1 = r1.priority;
5118 int v2 = r2.priority;
5119 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
5120 if (v1 != v2) {
5121 return (v1 > v2) ? -1 : 1;
5122 }
5123 v1 = r1.preferredOrder;
5124 v2 = r2.preferredOrder;
5125 if (v1 != v2) {
5126 return (v1 > v2) ? -1 : 1;
5127 }
5128 if (r1.isDefault != r2.isDefault) {
5129 return r1.isDefault ? -1 : 1;
5130 }
5131 v1 = r1.match;
5132 v2 = r2.match;
5133 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
Dianne Hackbornd99b2932011-08-18 14:39:58 -07005134 if (v1 != v2) {
5135 return (v1 > v2) ? -1 : 1;
5136 }
5137 if (r1.system != r2.system) {
5138 return r1.system ? -1 : 1;
5139 }
5140 return 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005141 }
5142 };
5143
5144 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
5145 new Comparator<ProviderInfo>() {
5146 public int compare(ProviderInfo p1, ProviderInfo p2) {
5147 final int v1 = p1.initOrder;
5148 final int v2 = p2.initOrder;
5149 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
5150 }
5151 };
5152
Kenny Root447106f2011-03-23 11:00:15 -07005153 static final void sendPackageBroadcast(String action, String pkg,
Amith Yamasani13593602012-03-22 16:16:17 -07005154 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005155 IActivityManager am = ActivityManagerNative.getDefault();
5156 if (am != null) {
5157 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005158 int[] userIds = userId == UserHandle.USER_ALL
Amith Yamasani13593602012-03-22 16:16:17 -07005159 ? sUserManager.getUserIds()
5160 : new int[] {userId};
5161 for (int id : userIds) {
5162 final Intent intent = new Intent(action,
5163 pkg != null ? Uri.fromParts("package", pkg, null) : null);
5164 if (extras != null) {
5165 intent.putExtras(extras);
5166 }
5167 if (targetPkg != null) {
5168 intent.setPackage(targetPkg);
5169 }
5170 // Modify the UID when posting to other users
5171 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
5172 if (uid > 0 && id > 0) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005173 uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
Amith Yamasani13593602012-03-22 16:16:17 -07005174 intent.putExtra(Intent.EXTRA_UID, uid);
5175 }
5176 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
5177 am.broadcastIntent(null, intent, null, finishedReceiver,
5178 0, null, null, null, finishedReceiver != null, false, id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005180 } catch (RemoteException ex) {
5181 }
5182 }
5183 }
Kenny Root300c13a2011-01-18 13:04:40 -08005184
5185 /**
5186 * Check if the external storage media is available. This is true if there
5187 * is a mounted external storage medium or if the external storage is
5188 * emulated.
5189 */
5190 private boolean isExternalMediaAvailable() {
5191 return mMediaMounted || Environment.isExternalStorageEmulated();
5192 }
5193
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005194 public String nextPackageToClean(String lastPackage) {
Kenny Root447106f2011-03-23 11:00:15 -07005195 // writer
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005196 synchronized (mPackages) {
Kenny Root300c13a2011-01-18 13:04:40 -08005197 if (!isExternalMediaAvailable()) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005198 // If the external storage is no longer mounted at this point,
5199 // the caller may not have been able to delete all of this
5200 // packages files and can not delete any more. Bail.
5201 return null;
5202 }
5203 if (lastPackage != null) {
5204 mSettings.mPackagesToBeCleaned.remove(lastPackage);
5205 }
5206 return mSettings.mPackagesToBeCleaned.size() > 0
5207 ? mSettings.mPackagesToBeCleaned.get(0) : null;
5208 }
5209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005210
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005211 void schedulePackageCleaning(String packageName) {
5212 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
5213 }
5214
5215 void startCleaningPackages() {
Kenny Root447106f2011-03-23 11:00:15 -07005216 // reader
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005217 synchronized (mPackages) {
Kenny Root300c13a2011-01-18 13:04:40 -08005218 if (!isExternalMediaAvailable()) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005219 return;
5220 }
5221 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
5222 return;
5223 }
5224 }
5225 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
5226 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
5227 IActivityManager am = ActivityManagerNative.getDefault();
5228 if (am != null) {
5229 try {
5230 am.startService(null, intent, null);
5231 } catch (RemoteException e) {
5232 }
5233 }
5234 }
5235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005236 private final class AppDirObserver extends FileObserver {
5237 public AppDirObserver(String path, int mask, boolean isrom) {
5238 super(path, mask);
5239 mRootDir = path;
5240 mIsRom = isrom;
5241 }
5242
5243 public void onEvent(int event, String path) {
5244 String removedPackage = null;
5245 int removedUid = -1;
5246 String addedPackage = null;
5247 int addedUid = -1;
5248
Kenny Root447106f2011-03-23 11:00:15 -07005249 // TODO post a message to the handler to obtain serial ordering
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005250 synchronized (mInstallLock) {
5251 String fullPathStr = null;
5252 File fullPath = null;
5253 if (path != null) {
5254 fullPath = new File(mRootDir, path);
5255 fullPathStr = fullPath.getPath();
5256 }
5257
Kenny Root9718cf52011-02-23 16:45:26 -08005258 if (DEBUG_APP_DIR_OBSERVER)
5259 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005260
5261 if (!isPackageFilename(path)) {
Kenny Root9718cf52011-02-23 16:45:26 -08005262 if (DEBUG_APP_DIR_OBSERVER)
5263 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005264 return;
5265 }
5266
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005267 // Ignore packages that are being installed or
5268 // have just been installed.
5269 if (ignoreCodePath(fullPathStr)) {
5270 return;
5271 }
5272 PackageParser.Package p = null;
Kenny Root447106f2011-03-23 11:00:15 -07005273 // reader
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005274 synchronized (mPackages) {
5275 p = mAppDirs.get(fullPathStr);
5276 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005277 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005278 if (p != null) {
5279 removePackageLI(p, true);
5280 removedPackage = p.applicationInfo.packageName;
5281 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005282 }
5283 }
5284
5285 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005286 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005287 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07005288 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
5289 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005290 PackageParser.PARSE_CHATTY |
5291 PackageParser.PARSE_MUST_BE_APK,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005292 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
5293 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005294 if (p != null) {
Kenny Root447106f2011-03-23 11:00:15 -07005295 /*
5296 * TODO this seems dangerous as the package may have
5297 * changed since we last acquired the mPackages
5298 * lock.
5299 */
5300 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005301 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07005302 updatePermissionsLPw(p.packageName, p,
Dianne Hackborne639da72012-02-21 15:11:13 -08005303 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005304 }
5305 addedPackage = p.applicationInfo.packageName;
5306 addedUid = p.applicationInfo.uid;
5307 }
5308 }
5309 }
5310
Kenny Root447106f2011-03-23 11:00:15 -07005311 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005312 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07005313 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005314 }
5315 }
5316
5317 if (removedPackage != null) {
5318 Bundle extras = new Bundle(1);
5319 extras.putInt(Intent.EXTRA_UID, removedUid);
5320 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07005321 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005322 extras, null, null, UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005323 }
5324 if (addedPackage != null) {
5325 Bundle extras = new Bundle(1);
5326 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07005327 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005328 extras, null, null, UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005329 }
5330 }
5331
5332 private final String mRootDir;
5333 private final boolean mIsRom;
5334 }
Jacek Surazski65e13172009-04-28 15:26:38 +02005335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005336 /* Called when a downloaded package installation has been confirmed by the user */
5337 public void installPackage(
5338 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02005339 installPackage(packageURI, observer, flags, null);
5340 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005341
Jacek Surazski65e13172009-04-28 15:26:38 +02005342 /* Called when a downloaded package installation has been confirmed by the user */
5343 public void installPackage(
5344 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
5345 final String installerPackageName) {
Kenny Root5ab21572011-07-27 11:11:19 -07005346 installPackageWithVerification(packageURI, observer, flags, installerPackageName, null,
Rich Canningse1d7c712012-08-08 12:46:06 -07005347 null, null);
Kenny Root5ab21572011-07-27 11:11:19 -07005348 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005349
Kenny Root5ab21572011-07-27 11:11:19 -07005350 @Override
5351 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
5352 int flags, String installerPackageName, Uri verificationURI,
Rich Canningse1d7c712012-08-08 12:46:06 -07005353 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
Kenny Root5ab21572011-07-27 11:11:19 -07005354 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
5355
5356 final int uid = Binder.getCallingUid();
5357
5358 final int filteredFlags;
5359
5360 if (uid == Process.SHELL_UID || uid == 0) {
5361 if (DEBUG_INSTALL) {
5362 Slog.v(TAG, "Install from ADB");
5363 }
5364 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
5365 } else {
5366 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
5367 }
5368
5369 final Message msg = mHandler.obtainMessage(INIT_COPY);
5370 msg.obj = new InstallParams(packageURI, observer, filteredFlags, installerPackageName,
Rich Canningse1d7c712012-08-08 12:46:06 -07005371 verificationURI, manifestDigest, encryptionParams);
Kenny Root5ab21572011-07-27 11:11:19 -07005372 mHandler.sendMessage(msg);
5373 }
5374
5375 @Override
Kenny Root05ca4c92011-09-15 10:36:25 -07005376 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
Kenny Root5ab21572011-07-27 11:11:19 -07005377 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
Kenny Root05ca4c92011-09-15 10:36:25 -07005378 final PackageVerificationResponse response = new PackageVerificationResponse(
5379 verificationCode, Binder.getCallingUid());
Kenny Root5ab21572011-07-27 11:11:19 -07005380 msg.arg1 = id;
Kenny Root05ca4c92011-09-15 10:36:25 -07005381 msg.obj = response;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005382 mHandler.sendMessage(msg);
5383 }
5384
Kenny Root05ca4c92011-09-15 10:36:25 -07005385 private ComponentName matchComponentForVerifier(String packageName,
5386 List<ResolveInfo> receivers) {
5387 ActivityInfo targetReceiver = null;
5388
5389 final int NR = receivers.size();
5390 for (int i = 0; i < NR; i++) {
5391 final ResolveInfo info = receivers.get(i);
5392 if (info.activityInfo == null) {
5393 continue;
5394 }
5395
5396 if (packageName.equals(info.activityInfo.packageName)) {
5397 targetReceiver = info.activityInfo;
5398 break;
5399 }
5400 }
5401
5402 if (targetReceiver == null) {
5403 return null;
5404 }
5405
5406 return new ComponentName(targetReceiver.packageName, targetReceiver.name);
5407 }
5408
5409 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
5410 List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
5411 if (pkgInfo.verifiers.length == 0) {
5412 return null;
5413 }
5414
5415 final int N = pkgInfo.verifiers.length;
5416 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
5417 for (int i = 0; i < N; i++) {
5418 final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
5419
5420 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
5421 receivers);
5422 if (comp == null) {
5423 continue;
5424 }
5425
5426 final int verifierUid = getUidForVerifier(verifierInfo);
5427 if (verifierUid == -1) {
5428 continue;
5429 }
5430
5431 if (DEBUG_VERIFY) {
5432 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
5433 + " with the correct signature");
5434 }
5435 sufficientVerifiers.add(comp);
5436 verificationState.addSufficientVerifier(verifierUid);
5437 }
5438
5439 return sufficientVerifiers;
5440 }
5441
5442 private int getUidForVerifier(VerifierInfo verifierInfo) {
5443 synchronized (mPackages) {
5444 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
5445 if (pkg == null) {
5446 return -1;
5447 } else if (pkg.mSignatures.length != 1) {
5448 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
5449 + " has more than one signature; ignoring");
5450 return -1;
5451 }
5452
5453 /*
5454 * If the public key of the package's signature does not match
5455 * our expected public key, then this is a different package and
5456 * we should skip.
5457 */
5458
5459 final byte[] expectedPublicKey;
5460 try {
5461 final Signature verifierSig = pkg.mSignatures[0];
5462 final PublicKey publicKey = verifierSig.getPublicKey();
5463 expectedPublicKey = publicKey.getEncoded();
5464 } catch (CertificateException e) {
5465 return -1;
5466 }
5467
5468 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
5469
5470 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
5471 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
5472 + " does not have the expected public key; ignoring");
5473 return -1;
5474 }
5475
5476 return pkg.applicationInfo.uid;
5477 }
5478 }
5479
Christopher Tate1bb69062010-02-19 17:02:12 -08005480 public void finishPackageInstall(int token) {
Kenny Root461ff1f2011-08-09 09:43:03 -07005481 enforceSystemOrRoot("Only the system is allowed to finish installs");
5482
5483 if (DEBUG_INSTALL) {
5484 Slog.v(TAG, "BM finishing package install for " + token);
5485 }
5486
5487 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
Christopher Tate1bb69062010-02-19 17:02:12 -08005488 mHandler.sendMessage(msg);
5489 }
5490
Kenny Root5ab21572011-07-27 11:11:19 -07005491 /**
5492 * Get the verification agent timeout.
5493 *
5494 * @return verification timeout in milliseconds
5495 */
5496 private long getVerificationTimeout() {
5497 return android.provider.Settings.Secure.getLong(mContext.getContentResolver(),
5498 android.provider.Settings.Secure.PACKAGE_VERIFIER_TIMEOUT,
5499 DEFAULT_VERIFICATION_TIMEOUT);
5500 }
5501
5502 /**
rich canningsa6cfe522012-05-21 15:50:56 -07005503 * Get the default verification agent response code.
5504 *
5505 * @return default verification response code
5506 */
5507 private int getDefaultVerificationResponse() {
5508 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
5509 android.provider.Settings.Secure.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
5510 DEFAULT_VERIFICATION_RESPONSE);
5511 }
5512
5513 /**
Kenny Root5ab21572011-07-27 11:11:19 -07005514 * Check whether or not package verification has been enabled.
5515 *
5516 * @return true if verification should be performed
5517 */
5518 private boolean isVerificationEnabled() {
5519 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
5520 android.provider.Settings.Secure.PACKAGE_VERIFIER_ENABLE,
5521 DEFAULT_VERIFY_ENABLE ? 1 : 0) == 1 ? true : false;
5522 }
5523
Matt Finifterf8a98ed2012-05-14 15:43:34 -07005524 /**
5525 * Get the "allow unknown sources" setting.
5526 *
5527 * @return the current "allow unknown sources" setting
5528 */
5529 private int getUnknownSourcesSettings() {
5530 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
5531 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
5532 -1);
5533 }
5534
Kenny Rootf03b45f2011-02-23 17:25:45 -08005535 public void setInstallerPackageName(String targetPackage, String installerPackageName) {
Dianne Hackborn880119b2010-11-18 22:26:40 -08005536 final int uid = Binder.getCallingUid();
Kenny Root447106f2011-03-23 11:00:15 -07005537 // writer
Dianne Hackborn880119b2010-11-18 22:26:40 -08005538 synchronized (mPackages) {
5539 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
5540 if (targetPackageSetting == null) {
5541 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
5542 }
5543
5544 PackageSetting installerPackageSetting;
5545 if (installerPackageName != null) {
5546 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
5547 if (installerPackageSetting == null) {
5548 throw new IllegalArgumentException("Unknown installer package: "
5549 + installerPackageName);
5550 }
5551 } else {
5552 installerPackageSetting = null;
5553 }
5554
5555 Signature[] callerSignature;
Kenny Root447106f2011-03-23 11:00:15 -07005556 Object obj = mSettings.getUserIdLPr(uid);
Dianne Hackborn880119b2010-11-18 22:26:40 -08005557 if (obj != null) {
5558 if (obj instanceof SharedUserSetting) {
5559 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
5560 } else if (obj instanceof PackageSetting) {
5561 callerSignature = ((PackageSetting)obj).signatures.mSignatures;
5562 } else {
5563 throw new SecurityException("Bad object " + obj + " for uid " + uid);
5564 }
5565 } else {
5566 throw new SecurityException("Unknown calling uid " + uid);
5567 }
5568
5569 // Verify: can't set installerPackageName to a package that is
5570 // not signed with the same cert as the caller.
5571 if (installerPackageSetting != null) {
Kenny Root447106f2011-03-23 11:00:15 -07005572 if (compareSignatures(callerSignature,
Dianne Hackborn880119b2010-11-18 22:26:40 -08005573 installerPackageSetting.signatures.mSignatures)
5574 != PackageManager.SIGNATURE_MATCH) {
5575 throw new SecurityException(
5576 "Caller does not have same cert as new installer package "
5577 + installerPackageName);
5578 }
5579 }
5580
5581 // Verify: if target already has an installer package, it must
5582 // be signed with the same cert as the caller.
5583 if (targetPackageSetting.installerPackageName != null) {
5584 PackageSetting setting = mSettings.mPackages.get(
5585 targetPackageSetting.installerPackageName);
5586 // If the currently set package isn't valid, then it's always
5587 // okay to change it.
5588 if (setting != null) {
Kenny Root447106f2011-03-23 11:00:15 -07005589 if (compareSignatures(callerSignature,
Dianne Hackborn880119b2010-11-18 22:26:40 -08005590 setting.signatures.mSignatures)
5591 != PackageManager.SIGNATURE_MATCH) {
5592 throw new SecurityException(
5593 "Caller does not have same cert as old installer package "
5594 + targetPackageSetting.installerPackageName);
5595 }
5596 }
5597 }
5598
5599 // Okay!
5600 targetPackageSetting.installerPackageName = installerPackageName;
5601 scheduleWriteSettingsLocked();
5602 }
5603 }
5604
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005605 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005606 // Queue up an async operation since the package installation may take a little while.
5607 mHandler.post(new Runnable() {
5608 public void run() {
5609 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005610 // Result object to be returned
5611 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005612 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005613 res.uid = -1;
5614 res.pkg = null;
5615 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005616 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07005617 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005618 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005619 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005620 }
Kenny Root6dceb882012-04-12 14:23:49 -07005621 args.doPostInstall(res.returnCode, res.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005622 }
Christopher Tate1bb69062010-02-19 17:02:12 -08005623
5624 // A restore should be performed at this point if (a) the install
5625 // succeeded, (b) the operation is not an update, and (c) the new
5626 // package has a backupAgent defined.
5627 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08005628 boolean doRestore = (!update
5629 && res.pkg != null
5630 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08005631
5632 // Set up the post-install work request bookkeeping. This will be used
5633 // and cleaned up by the post-install event handling regardless of whether
5634 // there's a restore pass performed. Token values are >= 1.
5635 int token;
5636 if (mNextInstallToken < 0) mNextInstallToken = 1;
5637 token = mNextInstallToken++;
5638
5639 PostInstallData data = new PostInstallData(args, res);
5640 mRunningInstalls.put(token, data);
5641 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
5642
5643 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
5644 // Pass responsibility to the Backup Manager. It will perform a
5645 // restore if appropriate, then pass responsibility back to the
5646 // Package Manager to run the post-install observer callbacks
5647 // and broadcasts.
5648 IBackupManager bm = IBackupManager.Stub.asInterface(
5649 ServiceManager.getService(Context.BACKUP_SERVICE));
5650 if (bm != null) {
5651 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
5652 + " to BM for possible restore");
5653 try {
5654 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
5655 } catch (RemoteException e) {
5656 // can't happen; the backup manager is local
5657 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005658 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08005659 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005660 }
Christopher Tate1bb69062010-02-19 17:02:12 -08005661 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005662 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08005663 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005665 }
Christopher Tate1bb69062010-02-19 17:02:12 -08005666
5667 if (!doRestore) {
5668 // No restore possible, or the Backup Manager was mysteriously not
5669 // available -- just fire the post-install work request directly.
5670 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
5671 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
5672 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005674 }
5675 });
5676 }
5677
Kenny Root5ab21572011-07-27 11:11:19 -07005678 private abstract class HandlerParams {
5679 private static final int MAX_RETRIES = 4;
5680
5681 /**
5682 * Number of times startCopy() has been attempted and had a non-fatal
5683 * error.
5684 */
5685 private int mRetries = 0;
5686
Dianne Hackborn7d608422011-08-07 16:24:18 -07005687 final boolean startCopy() {
5688 boolean res;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005689 try {
Kenny Root5ab21572011-07-27 11:11:19 -07005690 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy");
5691
5692 if (++mRetries > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005693 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005694 mHandler.sendEmptyMessage(MCS_GIVE_UP);
5695 handleServiceError();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005696 return false;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005697 } else {
5698 handleStartCopy();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005699 res = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005700 }
5701 } catch (RemoteException e) {
Kenny Root5ab21572011-07-27 11:11:19 -07005702 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005703 mHandler.sendEmptyMessage(MCS_RECONNECT);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005704 res = false;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005705 }
5706 handleReturnCode();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005707 return res;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005708 }
5709
5710 final void serviceError() {
Kenny Root5ab21572011-07-27 11:11:19 -07005711 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005712 handleServiceError();
5713 handleReturnCode();
5714 }
Kenny Root5ab21572011-07-27 11:11:19 -07005715
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005716 abstract void handleStartCopy() throws RemoteException;
5717 abstract void handleServiceError();
5718 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005719 }
5720
Kenny Root366949c2011-01-14 17:18:14 -08005721 class MeasureParams extends HandlerParams {
5722 private final PackageStats mStats;
5723 private boolean mSuccess;
5724
5725 private final IPackageStatsObserver mObserver;
5726
Kenny Roota69b7eb2012-05-14 14:47:06 -07005727 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
Kenny Root366949c2011-01-14 17:18:14 -08005728 mObserver = observer;
5729 mStats = stats;
Kenny Root366949c2011-01-14 17:18:14 -08005730 }
5731
5732 @Override
5733 void handleStartCopy() throws RemoteException {
Kenny Roota69b7eb2012-05-14 14:47:06 -07005734 synchronized (mInstallLock) {
5735 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats);
5736 }
Kenny Root366949c2011-01-14 17:18:14 -08005737
Kenny Roota69b7eb2012-05-14 14:47:06 -07005738 final boolean mounted;
Kenny Root366949c2011-01-14 17:18:14 -08005739 if (Environment.isExternalStorageEmulated()) {
5740 mounted = true;
5741 } else {
5742 final String status = Environment.getExternalStorageState();
5743
5744 mounted = status.equals(Environment.MEDIA_MOUNTED)
5745 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
5746 }
5747
5748 if (mounted) {
5749 final File externalCacheDir = Environment
5750 .getExternalStorageAppCacheDirectory(mStats.packageName);
5751 final long externalCacheSize = mContainerService
5752 .calculateDirectorySize(externalCacheDir.getPath());
5753 mStats.externalCacheSize = externalCacheSize;
5754
5755 final File externalDataDir = Environment
5756 .getExternalStorageAppDataDirectory(mStats.packageName);
5757 long externalDataSize = mContainerService.calculateDirectorySize(externalDataDir
5758 .getPath());
5759
5760 if (externalCacheDir.getParentFile().equals(externalDataDir)) {
5761 externalDataSize -= externalCacheSize;
5762 }
5763 mStats.externalDataSize = externalDataSize;
5764
5765 final File externalMediaDir = Environment
5766 .getExternalStorageAppMediaDirectory(mStats.packageName);
5767 mStats.externalMediaSize = mContainerService
Kenny Rootc7624d92011-02-23 16:25:25 -08005768 .calculateDirectorySize(externalMediaDir.getPath());
Kenny Rootbcd6c962011-01-17 11:21:49 -08005769
5770 final File externalObbDir = Environment
5771 .getExternalStorageAppObbDirectory(mStats.packageName);
5772 mStats.externalObbSize = mContainerService.calculateDirectorySize(externalObbDir
5773 .getPath());
Kenny Root366949c2011-01-14 17:18:14 -08005774 }
5775 }
5776
5777 @Override
5778 void handleReturnCode() {
5779 if (mObserver != null) {
5780 try {
5781 mObserver.onGetStatsCompleted(mStats, mSuccess);
5782 } catch (RemoteException e) {
5783 Slog.i(TAG, "Observer no longer exists.");
5784 }
5785 }
5786 }
5787
5788 @Override
5789 void handleServiceError() {
5790 Slog.e(TAG, "Could not measure application " + mStats.packageName
5791 + " external storage");
5792 }
5793 }
5794
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005795 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005796 final IPackageInstallObserver observer;
5797 int flags;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07005798
5799 private final Uri mPackageURI;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005800 final String installerPackageName;
Kenny Root5ab21572011-07-27 11:11:19 -07005801 final Uri verificationURI;
5802 final ManifestDigest manifestDigest;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005803 private InstallArgs mArgs;
5804 private int mRet;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07005805 private File mTempPackage;
5806 final ContainerEncryptionParams encryptionParams;
Kenny Root5ab21572011-07-27 11:11:19 -07005807
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005808 InstallParams(Uri packageURI,
5809 IPackageInstallObserver observer, int flags,
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07005810 String installerPackageName, Uri verificationURI, ManifestDigest manifestDigest,
Rich Canningse1d7c712012-08-08 12:46:06 -07005811 ContainerEncryptionParams encryptionParams) {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07005812 this.mPackageURI = packageURI;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005813 this.flags = flags;
5814 this.observer = observer;
5815 this.installerPackageName = installerPackageName;
Kenny Root5ab21572011-07-27 11:11:19 -07005816 this.verificationURI = verificationURI;
5817 this.manifestDigest = manifestDigest;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07005818 this.encryptionParams = encryptionParams;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005819 }
5820
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08005821 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
5822 String packageName = pkgLite.packageName;
5823 int installLocation = pkgLite.installLocation;
5824 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Kenny Root447106f2011-03-23 11:00:15 -07005825 // reader
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08005826 synchronized (mPackages) {
5827 PackageParser.Package pkg = mPackages.get(packageName);
5828 if (pkg != null) {
5829 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5830 // Check for updated system application.
5831 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5832 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005833 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08005834 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
5835 }
5836 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
5837 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08005838 if (onSd) {
5839 // Install flag overrides everything.
5840 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
5841 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07005842 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08005843 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
5844 // Application explicitly specified internal.
5845 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
5846 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
5847 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07005848 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08005849 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07005850 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07005851 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
5852 }
5853 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08005854 }
5855 }
5856 } else {
5857 // Invalid install. Return error code
5858 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
5859 }
5860 }
5861 }
5862 // All the special cases have been taken care of.
5863 // Return result based on recommended install location.
5864 if (onSd) {
5865 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
5866 }
5867 return pkgLite.recommendedInstallLocation;
5868 }
5869
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005870 /*
5871 * Invoke remote method to get package information and install
5872 * location values. Override install location based on default
5873 * policy if needed and then create install arguments based
5874 * on the install location.
5875 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005876 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08005877 int ret = PackageManager.INSTALL_SUCCEEDED;
Kenny Root05ca4c92011-09-15 10:36:25 -07005878 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
5879 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
5880 PackageInfoLite pkgLite = null;
5881
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07005882 if (onInt && onSd) {
5883 // Check if both bits are set.
5884 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
5885 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005886 } else {
Kenny Root62e1b4e2011-03-14 17:13:39 -07005887 final long lowThreshold;
5888
5889 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
5890 .getService(DeviceStorageMonitorService.SERVICE);
5891 if (dsm == null) {
5892 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
5893 lowThreshold = 0L;
5894 } else {
5895 lowThreshold = dsm.getMemoryLowThreshold();
5896 }
5897
Kenny Root11128572010-10-11 10:51:32 -07005898 try {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07005899 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
Kenny Root11128572010-10-11 10:51:32 -07005900 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root11128572010-10-11 10:51:32 -07005901
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07005902 final File packageFile;
5903 if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
5904 ParcelFileDescriptor out = null;
5905
5906 mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
5907 if (mTempPackage != null) {
5908 try {
5909 out = ParcelFileDescriptor.open(mTempPackage,
5910 ParcelFileDescriptor.MODE_READ_WRITE);
5911 } catch (FileNotFoundException e) {
5912 Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
5913 }
5914
5915 // Make a temporary file for decryption.
5916 ret = mContainerService
5917 .copyResource(mPackageURI, encryptionParams, out);
5918
5919 packageFile = mTempPackage;
5920
5921 FileUtils.setPermissions(packageFile.getAbsolutePath(),
5922 FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IROTH,
5923 -1, -1);
5924 } else {
5925 packageFile = null;
5926 }
5927 } else {
5928 packageFile = new File(mPackageURI.getPath());
5929 }
5930
5931 if (packageFile != null) {
5932 // Remote call to find out default install location
5933 pkgLite = mContainerService.getMinimalPackageInfo(
5934 packageFile.getAbsolutePath(), flags, lowThreshold);
5935 }
5936 } finally {
5937 mContext.revokeUriPermission(mPackageURI,
5938 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5939 }
5940 }
5941
5942 if (ret == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005943 int loc = pkgLite.recommendedInstallLocation;
Kenny Root1ebd74a2011-08-03 15:09:44 -07005944 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08005945 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Kenny Root1ebd74a2011-08-03 15:09:44 -07005946 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08005947 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
Kenny Root1ebd74a2011-08-03 15:09:44 -07005948 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005949 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5950 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
5951 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Kenny Root1ebd74a2011-08-03 15:09:44 -07005952 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
5953 ret = PackageManager.INSTALL_FAILED_INVALID_URI;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005954 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
Kenny Root1ebd74a2011-08-03 15:09:44 -07005955 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005956 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005957 // Override with defaults if needed.
5958 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07005959 if (!onSd && !onInt) {
5960 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005961 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
5962 // Set the flag to install on external media.
5963 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07005964 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005965 } else {
5966 // Make sure the flag for installing on external
5967 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07005968 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005969 flags &= ~PackageManager.INSTALL_EXTERNAL;
5970 }
5971 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005972 }
5973 }
Kenny Root5ab21572011-07-27 11:11:19 -07005974
5975 final InstallArgs args = createInstallArgs(this);
Kenny Root05ca4c92011-09-15 10:36:25 -07005976 mArgs = args;
5977
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005978 if (ret == PackageManager.INSTALL_SUCCEEDED) {
Kenny Root5ab21572011-07-27 11:11:19 -07005979 /*
5980 * Determine if we have any installed package verifiers. If we
5981 * do, then we'll defer to them to verify the packages.
5982 */
Kenny Root05ca4c92011-09-15 10:36:25 -07005983 final int requiredUid = mRequiredVerifierPackage == null ? -1
Amith Yamasani483f3b02012-03-13 16:08:00 -07005984 : getPackageUid(mRequiredVerifierPackage, 0);
Kenny Root05ca4c92011-09-15 10:36:25 -07005985 if (requiredUid != -1 && isVerificationEnabled()) {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07005986 final Intent verification = new Intent(
5987 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
5988 verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
Kenny Root05ca4c92011-09-15 10:36:25 -07005989 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root5ab21572011-07-27 11:11:19 -07005990
Kenny Root05ca4c92011-09-15 10:36:25 -07005991 final List<ResolveInfo> receivers = queryIntentReceivers(verification, null,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005992 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
Kenny Root05ca4c92011-09-15 10:36:25 -07005993
5994 if (DEBUG_VERIFY) {
Kenny Root5ab21572011-07-27 11:11:19 -07005995 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
Kenny Root05ca4c92011-09-15 10:36:25 -07005996 + verification.toString() + " with " + pkgLite.verifiers.length
5997 + " optional verifiers");
Kenny Root5ab21572011-07-27 11:11:19 -07005998 }
5999
6000 final int verificationId = mPendingVerificationToken++;
6001
6002 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
6003
6004 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
6005 installerPackageName);
6006
6007 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
6008
6009 if (verificationURI != null) {
6010 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
6011 verificationURI);
6012 }
6013
Kenny Root05ca4c92011-09-15 10:36:25 -07006014 final PackageVerificationState verificationState = new PackageVerificationState(
6015 requiredUid, args);
6016
6017 mPendingVerification.append(verificationId, verificationState);
6018
6019 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
6020 receivers, verificationState);
Kenny Root5ab21572011-07-27 11:11:19 -07006021
6022 /*
Kenny Root05ca4c92011-09-15 10:36:25 -07006023 * If any sufficient verifiers were listed in the package
6024 * manifest, attempt to ask them.
Kenny Root5ab21572011-07-27 11:11:19 -07006025 */
Kenny Root05ca4c92011-09-15 10:36:25 -07006026 if (sufficientVerifiers != null) {
6027 final int N = sufficientVerifiers.size();
6028 if (N == 0) {
6029 Slog.i(TAG, "Additional verifiers required, but none installed.");
6030 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
6031 } else {
6032 for (int i = 0; i < N; i++) {
6033 final ComponentName verifierComponent = sufficientVerifiers.get(i);
6034
6035 final Intent sufficientIntent = new Intent(verification);
6036 sufficientIntent.setComponent(verifierComponent);
6037
6038 mContext.sendBroadcast(sufficientIntent);
6039 }
6040 }
6041 }
6042
6043 final ComponentName requiredVerifierComponent = matchComponentForVerifier(
6044 mRequiredVerifierPackage, receivers);
6045 if (ret == PackageManager.INSTALL_SUCCEEDED
6046 && mRequiredVerifierPackage != null) {
6047 /*
6048 * Send the intent to the required verification agent,
6049 * but only start the verification timeout after the
6050 * target BroadcastReceivers have run.
6051 */
6052 verification.setComponent(requiredVerifierComponent);
6053 mContext.sendOrderedBroadcast(verification,
6054 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
6055 new BroadcastReceiver() {
6056 @Override
6057 public void onReceive(Context context, Intent intent) {
6058 final Message msg = mHandler
6059 .obtainMessage(CHECK_PENDING_VERIFICATION);
6060 msg.arg1 = verificationId;
6061 mHandler.sendMessageDelayed(msg, getVerificationTimeout());
6062 }
6063 }, null, 0, null, null);
6064
6065 /*
6066 * We don't want the copy to proceed until verification
6067 * succeeds, so null out this field.
6068 */
6069 mArgs = null;
6070 }
Kenny Root5ab21572011-07-27 11:11:19 -07006071 } else {
Kenny Root05ca4c92011-09-15 10:36:25 -07006072 /*
6073 * No package verification is enabled, so immediately start
6074 * the remote call to initiate copy using temporary file.
6075 */
Kenny Root5ab21572011-07-27 11:11:19 -07006076 ret = args.copyApk(mContainerService, true);
6077 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006078 }
Kenny Root5ab21572011-07-27 11:11:19 -07006079
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006080 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006081 }
6082
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006083 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006084 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07006085 // If mArgs is null, then MCS couldn't be reached. When it
6086 // reconnects, it will try again to install. At that point, this
6087 // will succeed.
6088 if (mArgs != null) {
6089 processPendingInstall(mArgs, mRet);
6090 }
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006091
6092 if (mTempPackage != null) {
6093 if (!mTempPackage.delete()) {
6094 Slog.w(TAG, "Couldn't delete temporary file: "
6095 + mTempPackage.getAbsolutePath());
6096 }
6097 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006098 }
6099
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006100 @Override
6101 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006102 mArgs = createInstallArgs(this);
6103 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006104 }
Kenny Root6dceb882012-04-12 14:23:49 -07006105
6106 public boolean isForwardLocked() {
6107 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
6108 }
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006109
6110 public Uri getPackageUri() {
6111 if (mTempPackage != null) {
6112 return Uri.fromFile(mTempPackage);
6113 } else {
6114 return mPackageURI;
6115 }
6116 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006117 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006118
6119 /*
6120 * Utility class used in movePackage api.
6121 * srcArgs and targetArgs are not set for invalid flags and make
6122 * sure to do null checks when invoking methods on them.
6123 * We probably want to return ErrorPrams for both failed installs
6124 * and moves.
6125 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006126 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006127 final IPackageMoveObserver observer;
6128 final int flags;
6129 final String packageName;
6130 final InstallArgs srcArgs;
6131 final InstallArgs targetArgs;
Kenny Root6dceb882012-04-12 14:23:49 -07006132 int uid;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006133 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07006134
6135 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
Kenny Root6dceb882012-04-12 14:23:49 -07006136 String packageName, String dataDir, int uid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006137 this.srcArgs = srcArgs;
6138 this.observer = observer;
6139 this.flags = flags;
6140 this.packageName = packageName;
Kenny Root6dceb882012-04-12 14:23:49 -07006141 this.uid = uid;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006142 if (srcArgs != null) {
6143 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07006144 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006145 } else {
6146 targetArgs = null;
6147 }
6148 }
6149
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006150 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006151 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6152 // Check for storage space on target medium
6153 if (!targetArgs.checkFreeStorage(mContainerService)) {
6154 Log.w(TAG, "Insufficient storage to install");
6155 return;
6156 }
Kenny Rootbf023582012-05-02 16:56:15 -07006157
6158 mRet = srcArgs.doPreCopy();
6159 if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6160 return;
6161 }
6162
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006163 mRet = targetArgs.copyApk(mContainerService, false);
Kenny Rootbf023582012-05-02 16:56:15 -07006164 if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6165 srcArgs.doPostCopy(uid);
6166 return;
6167 }
6168
6169 mRet = srcArgs.doPostCopy(uid);
6170 if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6171 return;
6172 }
6173
6174 mRet = targetArgs.doPreInstall(mRet);
6175 if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6176 return;
6177 }
6178
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006179 if (DEBUG_SD_INSTALL) {
6180 StringBuilder builder = new StringBuilder();
6181 if (srcArgs != null) {
6182 builder.append("src: ");
6183 builder.append(srcArgs.getCodePath());
6184 }
6185 if (targetArgs != null) {
6186 builder.append(" target : ");
6187 builder.append(targetArgs.getCodePath());
6188 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006189 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006190 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006191 }
6192
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006193 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006194 void handleReturnCode() {
Kenny Root6dceb882012-04-12 14:23:49 -07006195 targetArgs.doPostInstall(mRet, uid);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006196 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
6197 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
6198 currentStatus = PackageManager.MOVE_SUCCEEDED;
6199 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
6200 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
6201 }
6202 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006203 }
6204
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006205 @Override
6206 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006207 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006208 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006209 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006210
Kenny Root6dceb882012-04-12 14:23:49 -07006211 /**
6212 * Used during creation of InstallArgs
6213 *
6214 * @param flags package installation flags
6215 * @return true if should be installed on external storage
6216 */
6217 private static boolean installOnSd(int flags) {
6218 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
6219 return false;
6220 }
6221 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
6222 return true;
6223 }
6224 return false;
6225 }
6226
6227 /**
6228 * Used during creation of InstallArgs
6229 *
6230 * @param flags package installation flags
6231 * @return true if should be installed as forward locked
6232 */
6233 private static boolean installForwardLocked(int flags) {
6234 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
6235 }
6236
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006237 private InstallArgs createInstallArgs(InstallParams params) {
Kenny Root6dceb882012-04-12 14:23:49 -07006238 if (installOnSd(params.flags) || params.isForwardLocked()) {
6239 return new AsecInstallArgs(params);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006240 } else {
6241 return new FileInstallArgs(params);
6242 }
6243 }
6244
Kenny Root85387d72010-08-26 10:13:11 -07006245 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
6246 String nativeLibraryPath) {
Kenny Root84e35ea2012-06-06 16:05:05 -07006247 final boolean isInAsec;
6248 if (installOnSd(flags)) {
6249 /* Apps on SD card are always in ASEC containers. */
6250 isInAsec = true;
6251 } else if (installForwardLocked(flags)
6252 && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
6253 /*
6254 * Forward-locked apps are only in ASEC containers if they're the
6255 * new style
6256 */
6257 isInAsec = true;
6258 } else {
6259 isInAsec = false;
6260 }
6261
6262 if (isInAsec) {
Kenny Root6dceb882012-04-12 14:23:49 -07006263 return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
Kenny Rootbf023582012-05-02 16:56:15 -07006264 installOnSd(flags), installForwardLocked(flags));
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006265 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006266 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006267 }
6268 }
6269
Kenny Root85387d72010-08-26 10:13:11 -07006270 // Used by package mover
6271 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Kenny Root6dceb882012-04-12 14:23:49 -07006272 if (installOnSd(flags) || installForwardLocked(flags)) {
Kenny Rootbf023582012-05-02 16:56:15 -07006273 String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
6274 + AsecInstallArgs.RES_FILE_NAME);
6275 return new AsecInstallArgs(packageURI, cid, installOnSd(flags),
6276 installForwardLocked(flags));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006277 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006278 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006279 }
6280 }
6281
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006282 static abstract class InstallArgs {
6283 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006284 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006285 final int flags;
6286 final Uri packageURI;
6287 final String installerPackageName;
Kenny Root5ab21572011-07-27 11:11:19 -07006288 final ManifestDigest manifestDigest;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006289
Kenny Root5ab21572011-07-27 11:11:19 -07006290 InstallArgs(Uri packageURI, IPackageInstallObserver observer, int flags,
6291 String installerPackageName, ManifestDigest manifestDigest) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006292 this.packageURI = packageURI;
6293 this.flags = flags;
6294 this.observer = observer;
6295 this.installerPackageName = installerPackageName;
Kenny Root5ab21572011-07-27 11:11:19 -07006296 this.manifestDigest = manifestDigest;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006297 }
6298
6299 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006300 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006301 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006302 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Kenny Root6dceb882012-04-12 14:23:49 -07006303
6304 abstract int doPostInstall(int status, int uid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006305 abstract String getCodePath();
6306 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07006307 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006308 // Need installer lock especially for dex file removal.
6309 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006310 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006311 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Kenny Root6dceb882012-04-12 14:23:49 -07006312
Kenny Rootbf023582012-05-02 16:56:15 -07006313 /**
6314 * Called before the source arguments are copied. This is used mostly
6315 * for MoveParams when it needs to read the source file to put it in the
6316 * destination.
6317 */
6318 int doPreCopy() {
6319 return PackageManager.INSTALL_SUCCEEDED;
6320 }
6321
6322 /**
6323 * Called after the source arguments are copied. This is used mostly for
6324 * MoveParams when it needs to read the source file to put it in the
6325 * destination.
6326 *
6327 * @return
6328 */
6329 int doPostCopy(int uid) {
6330 return PackageManager.INSTALL_SUCCEEDED;
6331 }
6332
Kenny Root6dceb882012-04-12 14:23:49 -07006333 protected boolean isFwdLocked() {
6334 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
6335 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006336 }
6337
6338 class FileInstallArgs extends InstallArgs {
6339 File installDir;
6340 String codeFileName;
6341 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07006342 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006343 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006344
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006345 FileInstallArgs(InstallParams params) {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006346 super(params.getPackageUri(), params.observer, params.flags,
6347 params.installerPackageName, params.manifestDigest);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006348 }
6349
Kenny Root85387d72010-08-26 10:13:11 -07006350 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Kenny Root5ab21572011-07-27 11:11:19 -07006351 super(null, null, 0, null, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006352 File codeFile = new File(fullCodePath);
6353 installDir = codeFile.getParentFile();
6354 codeFileName = fullCodePath;
6355 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07006356 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006357 }
6358
Kenny Root85387d72010-08-26 10:13:11 -07006359 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Kenny Root5ab21572011-07-27 11:11:19 -07006360 super(packageURI, null, 0, null, null);
Kenny Root85387d72010-08-26 10:13:11 -07006361 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006362 String apkName = getNextCodePath(null, pkgName, ".apk");
6363 codeFileName = new File(installDir, apkName + ".apk").getPath();
6364 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07006365 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006366 }
6367
Kenny Root11128572010-10-11 10:51:32 -07006368 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
Kenny Root62e1b4e2011-03-14 17:13:39 -07006369 final long lowThreshold;
6370
6371 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
6372 .getService(DeviceStorageMonitorService.SERVICE);
6373 if (dsm == null) {
6374 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
6375 lowThreshold = 0L;
6376 } else {
6377 if (dsm.isMemoryLow()) {
6378 Log.w(TAG, "Memory is reported as being too low; aborting package install");
6379 return false;
6380 }
6381
6382 lowThreshold = dsm.getMemoryLowThreshold();
6383 }
6384
Kenny Root11128572010-10-11 10:51:32 -07006385 try {
6386 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
6387 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root6dceb882012-04-12 14:23:49 -07006388 return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
Kenny Root11128572010-10-11 10:51:32 -07006389 } finally {
6390 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
6391 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006392 }
6393
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006394 String getCodePath() {
6395 return codeFileName;
6396 }
6397
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006398 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07006399 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006400 codeFileName = createTempPackageFile(installDir).getPath();
6401 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006402 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006403 }
6404
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006405 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006406 if (temp) {
6407 // Generate temp file name
6408 createCopyFile();
6409 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006410 // Get a ParcelFileDescriptor to write to the output file
6411 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006412 if (!created) {
6413 try {
6414 codeFile.createNewFile();
6415 // Set permissions
6416 if (!setPermissions()) {
6417 // Failed setting permissions.
6418 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6419 }
6420 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006421 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006422 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6423 }
6424 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006425 ParcelFileDescriptor out = null;
6426 try {
Kenny Root85387d72010-08-26 10:13:11 -07006427 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006428 } catch (FileNotFoundException e) {
Kenny Rootf5121a92011-08-10 16:23:32 -07006429 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006430 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6431 }
6432 // Copy the resource now
6433 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6434 try {
Kenny Root11128572010-10-11 10:51:32 -07006435 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
6436 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006437 ret = imcs.copyResource(packageURI, null, out);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006438 } finally {
Kenny Root2782a472012-04-14 21:48:21 -07006439 IoUtils.closeQuietly(out);
Kenny Root11128572010-10-11 10:51:32 -07006440 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006441 }
Kenny Root85387d72010-08-26 10:13:11 -07006442
Kenny Root2782a472012-04-14 21:48:21 -07006443 if (isFwdLocked()) {
6444 final File destResourceFile = new File(getResourcePath());
6445
6446 // Copy the public files
6447 try {
6448 PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
6449 } catch (IOException e) {
6450 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
6451 + " forward-locked app.");
6452 destResourceFile.delete();
6453 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6454 }
6455 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006456 return ret;
6457 }
6458
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006459 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006460 if (status != PackageManager.INSTALL_SUCCEEDED) {
6461 cleanUp();
6462 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006463 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006464 }
6465
6466 boolean doRename(int status, final String pkgName, String oldCodePath) {
6467 if (status != PackageManager.INSTALL_SUCCEEDED) {
6468 cleanUp();
6469 return false;
6470 } else {
Kenny Root2782a472012-04-14 21:48:21 -07006471 final File oldCodeFile = new File(getCodePath());
6472 final File oldResourceFile = new File(getResourcePath());
6473
6474 // Rename APK file based on packageName
6475 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
6476 final File newCodeFile = new File(installDir, apkName + ".apk");
6477 if (!oldCodeFile.renameTo(newCodeFile)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006478 return false;
6479 }
Kenny Root2782a472012-04-14 21:48:21 -07006480 codeFileName = newCodeFile.getPath();
6481
6482 // Rename public resource file if it's forward-locked.
6483 final File newResFile = new File(getResourcePathFromCodePath());
6484 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
6485 return false;
6486 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006487 resourceFileName = getResourcePathFromCodePath();
Kenny Root2782a472012-04-14 21:48:21 -07006488
6489 // Attempt to set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006490 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006491 return false;
6492 }
Kenny Root2782a472012-04-14 21:48:21 -07006493
rpcraig554cb0c2012-07-05 06:41:43 -04006494 if (!SELinux.restorecon(newCodeFile)) {
6495 return false;
6496 }
6497
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006498 return true;
6499 }
6500 }
6501
Kenny Root6dceb882012-04-12 14:23:49 -07006502 int doPostInstall(int status, int uid) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006503 if (status != PackageManager.INSTALL_SUCCEEDED) {
6504 cleanUp();
6505 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006506 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006507 }
6508
6509 String getResourcePath() {
6510 return resourceFileName;
6511 }
6512
Kenny Root2782a472012-04-14 21:48:21 -07006513 private String getResourcePathFromCodePath() {
6514 final String codePath = getCodePath();
6515 if (isFwdLocked()) {
6516 final StringBuilder sb = new StringBuilder();
6517
6518 sb.append(mAppInstallDir.getPath());
6519 sb.append('/');
6520 sb.append(getApkName(codePath));
6521 sb.append(".zip");
6522
6523 /*
6524 * If our APK is a temporary file, mark the resource as a
6525 * temporary file as well so it can be cleaned up after
6526 * catastrophic failure.
6527 */
6528 if (codePath.endsWith(".tmp")) {
6529 sb.append(".tmp");
6530 }
6531
6532 return sb.toString();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006533 } else {
6534 return codePath;
6535 }
6536 }
6537
Kenny Root85387d72010-08-26 10:13:11 -07006538 @Override
6539 String getNativeLibraryPath() {
6540 return libraryPath;
6541 }
6542
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006543 private boolean cleanUp() {
6544 boolean ret = true;
6545 String sourceDir = getCodePath();
6546 String publicSourceDir = getResourcePath();
6547 if (sourceDir != null) {
6548 File sourceFile = new File(sourceDir);
6549 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006550 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006551 ret = false;
6552 }
6553 // Delete application's code and resources
6554 sourceFile.delete();
6555 }
6556 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
6557 final File publicSourceFile = new File(publicSourceDir);
6558 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006559 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006560 }
6561 if (publicSourceFile.exists()) {
6562 publicSourceFile.delete();
6563 }
6564 }
6565 return ret;
6566 }
6567
6568 void cleanUpResourcesLI() {
6569 String sourceDir = getCodePath();
Jeff Brown5d6d90f2011-07-11 13:04:53 -07006570 if (cleanUp()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006571 int retCode = mInstaller.rmdex(sourceDir);
6572 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006573 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006574 + " at location "
6575 + sourceDir + ", retcode=" + retCode);
6576 // we don't consider this to be a failure of the core package deletion
6577 }
6578 }
6579 }
6580
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006581 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006582 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07006583 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006584 final int filePermissions =
6585 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
6586 |FileUtils.S_IROTH;
6587 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
6588 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006589 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006590 getCodePath()
6591 + ". The return code was: " + retCode);
6592 // TODO Define new internal error
6593 return false;
6594 }
6595 return true;
6596 }
6597 return true;
6598 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006599
6600 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07006601 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006602 cleanUpResourcesLI();
6603 return true;
6604 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006605 }
6606
Kenny Root51a573c2012-05-17 13:30:28 -07006607 private boolean isAsecExternal(String cid) {
6608 final String asecPath = PackageHelper.getSdFilesystem(cid);
6609 return !asecPath.startsWith(mAsecInternalPath);
6610 }
6611
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07006612 /**
6613 * Extract the MountService "container ID" from the full code path of an
6614 * .apk.
6615 */
6616 static String cidFromCodePath(String fullCodePath) {
6617 int eidx = fullCodePath.lastIndexOf("/");
6618 String subStr1 = fullCodePath.substring(0, eidx);
6619 int sidx = subStr1.lastIndexOf("/");
6620 return subStr1.substring(sidx+1, eidx);
6621 }
6622
Kenny Root6dceb882012-04-12 14:23:49 -07006623 class AsecInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006624 static final String RES_FILE_NAME = "pkg.apk";
Kenny Root6dceb882012-04-12 14:23:49 -07006625 static final String PUBLIC_RES_FILE_NAME = "res.zip";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006626
Kenny Root85387d72010-08-26 10:13:11 -07006627 String cid;
6628 String packagePath;
Kenny Root6dceb882012-04-12 14:23:49 -07006629 String resourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07006630 String libraryPath;
6631
Kenny Root6dceb882012-04-12 14:23:49 -07006632 AsecInstallArgs(InstallParams params) {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006633 super(params.getPackageUri(), params.observer, params.flags,
6634 params.installerPackageName, params.manifestDigest);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006635 }
6636
Kenny Root6dceb882012-04-12 14:23:49 -07006637 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
Kenny Rootbf023582012-05-02 16:56:15 -07006638 boolean isExternal, boolean isForwardLocked) {
6639 super(null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
6640 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), null, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006641 // Extract cid from fullCodePath
6642 int eidx = fullCodePath.lastIndexOf("/");
6643 String subStr1 = fullCodePath.substring(0, eidx);
6644 int sidx = subStr1.lastIndexOf("/");
6645 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07006646 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006647 }
6648
Kenny Rootc7a89992012-06-05 15:13:17 -07006649 AsecInstallArgs(String cid, boolean isForwardLocked) {
6650 super(null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
6651 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), null, null);
Dianne Hackbornaa77de12010-05-14 22:33:54 -07006652 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07006653 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006654 }
6655
Kenny Rootbf023582012-05-02 16:56:15 -07006656 AsecInstallArgs(Uri packageURI, String cid, boolean isExternal, boolean isForwardLocked) {
6657 super(packageURI, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
6658 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), null, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006659 this.cid = cid;
6660 }
6661
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006662 void createCopyFile() {
6663 cid = getTempContainerId();
6664 }
6665
Kenny Root11128572010-10-11 10:51:32 -07006666 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
6667 try {
6668 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
6669 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root6dceb882012-04-12 14:23:49 -07006670 return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
Kenny Root11128572010-10-11 10:51:32 -07006671 } finally {
6672 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
6673 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006674 }
6675
Kenny Root6dceb882012-04-12 14:23:49 -07006676 private final boolean isExternal() {
6677 return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
6678 }
6679
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006680 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006681 if (temp) {
6682 createCopyFile();
Kenny Rootf5121a92011-08-10 16:23:32 -07006683 } else {
6684 /*
6685 * Pre-emptively destroy the container since it's destroyed if
6686 * copying fails due to it existing anyway.
6687 */
6688 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006689 }
Kenny Root11128572010-10-11 10:51:32 -07006690
6691 final String newCachePath;
6692 try {
6693 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
6694 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root6dceb882012-04-12 14:23:49 -07006695 newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
6696 RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
Kenny Root11128572010-10-11 10:51:32 -07006697 } finally {
6698 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
6699 }
6700
Kenny Root85387d72010-08-26 10:13:11 -07006701 if (newCachePath != null) {
6702 setCachePath(newCachePath);
6703 return PackageManager.INSTALL_SUCCEEDED;
6704 } else {
6705 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
6706 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006707 }
6708
6709 @Override
6710 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07006711 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006712 }
6713
6714 @Override
6715 String getResourcePath() {
Kenny Root6dceb882012-04-12 14:23:49 -07006716 return resourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07006717 }
6718
6719 @Override
6720 String getNativeLibraryPath() {
6721 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006722 }
6723
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006724 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006725 if (status != PackageManager.INSTALL_SUCCEEDED) {
6726 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08006727 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006728 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08006729 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006730 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07006731 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
6732 Process.SYSTEM_UID);
6733 if (newCachePath != null) {
6734 setCachePath(newCachePath);
6735 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006736 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
6737 }
6738 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006739 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006740 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006741 }
6742
6743 boolean doRename(int status, final String pkgName,
6744 String oldCodePath) {
6745 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006746 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006747 if (PackageHelper.isContainerMounted(cid)) {
6748 // Unmount the container
6749 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006750 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006751 return false;
6752 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006753 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006754 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07006755 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
6756 " which might be stale. Will try to clean up.");
6757 // Clean up the stale container and proceed to recreate.
6758 if (!PackageHelper.destroySdDir(newCacheId)) {
6759 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
6760 return false;
6761 }
6762 // Successfully cleaned up stale container. Try to rename again.
6763 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
6764 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
6765 + " inspite of cleaning it up.");
6766 return false;
6767 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006768 }
6769 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006770 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006771 newCachePath = PackageHelper.mountSdDir(newCacheId,
6772 getEncryptKey(), Process.SYSTEM_UID);
6773 } else {
6774 newCachePath = PackageHelper.getSdDir(newCacheId);
6775 }
6776 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006777 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006778 return false;
6779 }
6780 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07006781 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006782 " at new path: " + newCachePath);
6783 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07006784 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006785 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006786 }
6787
Kenny Root85387d72010-08-26 10:13:11 -07006788 private void setCachePath(String newCachePath) {
6789 File cachePath = new File(newCachePath);
6790 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
6791 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
Kenny Root6dceb882012-04-12 14:23:49 -07006792
6793 if (isFwdLocked()) {
6794 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
6795 } else {
6796 resourcePath = packagePath;
6797 }
Kenny Root85387d72010-08-26 10:13:11 -07006798 }
6799
Kenny Root6dceb882012-04-12 14:23:49 -07006800 int doPostInstall(int status, int uid) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006801 if (status != PackageManager.INSTALL_SUCCEEDED) {
6802 cleanUp();
6803 } else {
Kenny Rootbf023582012-05-02 16:56:15 -07006804 final int groupOwner;
6805 final String protectedFile;
6806 if (isFwdLocked()) {
6807 groupOwner = uid;
6808 protectedFile = RES_FILE_NAME;
6809 } else {
6810 groupOwner = -1;
6811 protectedFile = null;
6812 }
6813
Kenny Root6dceb882012-04-12 14:23:49 -07006814 if (uid < Process.FIRST_APPLICATION_UID
Kenny Rootbf023582012-05-02 16:56:15 -07006815 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
Kenny Root6dceb882012-04-12 14:23:49 -07006816 Slog.e(TAG, "Failed to finalize " + cid);
6817 PackageHelper.destroySdDir(cid);
6818 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
6819 }
6820
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08006821 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006822 if (!mounted) {
Kenny Root6dceb882012-04-12 14:23:49 -07006823 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006824 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006825 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006826 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006827 }
6828
6829 private void cleanUp() {
Kenny Root6dceb882012-04-12 14:23:49 -07006830 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
6831
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006832 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08006833 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006834 }
6835
6836 void cleanUpResourcesLI() {
6837 String sourceFile = getCodePath();
6838 // Remove dex file
Jeff Brown5d6d90f2011-07-11 13:04:53 -07006839 int retCode = mInstaller.rmdex(sourceFile);
6840 if (retCode < 0) {
6841 Slog.w(TAG, "Couldn't remove dex file for package: "
6842 + " at location "
6843 + sourceFile.toString() + ", retcode=" + retCode);
6844 // we don't consider this to be a failure of the core package deletion
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006845 }
6846 cleanUp();
6847 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006848
6849 boolean matchContainer(String app) {
6850 if (cid.startsWith(app)) {
6851 return true;
6852 }
6853 return false;
6854 }
6855
6856 String getPackageName() {
Kenny Rootc7a89992012-06-05 15:13:17 -07006857 return getAsecPackageName(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006858 }
6859
6860 boolean doPostDeleteLI(boolean delete) {
6861 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08006862 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006863 if (mounted) {
6864 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08006865 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006866 }
6867 if (ret && delete) {
6868 cleanUpResourcesLI();
6869 }
6870 return ret;
6871 }
Kenny Rootbf023582012-05-02 16:56:15 -07006872
6873 @Override
6874 int doPreCopy() {
6875 if (isFwdLocked()) {
6876 if (!PackageHelper.fixSdPermissions(cid,
6877 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
6878 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
6879 }
6880 }
6881
6882 return PackageManager.INSTALL_SUCCEEDED;
6883 }
6884
6885 @Override
6886 int doPostCopy(int uid) {
6887 if (isFwdLocked()) {
Kenny Rootbf023582012-05-02 16:56:15 -07006888 if (uid < Process.FIRST_APPLICATION_UID
6889 || !PackageHelper.fixSdPermissions(cid, uid, RES_FILE_NAME)) {
6890 Slog.e(TAG, "Failed to finalize " + cid);
6891 PackageHelper.destroySdDir(cid);
6892 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
6893 }
6894 }
6895
6896 return PackageManager.INSTALL_SUCCEEDED;
6897 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006898 };
6899
Kenny Rootc7a89992012-06-05 15:13:17 -07006900 static String getAsecPackageName(String packageCid) {
6901 int idx = packageCid.lastIndexOf("-");
6902 if (idx == -1) {
6903 return packageCid;
6904 }
6905 return packageCid.substring(0, idx);
6906 }
6907
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006908 // Utility method used to create code paths based on package name and available index.
6909 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
6910 String idxStr = "";
6911 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006912 // Fall back to default value of idx=1 if prefix is not
6913 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006914 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00006915 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006916 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00006917 if (subStr.endsWith(suffix)) {
6918 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006919 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006920 // If oldCodePath already contains prefix find out the
6921 // ending index to either increment or decrement.
6922 int sidx = subStr.lastIndexOf(prefix);
6923 if (sidx != -1) {
6924 subStr = subStr.substring(sidx + prefix.length());
6925 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006926 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
6927 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006928 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006929 try {
6930 idx = Integer.parseInt(subStr);
6931 if (idx <= 1) {
6932 idx++;
6933 } else {
6934 idx--;
6935 }
6936 } catch(NumberFormatException e) {
6937 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006938 }
6939 }
6940 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006941 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006942 return prefix + idxStr;
6943 }
6944
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006945 // Utility method used to ignore ADD/REMOVE events
6946 // by directory observer.
6947 private static boolean ignoreCodePath(String fullPathStr) {
6948 String apkName = getApkName(fullPathStr);
6949 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
6950 if (idx != -1 && ((idx+1) < apkName.length())) {
6951 // Make sure the package ends with a numeral
6952 String version = apkName.substring(idx+1);
6953 try {
6954 Integer.parseInt(version);
6955 return true;
6956 } catch (NumberFormatException e) {}
6957 }
6958 return false;
6959 }
6960
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006961 // Utility method that returns the relative package path with respect
6962 // to the installation directory. Like say for /data/data/com.test-1.apk
6963 // string com.test-1 is returned.
6964 static String getApkName(String codePath) {
6965 if (codePath == null) {
6966 return null;
6967 }
6968 int sidx = codePath.lastIndexOf("/");
6969 int eidx = codePath.lastIndexOf(".");
6970 if (eidx == -1) {
6971 eidx = codePath.length();
6972 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006973 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006974 return null;
6975 }
6976 return codePath.substring(sidx+1, eidx);
6977 }
6978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006979 class PackageInstalledInfo {
6980 String name;
6981 int uid;
6982 PackageParser.Package pkg;
6983 int returnCode;
6984 PackageRemovedInfo removedInfo;
6985 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006987 /*
6988 * Install a non-existing package.
6989 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006990 private void installNewPackageLI(PackageParser.Package pkg,
6991 int parseFlags,
6992 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02006993 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006994 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006995 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08006996
Amith Yamasani0b285492011-04-14 17:35:23 -07006997 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006998 res.name = pkgName;
6999 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07007000 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
7001 // A package with the same name is already installed, though
7002 // it has been renamed to an older name. The package we
7003 // are trying to install should be installed as an update to
7004 // the existing one, but that has not been requested, so bail.
7005 Slog.w(TAG, "Attempt to re-install " + pkgName
7006 + " without first uninstalling package running as "
7007 + mSettings.mRenamedPackages.get(pkgName));
7008 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
7009 return;
7010 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007011 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007012 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007013 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007014 + " without first uninstalling.");
7015 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
7016 return;
7017 }
7018 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007019 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007020 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
7021 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007022 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007023 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007024 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
7025 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
7026 }
7027 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007028 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02007029 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007030 res);
7031 // delete the partially installed application. the data directory will have to be
7032 // restored if it was already existing
7033 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
7034 // remove package from internal structures. Note that we want deletePackageX to
7035 // delete the package data and cache directories that it created in
7036 // scanPackageLocked, unless those directories existed before we even tried to
7037 // install.
7038 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007039 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007040 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007041 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007042 }
7043 }
7044 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007045
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007046 private void replacePackageLI(PackageParser.Package pkg,
7047 int parseFlags,
7048 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02007049 String installerPackageName, PackageInstalledInfo res) {
7050
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007051 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007052 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007053 // First find the old package info and check signatures
7054 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007055 oldPackage = mPackages.get(pkgName);
Kenny Root447106f2011-03-23 11:00:15 -07007056 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07007057 != PackageManager.SIGNATURE_MATCH) {
Kenny Root8c11f1d2012-04-14 12:10:38 -07007058 Slog.w(TAG, "New package has a different signature: " + pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007059 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
7060 return;
7061 }
7062 }
Kenny Root85387d72010-08-26 10:13:11 -07007063 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007064 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007065 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007066 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007067 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007068 }
7069 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007071 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007072 PackageParser.Package pkg,
7073 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02007074 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007075 PackageParser.Package newPackage = null;
7076 String pkgName = deletedPackage.packageName;
7077 boolean deletedPkg = true;
7078 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007079
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007080 long origUpdateTime;
7081 if (pkg.mExtras != null) {
7082 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
7083 } else {
7084 origUpdateTime = 0;
7085 }
7086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007087 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007088 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007089 res.removedInfo, true)) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007090 // If the existing package wasn't successfully deleted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007091 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
7092 deletedPkg = false;
7093 } else {
7094 // Successfully deleted the old package. Now proceed with re-installation
7095 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007096 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
7097 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007098 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007099 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007100 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
7101 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08007102 }
7103 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007104 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02007105 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007106 res);
7107 updatedSettings = true;
7108 }
7109 }
7110
Suchi Amalapurapuae181712010-03-30 14:01:02 -07007111 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007112 // remove package from internal structures. Note that we want deletePackageX to
7113 // delete the package data and cache directories that it created in
7114 // scanPackageLocked, unless those directories existed before we even tried to
7115 // install.
7116 if(updatedSettings) {
7117 deletePackageLI(
7118 pkgName, true,
7119 PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007120 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007121 }
7122 // Since we failed to install the new package we need to restore the old
7123 // package that we deleted.
7124 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07007125 File restoreFile = new File(deletedPackage.mPath);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007126 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07007127 boolean oldOnSd = isExternal(deletedPackage);
7128 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
7129 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
7130 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007131 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
7132 | SCAN_UPDATE_TIME;
7133 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
7134 origUpdateTime) == null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07007135 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
7136 return;
7137 }
7138 // Restore of old package succeeded. Update permissions.
Kenny Root447106f2011-03-23 11:00:15 -07007139 // writer
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007140 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07007141 updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
Dianne Hackborne639da72012-02-21 15:11:13 -08007142 UPDATE_PERMISSIONS_ALL);
Kenny Root447106f2011-03-23 11:00:15 -07007143 // can downgrade to reader
7144 mSettings.writeLPr();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007145 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07007146 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007147 }
7148 }
7149 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007151 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007152 PackageParser.Package pkg,
7153 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02007154 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007155 PackageParser.Package newPackage = null;
7156 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007157 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007158 PackageParser.PARSE_IS_SYSTEM;
7159 String packageName = deletedPackage.packageName;
7160 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
7161 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007162 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007163 return;
7164 }
7165 PackageParser.Package oldPkg;
7166 PackageSetting oldPkgSetting;
Kenny Root447106f2011-03-23 11:00:15 -07007167 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007168 synchronized (mPackages) {
7169 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007170 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007171 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
7172 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007173 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007174 return;
7175 }
7176 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007177
7178 killApplication(packageName, oldPkg.applicationInfo.uid);
7179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007180 res.removedInfo.uid = oldPkg.applicationInfo.uid;
7181 res.removedInfo.removedPackage = packageName;
7182 // Remove existing system package
7183 removePackageLI(oldPkg, true);
Kenny Root447106f2011-03-23 11:00:15 -07007184 // writer
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08007185 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07007186 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007187 // We didn't need to disable the .apk as a current system package,
7188 // which means we are replacing another update that is already
7189 // installed. We need to make sure to delete the older one's .apk.
Kenny Root6dceb882012-04-12 14:23:49 -07007190 res.removedInfo.args = createInstallArgs(0,
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007191 deletedPackage.applicationInfo.sourceDir,
7192 deletedPackage.applicationInfo.publicSourceDir,
7193 deletedPackage.applicationInfo.nativeLibraryDir);
7194 } else {
7195 res.removedInfo.args = null;
7196 }
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08007197 }
7198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007199 // Successfully disabled the old package. Now proceed with re-installation
7200 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
7201 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007202 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007203 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007204 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007205 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
7206 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
7207 }
7208 } else {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007209 if (newPackage.mExtras != null) {
7210 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
7211 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
7212 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
7213 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007214 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007215 updatedSettings = true;
7216 }
7217
Suchi Amalapurapuae181712010-03-30 14:01:02 -07007218 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007219 // Re installation failed. Restore old information
7220 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07007221 if (newPackage != null) {
7222 removePackageLI(newPackage, true);
7223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007224 // Add back the old system package
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007225 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007226 // Restore the old system information in Settings
7227 synchronized(mPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007228 if (updatedSettings) {
Kenny Root447106f2011-03-23 11:00:15 -07007229 mSettings.enableSystemPackageLPw(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02007230 mSettings.setInstallerPackageName(packageName,
7231 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007232 }
Kenny Root447106f2011-03-23 11:00:15 -07007233 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007234 }
7235 }
7236 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007237
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007238 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07007239 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007240 int retCode;
7241 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
7242 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
7243 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07007244 if (mNoDexOpt) {
7245 /*
7246 * If we're in an engineering build, programs are lazily run
7247 * through dexopt. If the .dex file doesn't exist yet, it
7248 * will be created when the program is run next.
7249 */
7250 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
7251 } else {
7252 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
7253 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7254 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007255 }
7256 }
7257 return PackageManager.INSTALL_SUCCEEDED;
7258 }
7259
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007260 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02007261 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007262 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007263 synchronized (mPackages) {
7264 //write settings. the installStatus will be incomplete at this stage.
7265 //note that the new package setting would have already been
7266 //added to mPackages. It hasn't been persisted yet.
Kenny Rootcf0b38c2011-03-22 14:17:59 -07007267 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
Kenny Root447106f2011-03-23 11:00:15 -07007268 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007269 }
7270
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07007271 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007272 != PackageManager.INSTALL_SUCCEEDED) {
7273 // Discontinue if moving dex files failed.
7274 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007275 }
Kenny Root6dceb882012-04-12 14:23:49 -07007276
7277 Log.d(TAG, "New package installed in " + newPackage.mPath);
7278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007279 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07007280 updatePermissionsLPw(newPackage.packageName, newPackage,
Dianne Hackborne639da72012-02-21 15:11:13 -08007281 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
7282 ? UPDATE_PERMISSIONS_ALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007283 res.name = pkgName;
7284 res.uid = newPackage.applicationInfo.uid;
7285 res.pkg = newPackage;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07007286 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02007287 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007288 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
7289 //to update install status
Kenny Root447106f2011-03-23 11:00:15 -07007290 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007291 }
7292 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007293
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007294 private void installPackageLI(InstallArgs args,
7295 boolean newInstall, PackageInstalledInfo res) {
7296 int pFlags = args.flags;
7297 String installerPackageName = args.installerPackageName;
7298 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007299 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08007300 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007301 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07007302 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007303 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07007304 // Result object to be returned
7305 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
7306
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007307 // Retrieve PackageSettings and parse package
Kenny Root6dceb882012-04-12 14:23:49 -07007308 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
7309 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
7310 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007311 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
7312 pp.setSeparateProcesses(mSeparateProcesses);
7313 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
7314 null, mMetrics, parseFlags);
7315 if (pkg == null) {
7316 res.returnCode = pp.getParseError();
7317 return;
7318 }
7319 String pkgName = res.name = pkg.packageName;
7320 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
7321 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
7322 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
7323 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007324 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007325 }
7326 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
7327 res.returnCode = pp.getParseError();
7328 return;
7329 }
Kenny Root5ab21572011-07-27 11:11:19 -07007330
7331 /* If the installer passed in a manifest digest, compare it now. */
7332 if (args.manifestDigest != null) {
7333 if (DEBUG_INSTALL) {
7334 final String parsedManifest = pkg.manifestDigest == null ? "null"
7335 : pkg.manifestDigest.toString();
7336 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
7337 + parsedManifest);
7338 }
7339
7340 if (!args.manifestDigest.equals(pkg.manifestDigest)) {
7341 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
7342 return;
7343 }
7344 } else if (DEBUG_INSTALL) {
7345 final String parsedManifest = pkg.manifestDigest == null
7346 ? "null" : pkg.manifestDigest.toString();
7347 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
7348 }
7349
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007350 // Get rid of all references to package scan path via parser.
7351 pp = null;
7352 String oldCodePath = null;
7353 boolean systemApp = false;
7354 synchronized (mPackages) {
7355 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007356 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
7357 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08007358 if (pkg.mOriginalPackages != null
7359 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007360 && mPackages.containsKey(oldName)) {
7361 // This package is derived from an original package,
7362 // and this device has been updating from that original
7363 // name. We must continue using the original name, so
7364 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08007365 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007366 pkgName = pkg.packageName;
7367 replace = true;
7368 } else if (mPackages.containsKey(pkgName)) {
7369 // This package, under its official name, already exists
7370 // on the device; we should replace it.
7371 replace = true;
7372 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007373 }
7374 PackageSetting ps = mSettings.mPackages.get(pkgName);
7375 if (ps != null) {
7376 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
7377 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7378 systemApp = (ps.pkg.applicationInfo.flags &
7379 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07007380 }
7381 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007382 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007383
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007384 if (systemApp && onSd) {
7385 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007386 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007387 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
7388 return;
7389 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08007390
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007391 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
7392 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7393 return;
7394 }
7395 // Set application objects path explicitly after the rename
7396 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07007397 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007398 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007399 replacePackageLI(pkg, parseFlags, scanMode,
7400 installerPackageName, res);
7401 } else {
7402 installNewPackageLI(pkg, parseFlags, scanMode,
7403 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007404 }
7405 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007406
Kenny Root85387d72010-08-26 10:13:11 -07007407 private static boolean isForwardLocked(PackageParser.Package pkg) {
7408 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007409 }
7410
Kenny Root88670d82012-05-09 15:47:35 -07007411
7412 private boolean isForwardLocked(PackageSetting ps) {
7413 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
7414 }
7415
Kenny Root85387d72010-08-26 10:13:11 -07007416 private static boolean isExternal(PackageParser.Package pkg) {
7417 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
7418 }
7419
Kenny Root6dceb882012-04-12 14:23:49 -07007420 private static boolean isExternal(PackageSetting ps) {
7421 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
7422 }
7423
Kenny Root85387d72010-08-26 10:13:11 -07007424 private static boolean isSystemApp(PackageParser.Package pkg) {
7425 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7426 }
7427
Kenny Root502e9a42011-01-10 13:48:15 -08007428 private static boolean isSystemApp(ApplicationInfo info) {
7429 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7430 }
7431
Kenny Root208d3412012-05-07 19:42:35 -07007432 private static boolean isSystemApp(PackageSetting ps) {
7433 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
7434 }
7435
Kenny Root85387d72010-08-26 10:13:11 -07007436 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
7437 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07007438 }
7439
Kenny Root88670d82012-05-09 15:47:35 -07007440 private int packageFlagsToInstallFlags(PackageSetting ps) {
7441 int installFlags = 0;
7442 if (isExternal(ps)) {
7443 installFlags |= PackageManager.INSTALL_EXTERNAL;
7444 }
7445 if (isForwardLocked(ps)) {
7446 installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
7447 }
7448 return installFlags;
7449 }
7450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007451 private void deleteTempPackageFiles() {
7452 FilenameFilter filter = new FilenameFilter() {
7453 public boolean accept(File dir, String name) {
7454 return name.startsWith("vmdl") && name.endsWith(".tmp");
7455 }
7456 };
7457 String tmpFilesList[] = mAppInstallDir.list(filter);
7458 if(tmpFilesList == null) {
7459 return;
7460 }
7461 for(int i = 0; i < tmpFilesList.length; i++) {
7462 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
7463 tmpFile.delete();
7464 }
7465 }
7466
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007467 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007468 File tmpPackageFile;
7469 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007470 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007471 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007472 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007473 return null;
7474 }
7475 try {
7476 FileUtils.setPermissions(
7477 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
7478 -1, -1);
rpcraig554cb0c2012-07-05 06:41:43 -04007479 if (!SELinux.restorecon(tmpPackageFile)) {
7480 return null;
7481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007482 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007483 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007484 return null;
7485 }
7486 return tmpPackageFile;
7487 }
7488
7489 public void deletePackage(final String packageName,
7490 final IPackageDeleteObserver observer,
7491 final int flags) {
7492 mContext.enforceCallingOrSelfPermission(
7493 android.Manifest.permission.DELETE_PACKAGES, null);
7494 // Queue up an async operation since the package deletion may take a little while.
7495 mHandler.post(new Runnable() {
7496 public void run() {
7497 mHandler.removeCallbacks(this);
Kenny Rootc39bb4a2011-02-28 13:27:19 -08007498 final int returnCode = deletePackageX(packageName, true, true, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007499 if (observer != null) {
7500 try {
Kenny Rootc39bb4a2011-02-28 13:27:19 -08007501 observer.packageDeleted(packageName, returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007502 } catch (RemoteException e) {
7503 Log.i(TAG, "Observer no longer exists.");
7504 } //end catch
7505 } //end if
7506 } //end run
7507 });
7508 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007510 /**
7511 * This method is an internal method that could be get invoked either
7512 * to delete an installed package or to clean up a failed installation.
7513 * After deleting an installed package, a broadcast is sent to notify any
7514 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007515 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007516 * installation wouldn't have sent the initial broadcast either
7517 * The key steps in deleting a package are
7518 * deleting the package information in internal structures like mPackages,
7519 * deleting the packages base directories through installd
7520 * updating mSettings to reflect current status
7521 * persisting settings for later use
7522 * sending a broadcast if necessary
7523 */
Kenny Rootc39bb4a2011-02-28 13:27:19 -08007524 private int deletePackageX(String packageName, boolean sendBroadCast,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007525 boolean deleteCodeAndResources, int flags) {
Kenny Rootc39bb4a2011-02-28 13:27:19 -08007526 final PackageRemovedInfo info = new PackageRemovedInfo();
7527 final boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007528
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007529 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
7530 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
7531 try {
7532 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007533 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Kenny Rootc39bb4a2011-02-28 13:27:19 -08007534 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007535 }
7536 } catch (RemoteException e) {
7537 }
7538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007539 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07007540 res = deletePackageLI(packageName, deleteCodeAndResources,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007541 flags | REMOVE_CHATTY, info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007542 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007543
Kenny Rootc39bb4a2011-02-28 13:27:19 -08007544 if (res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07007545 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07007546 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07007547
7548 // If the removed package was a system update, the old system packaged
7549 // was re-enabled; we need to broadcast this information
7550 if (systemUpdate) {
7551 Bundle extras = new Bundle(1);
7552 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
7553 extras.putBoolean(Intent.EXTRA_REPLACING, true);
7554
Dianne Hackborne7f97212011-02-24 14:40:20 -08007555 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007556 extras, null, null, UserHandle.USER_ALL);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007557 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007558 extras, null, null, UserHandle.USER_ALL);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007559 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007560 null, packageName, null, UserHandle.USER_ALL);
Romain Guy96f43572009-03-24 20:27:49 -07007561 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007562 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07007563 // Force a gc here.
7564 Runtime.getRuntime().gc();
7565 // Delete the resources here after sending the broadcast to let
7566 // other processes clean up before deleting resources.
7567 if (info.args != null) {
7568 synchronized (mInstallLock) {
7569 info.args.doPostDeleteLI(deleteCodeAndResources);
7570 }
7571 }
Kenny Rootc39bb4a2011-02-28 13:27:19 -08007572
7573 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007574 }
7575
7576 static class PackageRemovedInfo {
7577 String removedPackage;
7578 int uid = -1;
7579 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07007580 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007581 // Clean up resources deleted packages.
7582 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07007583
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07007584 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007585 Bundle extras = new Bundle(1);
7586 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
7587 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
7588 if (replacing) {
7589 extras.putBoolean(Intent.EXTRA_REPLACING, true);
7590 }
7591 if (removedPackage != null) {
Dianne Hackborne7f97212011-02-24 14:40:20 -08007592 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007593 extras, null, null, UserHandle.USER_ALL);
Dianne Hackbornf9abb402011-08-10 15:00:59 -07007594 if (fullRemove && !replacing) {
7595 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007596 extras, null, null, UserHandle.USER_ALL);
Dianne Hackbornf9abb402011-08-10 15:00:59 -07007597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007598 }
7599 if (removedUid >= 0) {
Amith Yamasani13593602012-03-22 16:16:17 -07007600 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007601 UserHandle.getUserId(removedUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007602 }
7603 }
7604 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007606 /*
7607 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
7608 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007609 * 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 -08007610 * delete a partially installed application.
7611 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007612 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007613 int flags, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007614 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007615 if (outInfo != null) {
7616 outInfo.removedPackage = packageName;
7617 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07007618 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007619 // Retrieve object to delete permissions for shared user later on
Kenny Root447106f2011-03-23 11:00:15 -07007620 final PackageSetting deletedPs;
7621 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007622 synchronized (mPackages) {
7623 deletedPs = mSettings.mPackages.get(packageName);
7624 }
7625 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Jeff Brown5d6d90f2011-07-11 13:04:53 -07007626 int retCode = mInstaller.remove(packageName, 0);
7627 if (retCode < 0) {
7628 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
7629 + packageName + ", retcode=" + retCode);
7630 // we don't consider this to be a failure of the core package deletion
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007631 } else {
Jeff Brown5d6d90f2011-07-11 13:04:53 -07007632 // TODO: Kill the processes first
Amith Yamasani13593602012-03-22 16:16:17 -07007633 sUserManager.removePackageForAllUsers(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007634 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07007635 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007636 }
Kenny Root447106f2011-03-23 11:00:15 -07007637 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007638 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007639 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007640 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
7641 if (outInfo != null) {
Kenny Root447106f2011-03-23 11:00:15 -07007642 outInfo.removedUid = mSettings.removePackageLPw(packageName);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007643 }
7644 if (deletedPs != null) {
Dianne Hackborne639da72012-02-21 15:11:13 -08007645 updatePermissionsLPw(deletedPs.name, null, 0);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007646 if (deletedPs.sharedUser != null) {
7647 // remove permissions associated with package
Kenny Root447106f2011-03-23 11:00:15 -07007648 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007649 }
7650 }
Amith Yamasania3f133a2012-08-09 17:11:28 -07007651 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007652 }
7653 }
Kenny Root447106f2011-03-23 11:00:15 -07007654 // can downgrade to reader
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007655 if (writeSettings) {
7656 // Save settings now
Kenny Root447106f2011-03-23 11:00:15 -07007657 mSettings.writeLPr();
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007659 }
7660 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007662 /*
7663 * Tries to delete system package.
7664 */
7665 private boolean deleteSystemPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007666 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007667 ApplicationInfo applicationInfo = p.applicationInfo;
7668 //applicable for non-partially installed applications only
7669 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007670 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007671 return false;
7672 }
7673 PackageSetting ps = null;
7674 // Confirm if the system package has been updated
7675 // An updated system app can be deleted. This will also have to restore
7676 // the system pkg from system partition
Kenny Root447106f2011-03-23 11:00:15 -07007677 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007678 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07007679 ps = mSettings.getDisabledSystemPkgLPr(p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007680 }
7681 if (ps == null) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007682 Slog.w(TAG, "Attempt to delete unknown system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007683 return false;
7684 } else {
7685 Log.i(TAG, "Deleting system pkg from data partition");
7686 }
7687 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07007688 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07007689 if (ps.versionCode < p.mVersionCode) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007690 // Delete data for downgrades
Kenny Root7c1bd7f2010-09-01 13:44:11 -07007691 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007692 } else {
7693 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07007694 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007695 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007696 boolean ret = deleteInstalledPackageLI(p, true, flags, outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007697 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007698 if (!ret) {
7699 return false;
7700 }
Kenny Root447106f2011-03-23 11:00:15 -07007701 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007702 synchronized (mPackages) {
7703 // Reinstate the old system package
Kenny Root447106f2011-03-23 11:00:15 -07007704 mSettings.enableSystemPackageLPw(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07007705 // Remove any native libraries from the upgraded package.
7706 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007707 }
7708 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007709 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007710 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007711 SCAN_MONITOR | SCAN_NO_PATHS, 0);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007713 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007714 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007715 return false;
7716 }
Kenny Root447106f2011-03-23 11:00:15 -07007717 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007718 synchronized (mPackages) {
Dianne Hackborne639da72012-02-21 15:11:13 -08007719 updatePermissionsLPw(newPkg.packageName, newPkg,
7720 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
Kenny Root447106f2011-03-23 11:00:15 -07007721 // can downgrade to reader here
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007722 if (writeSettings) {
Kenny Root447106f2011-03-23 11:00:15 -07007723 mSettings.writeLPr();
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007725 }
7726 return true;
7727 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007729 private boolean deleteInstalledPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007730 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
7731 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007732 ApplicationInfo applicationInfo = p.applicationInfo;
7733 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007734 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007735 return false;
7736 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007737 if (outInfo != null) {
7738 outInfo.uid = applicationInfo.uid;
7739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740
7741 // Delete package data from internal structures and also remove data if flag is set
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007742 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007743
7744 // Delete application code and resources
7745 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007746 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07007747 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
7748 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
7749 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
7750 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007751 }
7752 return true;
7753 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007755 /*
7756 * This method handles package deletion in general
7757 */
7758 private boolean deletePackageLI(String packageName,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007759 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
7760 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007761 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007762 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007763 return false;
7764 }
7765 PackageParser.Package p;
7766 boolean dataOnly = false;
7767 synchronized (mPackages) {
7768 p = mPackages.get(packageName);
7769 if (p == null) {
7770 //this retrieves partially installed apps
7771 dataOnly = true;
7772 PackageSetting ps = mSettings.mPackages.get(packageName);
7773 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007774 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007775 return false;
7776 }
7777 p = ps.pkg;
7778 }
7779 }
7780 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007781 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007782 return false;
7783 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007785 if (dataOnly) {
7786 // Delete application data first
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007787 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007788 return true;
7789 }
7790 // At this point the package should have ApplicationInfo associated with it
7791 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007792 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007793 return false;
7794 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007795 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07007796 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007797 Log.i(TAG, "Removing system package:"+p.packageName);
7798 // When an updated system application is deleted we delete the existing resources as well and
7799 // fall back to existing code in system partition
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007800 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007801 } else {
7802 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007803 // Kill application pre-emptively especially for apps on sd.
7804 killApplication(packageName, p.applicationInfo.uid);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007805 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
7806 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007807 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007808 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007809 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007810
Dianne Hackborn183ce022012-06-29 15:00:21 -07007811 private final class ClearStorageConnection implements ServiceConnection {
7812 IMediaContainerService mContainerService;
7813
7814 @Override
7815 public void onServiceConnected(ComponentName name, IBinder service) {
7816 synchronized (this) {
7817 mContainerService = IMediaContainerService.Stub.asInterface(service);
7818 notifyAll();
7819 }
7820 }
7821
7822 @Override
7823 public void onServiceDisconnected(ComponentName name) {
7824 }
7825 }
7826
7827 private void clearExternalStorageDataSync(String packageName, boolean allData) {
7828 final boolean mounted;
7829 if (Environment.isExternalStorageEmulated()) {
7830 mounted = true;
7831 } else {
7832 final String status = Environment.getExternalStorageState();
7833
7834 mounted = status.equals(Environment.MEDIA_MOUNTED)
7835 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
7836 }
7837
7838 if (!mounted) {
7839 return;
7840 }
7841
7842 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
7843 ClearStorageConnection conn = new ClearStorageConnection();
7844 if (mContext.bindService(containerIntent, conn, Context.BIND_AUTO_CREATE)) {
7845 try {
7846 long timeout = SystemClock.uptimeMillis() + 5000;
7847 synchronized (conn) {
7848 long now = SystemClock.uptimeMillis();
7849 while (conn.mContainerService == null && now < timeout) {
7850 try {
7851 conn.wait(timeout - now);
7852 } catch (InterruptedException e) {
7853 }
7854 }
7855 }
7856 if (conn.mContainerService == null) {
7857 return;
7858 }
7859 final File externalCacheDir = Environment
7860 .getExternalStorageAppCacheDirectory(packageName);
7861 try {
7862 conn.mContainerService.clearDirectory(externalCacheDir.toString());
7863 } catch (RemoteException e) {
7864 }
7865 if (allData) {
7866 final File externalDataDir = Environment
7867 .getExternalStorageAppDataDirectory(packageName);
7868 try {
7869 conn.mContainerService.clearDirectory(externalDataDir.toString());
7870 } catch (RemoteException e) {
7871 }
7872 final File externalMediaDir = Environment
7873 .getExternalStorageAppMediaDirectory(packageName);
7874 try {
7875 conn.mContainerService.clearDirectory(externalMediaDir.toString());
7876 } catch (RemoteException e) {
7877 }
7878 }
7879 } finally {
7880 mContext.unbindService(conn);
7881 }
7882 }
7883 }
7884
Amith Yamasani483f3b02012-03-13 16:08:00 -07007885 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007886 public void clearApplicationUserData(final String packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07007887 final IPackageDataObserver observer, final int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007888 mContext.enforceCallingOrSelfPermission(
7889 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
Amith Yamasani483f3b02012-03-13 16:08:00 -07007890 checkValidCaller(Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007891 // Queue up an async operation since the package deletion may take a little while.
7892 mHandler.post(new Runnable() {
7893 public void run() {
7894 mHandler.removeCallbacks(this);
7895 final boolean succeeded;
7896 synchronized (mInstallLock) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07007897 succeeded = clearApplicationUserDataLI(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007898 }
Dianne Hackborn183ce022012-06-29 15:00:21 -07007899 clearExternalStorageDataSync(packageName, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007900 if (succeeded) {
7901 // invoke DeviceStorageMonitor's update method to clear any notifications
7902 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
7903 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
7904 if (dsm != null) {
7905 dsm.updateMemory();
7906 }
7907 }
7908 if(observer != null) {
7909 try {
7910 observer.onRemoveCompleted(packageName, succeeded);
7911 } catch (RemoteException e) {
7912 Log.i(TAG, "Observer no longer exists.");
7913 }
7914 } //end if observer
7915 } //end run
7916 });
7917 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007918
Amith Yamasani483f3b02012-03-13 16:08:00 -07007919 private boolean clearApplicationUserDataLI(String packageName, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007920 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007921 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007922 return false;
7923 }
7924 PackageParser.Package p;
7925 boolean dataOnly = false;
7926 synchronized (mPackages) {
7927 p = mPackages.get(packageName);
7928 if(p == null) {
7929 dataOnly = true;
7930 PackageSetting ps = mSettings.mPackages.get(packageName);
7931 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007932 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007933 return false;
7934 }
7935 p = ps.pkg;
7936 }
7937 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08007938
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08007939 if (!dataOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007940 //need to check this only for fully installed applications
7941 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007942 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007943 return false;
7944 }
7945 final ApplicationInfo applicationInfo = p.applicationInfo;
7946 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007947 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007948 return false;
7949 }
7950 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07007951 int retCode = mInstaller.clearUserData(packageName, userId);
Jeff Brown5d6d90f2011-07-11 13:04:53 -07007952 if (retCode < 0) {
7953 Slog.w(TAG, "Couldn't remove cache files for package: "
7954 + packageName);
7955 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007956 }
7957 return true;
7958 }
7959
7960 public void deleteApplicationCacheFiles(final String packageName,
7961 final IPackageDataObserver observer) {
7962 mContext.enforceCallingOrSelfPermission(
7963 android.Manifest.permission.DELETE_CACHE_FILES, null);
7964 // Queue up an async operation since the package deletion may take a little while.
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007965 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007966 mHandler.post(new Runnable() {
7967 public void run() {
7968 mHandler.removeCallbacks(this);
7969 final boolean succeded;
7970 synchronized (mInstallLock) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07007971 succeded = deleteApplicationCacheFilesLI(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007972 }
Dianne Hackborn183ce022012-06-29 15:00:21 -07007973 clearExternalStorageDataSync(packageName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 if(observer != null) {
7975 try {
7976 observer.onRemoveCompleted(packageName, succeded);
7977 } catch (RemoteException e) {
7978 Log.i(TAG, "Observer no longer exists.");
7979 }
7980 } //end if observer
7981 } //end run
7982 });
7983 }
7984
Amith Yamasani483f3b02012-03-13 16:08:00 -07007985 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007986 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007987 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007988 return false;
7989 }
7990 PackageParser.Package p;
7991 synchronized (mPackages) {
7992 p = mPackages.get(packageName);
7993 }
7994 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007995 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007996 return false;
7997 }
7998 final ApplicationInfo applicationInfo = p.applicationInfo;
7999 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008000 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008001 return false;
8002 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07008003 // TODO: Pass userId to deleteCacheFiles
Jeff Brown5d6d90f2011-07-11 13:04:53 -07008004 int retCode = mInstaller.deleteCacheFiles(packageName);
8005 if (retCode < 0) {
8006 Slog.w(TAG, "Couldn't remove cache files for package: "
8007 + packageName);
8008 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008009 }
8010 return true;
8011 }
8012
8013 public void getPackageSizeInfo(final String packageName,
8014 final IPackageStatsObserver observer) {
8015 mContext.enforceCallingOrSelfPermission(
8016 android.Manifest.permission.GET_PACKAGE_SIZE, null);
Kenny Root366949c2011-01-14 17:18:14 -08008017
Kenny Roota69b7eb2012-05-14 14:47:06 -07008018 PackageStats stats = new PackageStats(packageName);
Kenny Root366949c2011-01-14 17:18:14 -08008019
Kenny Roota69b7eb2012-05-14 14:47:06 -07008020 /*
8021 * Queue up an async operation since the package measurement may take a
8022 * little while.
8023 */
8024 Message msg = mHandler.obtainMessage(INIT_COPY);
8025 msg.obj = new MeasureParams(stats, observer);
8026 mHandler.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008027 }
8028
8029 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
8030 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008031 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008032 return false;
8033 }
8034 PackageParser.Package p;
8035 boolean dataOnly = false;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07008036 String asecPath = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008037 synchronized (mPackages) {
8038 p = mPackages.get(packageName);
8039 if(p == null) {
8040 dataOnly = true;
8041 PackageSetting ps = mSettings.mPackages.get(packageName);
8042 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008043 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008044 return false;
8045 }
8046 p = ps.pkg;
8047 }
Kenny Root2afded12012-06-04 16:39:47 -07008048 if (p != null && (isExternal(p) || isForwardLocked(p))) {
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07008049 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
8050 if (secureContainerId != null) {
8051 asecPath = PackageHelper.getSdFilesystem(secureContainerId);
8052 }
8053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008054 }
8055 String publicSrcDir = null;
8056 if(!dataOnly) {
8057 final ApplicationInfo applicationInfo = p.applicationInfo;
8058 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008059 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008060 return false;
8061 }
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07008062 if (isForwardLocked(p)) {
8063 publicSrcDir = applicationInfo.publicSourceDir;
8064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008065 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07008066 int res = mInstaller.getSizeInfo(packageName, p.mPath, publicSrcDir,
8067 asecPath, pStats);
8068 if (res < 0) {
8069 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008070 }
Kenny Root2afded12012-06-04 16:39:47 -07008071
8072 // Fix-up for forward-locked applications in ASEC containers.
8073 if (!isExternal(p)) {
8074 pStats.codeSize += pStats.externalCodeSize;
8075 pStats.externalCodeSize = 0L;
8076 }
8077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008078 return true;
8079 }
8080
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008082 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07008083 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008084 }
8085
8086 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07008087 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008088 }
8089
8090 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008091 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008092 }
8093
Kenny Root447106f2011-03-23 11:00:15 -07008094 private int getUidTargetSdkVersionLockedLPr(int uid) {
8095 Object obj = mSettings.getUserIdLPr(uid);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008096 if (obj instanceof SharedUserSetting) {
Kenny Root60f7ad82011-03-22 12:49:06 -07008097 final SharedUserSetting sus = (SharedUserSetting) obj;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008098 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
Kenny Root60f7ad82011-03-22 12:49:06 -07008099 final Iterator<PackageSetting> it = sus.packages.iterator();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008100 while (it.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07008101 final PackageSetting ps = it.next();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008102 if (ps.pkg != null) {
8103 int v = ps.pkg.applicationInfo.targetSdkVersion;
8104 if (v < vers) vers = v;
8105 }
8106 }
8107 return vers;
8108 } else if (obj instanceof PackageSetting) {
Kenny Root60f7ad82011-03-22 12:49:06 -07008109 final PackageSetting ps = (PackageSetting) obj;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008110 if (ps.pkg != null) {
8111 return ps.pkg.applicationInfo.targetSdkVersion;
8112 }
8113 }
8114 return Build.VERSION_CODES.CUR_DEVELOPMENT;
8115 }
8116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008117 public void addPreferredActivity(IntentFilter filter, int match,
Amith Yamasania3f133a2012-08-09 17:11:28 -07008118 ComponentName[] set, ComponentName activity, int userId) {
Kenny Root447106f2011-03-23 11:00:15 -07008119 // writer
Amith Yamasania3f133a2012-08-09 17:11:28 -07008120 int callingUid = Binder.getCallingUid();
8121 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008122 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008123 if (mContext.checkCallingOrSelfPermission(
8124 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
8125 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasania3f133a2012-08-09 17:11:28 -07008126 if (getUidTargetSdkVersionLockedLPr(callingUid)
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008127 < Build.VERSION_CODES.FROYO) {
8128 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
Amith Yamasania3f133a2012-08-09 17:11:28 -07008129 + callingUid);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008130 return;
8131 }
8132 mContext.enforceCallingOrSelfPermission(
8133 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
8134 }
Amith Yamasania3f133a2012-08-09 17:11:28 -07008135
8136 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008137 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
8138 mSettings.mPreferredActivities.addFilter(
Amith Yamasania3f133a2012-08-09 17:11:28 -07008139 new PreferredActivity(filter, match, set, activity, userId));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07008140 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008141 }
8142 }
8143
Satish Sampath8dbe6122009-06-02 23:35:54 +01008144 public void replacePreferredActivity(IntentFilter filter, int match,
8145 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01008146 if (filter.countActions() != 1) {
8147 throw new IllegalArgumentException(
8148 "replacePreferredActivity expects filter to have only 1 action.");
8149 }
8150 if (filter.countCategories() != 1) {
8151 throw new IllegalArgumentException(
8152 "replacePreferredActivity expects filter to have only 1 category.");
8153 }
8154 if (filter.countDataAuthorities() != 0
8155 || filter.countDataPaths() != 0
8156 || filter.countDataSchemes() != 0
8157 || filter.countDataTypes() != 0) {
8158 throw new IllegalArgumentException(
8159 "replacePreferredActivity expects filter to have no data authorities, " +
8160 "paths, schemes or types.");
8161 }
8162 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008163 if (mContext.checkCallingOrSelfPermission(
8164 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
8165 != PackageManager.PERMISSION_GRANTED) {
Kenny Root447106f2011-03-23 11:00:15 -07008166 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008167 < Build.VERSION_CODES.FROYO) {
8168 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
8169 + Binder.getCallingUid());
8170 return;
8171 }
8172 mContext.enforceCallingOrSelfPermission(
8173 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
8174 }
Amith Yamasania3f133a2012-08-09 17:11:28 -07008175
8176 final int callingUserId = UserHandle.getCallingUserId();
Dianne Hackborn04505102012-02-29 12:34:04 -08008177 ArrayList<PreferredActivity> removed = null;
Satish Sampath8dbe6122009-06-02 23:35:54 +01008178 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
8179 String action = filter.getAction(0);
8180 String category = filter.getCategory(0);
8181 while (it.hasNext()) {
8182 PreferredActivity pa = it.next();
Amith Yamasania3f133a2012-08-09 17:11:28 -07008183 if (pa.mUserId != callingUserId) continue;
Satish Sampath8dbe6122009-06-02 23:35:54 +01008184 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
Dianne Hackborn04505102012-02-29 12:34:04 -08008185 if (removed == null) {
8186 removed = new ArrayList<PreferredActivity>();
8187 }
8188 removed.add(pa);
8189 Log.i(TAG, "Removing preferred activity " + pa.mPref.mComponent + ":");
Satish Sampath8dbe6122009-06-02 23:35:54 +01008190 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
8191 }
8192 }
Dianne Hackborn04505102012-02-29 12:34:04 -08008193 if (removed != null) {
8194 for (int i=0; i<removed.size(); i++) {
8195 PreferredActivity pa = removed.get(i);
8196 mSettings.mPreferredActivities.removeFilter(pa);
8197 }
8198 }
Amith Yamasania3f133a2012-08-09 17:11:28 -07008199 addPreferredActivity(filter, match, set, activity, callingUserId);
Satish Sampath8dbe6122009-06-02 23:35:54 +01008200 }
8201 }
8202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008203 public void clearPackagePreferredActivities(String packageName) {
Kenny Root447106f2011-03-23 11:00:15 -07008204 final int uid = Binder.getCallingUid();
8205 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008206 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08008207 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008208 if (pkg == null || pkg.applicationInfo.uid != uid) {
8209 if (mContext.checkCallingOrSelfPermission(
8210 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
8211 != PackageManager.PERMISSION_GRANTED) {
Kenny Root447106f2011-03-23 11:00:15 -07008212 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008213 < Build.VERSION_CODES.FROYO) {
8214 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
8215 + Binder.getCallingUid());
8216 return;
8217 }
8218 mContext.enforceCallingOrSelfPermission(
8219 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
8220 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08008221 }
8222
Amith Yamasania3f133a2012-08-09 17:11:28 -07008223 if (clearPackagePreferredActivitiesLPw(packageName, UserHandle.getCallingUserId())) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07008224 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008225 }
8226 }
8227 }
8228
Amith Yamasania3f133a2012-08-09 17:11:28 -07008229 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
8230 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
Dianne Hackborn04505102012-02-29 12:34:04 -08008231 ArrayList<PreferredActivity> removed = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008232 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
8233 while (it.hasNext()) {
8234 PreferredActivity pa = it.next();
Amith Yamasania3f133a2012-08-09 17:11:28 -07008235 if (userId != UserHandle.USER_ALL && pa.mUserId != userId) {
8236 continue;
8237 }
Dianne Hackbornf8b8a3f2011-03-04 00:05:31 -08008238 if (pa.mPref.mComponent.getPackageName().equals(packageName)) {
Dianne Hackborn04505102012-02-29 12:34:04 -08008239 if (removed == null) {
8240 removed = new ArrayList<PreferredActivity>();
8241 }
8242 removed.add(pa);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008243 }
8244 }
Dianne Hackborn04505102012-02-29 12:34:04 -08008245 if (removed != null) {
8246 for (int i=0; i<removed.size(); i++) {
8247 PreferredActivity pa = removed.get(i);
8248 mSettings.mPreferredActivities.removeFilter(pa);
8249 }
8250 return true;
8251 }
8252 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008253 }
8254
8255 public int getPreferredActivities(List<IntentFilter> outFilters,
8256 List<ComponentName> outActivities, String packageName) {
8257
8258 int num = 0;
Amith Yamasania3f133a2012-08-09 17:11:28 -07008259 final int userId = UserHandle.getCallingUserId();
Kenny Root447106f2011-03-23 11:00:15 -07008260 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008261 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07008262 final Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008263 while (it.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07008264 final PreferredActivity pa = it.next();
Amith Yamasania3f133a2012-08-09 17:11:28 -07008265 if (pa.mUserId != userId) {
8266 continue;
8267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008268 if (packageName == null
Dianne Hackbornf8b8a3f2011-03-04 00:05:31 -08008269 || pa.mPref.mComponent.getPackageName().equals(packageName)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008270 if (outFilters != null) {
8271 outFilters.add(new IntentFilter(pa));
8272 }
8273 if (outActivities != null) {
Dianne Hackbornf8b8a3f2011-03-04 00:05:31 -08008274 outActivities.add(pa.mPref.mComponent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008275 }
8276 }
8277 }
8278 }
8279
8280 return num;
8281 }
8282
Amith Yamasani483f3b02012-03-13 16:08:00 -07008283 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008284 public void setApplicationEnabledSetting(String appPackageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07008285 int newState, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07008286 if (!sUserManager.exists(userId)) return;
Amith Yamasani483f3b02012-03-13 16:08:00 -07008287 setEnabledSetting(appPackageName, null, newState, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008288 }
8289
Amith Yamasani483f3b02012-03-13 16:08:00 -07008290 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008291 public void setComponentEnabledSetting(ComponentName componentName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07008292 int newState, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07008293 if (!sUserManager.exists(userId)) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008294 setEnabledSetting(componentName.getPackageName(),
Amith Yamasani483f3b02012-03-13 16:08:00 -07008295 componentName.getClassName(), newState, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008296 }
8297
8298 private void setEnabledSetting(
Amith Yamasani483f3b02012-03-13 16:08:00 -07008299 final String packageName, String className, int newState, final int flags, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008300 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
8301 || newState == COMPONENT_ENABLED_STATE_ENABLED
Dianne Hackborn0ac30312011-06-17 14:49:23 -07008302 || newState == COMPONENT_ENABLED_STATE_DISABLED
8303 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008304 throw new IllegalArgumentException("Invalid new component state: "
8305 + newState);
8306 }
8307 PackageSetting pkgSetting;
8308 final int uid = Binder.getCallingUid();
8309 final int permission = mContext.checkCallingPermission(
8310 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
Amith Yamasani483f3b02012-03-13 16:08:00 -07008311 checkValidCaller(uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008312 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008313 boolean sendNow = false;
8314 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08008315 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008316 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08008317 ArrayList<String> components;
Kenny Root447106f2011-03-23 11:00:15 -07008318
8319 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008320 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008321 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008322 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008323 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008324 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008325 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008326 }
8327 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008328 "Unknown component: " + packageName
8329 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008330 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07008331 // Allow root and verify that userId is not being specified by a different user
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008332 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008333 throw new SecurityException(
8334 "Permission Denial: attempt to change component state from pid="
8335 + Binder.getCallingPid()
Amith Yamasani13593602012-03-22 16:16:17 -07008336 + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008337 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008338 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008339 // We're dealing with an application/package level state change
Amith Yamasani483f3b02012-03-13 16:08:00 -07008340 if (pkgSetting.getEnabled(userId) == newState) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07008341 // Nothing to do
8342 return;
8343 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07008344 pkgSetting.setEnabled(newState, userId);
Amith Yamasani13593602012-03-22 16:16:17 -07008345 // pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008346 } else {
8347 // We're dealing with a component level state change
Dianne Hackborn65696252012-03-05 18:49:21 -08008348 // First, verify that this is a valid class name.
8349 PackageParser.Package pkg = pkgSetting.pkg;
8350 if (pkg == null || !pkg.hasComponentClassName(className)) {
8351 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
8352 throw new IllegalArgumentException("Component class " + className
8353 + " does not exist in " + packageName);
8354 } else {
8355 Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
8356 + className + " does not exist in " + packageName);
8357 }
8358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008359 switch (newState) {
8360 case COMPONENT_ENABLED_STATE_ENABLED:
Amith Yamasani483f3b02012-03-13 16:08:00 -07008361 if (!pkgSetting.enableComponentLPw(className, userId)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07008362 return;
8363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008364 break;
8365 case COMPONENT_ENABLED_STATE_DISABLED:
Amith Yamasani483f3b02012-03-13 16:08:00 -07008366 if (!pkgSetting.disableComponentLPw(className, userId)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07008367 return;
8368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008369 break;
8370 case COMPONENT_ENABLED_STATE_DEFAULT:
Amith Yamasani483f3b02012-03-13 16:08:00 -07008371 if (!pkgSetting.restoreComponentLPw(className, userId)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07008372 return;
8373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008374 break;
8375 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008376 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008377 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008378 }
8379 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07008380 mSettings.writePackageRestrictionsLPr(userId);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008381 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08008382 components = mPendingBroadcasts.get(packageName);
Kenny Root447106f2011-03-23 11:00:15 -07008383 final boolean newPackage = components == null;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08008384 if (newPackage) {
8385 components = new ArrayList<String>();
8386 }
8387 if (!components.contains(componentName)) {
8388 components.add(componentName);
8389 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008390 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
8391 sendNow = true;
8392 // Purge entry from pending broadcast list if another one exists already
8393 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08008394 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008395 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08008396 if (newPackage) {
8397 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008398 }
8399 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
8400 // Schedule a message
8401 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
8402 }
8403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008404 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008406 long callingId = Binder.clearCallingIdentity();
8407 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008408 if (sendNow) {
8409 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08008410 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008412 } finally {
8413 Binder.restoreCallingIdentity(callingId);
8414 }
8415 }
8416
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008417 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08008418 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
Kenny Root4dfe6ff2011-02-23 17:00:43 -08008419 if (DEBUG_INSTALL)
8420 Log.v(TAG, "Sending package changed: package=" + packageName + " components="
8421 + componentNames);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08008422 Bundle extras = new Bundle(4);
8423 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
8424 String nameList[] = new String[componentNames.size()];
8425 componentNames.toArray(nameList);
8426 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008427 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
8428 extras.putInt(Intent.EXTRA_UID, packageUid);
Amith Yamasani13593602012-03-22 16:16:17 -07008429 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008430 UserHandle.getUserId(packageUid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08008431 }
8432
Amith Yamasani483f3b02012-03-13 16:08:00 -07008433 public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07008434 if (!sUserManager.exists(userId)) return;
Dianne Hackborne7f97212011-02-24 14:40:20 -08008435 final int uid = Binder.getCallingUid();
8436 final int permission = mContext.checkCallingOrSelfPermission(
8437 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
8438 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Amith Yamasani483f3b02012-03-13 16:08:00 -07008439 checkValidCaller(uid, userId);
Kenny Root447106f2011-03-23 11:00:15 -07008440 // writer
Dianne Hackborne7f97212011-02-24 14:40:20 -08008441 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07008442 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
Amith Yamasani483f3b02012-03-13 16:08:00 -07008443 uid, userId)) {
8444 scheduleWritePackageRestrictionsLocked(userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08008445 }
8446 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008447 }
8448
Jacek Surazski65e13172009-04-28 15:26:38 +02008449 public String getInstallerPackageName(String packageName) {
Kenny Root447106f2011-03-23 11:00:15 -07008450 // reader
Jacek Surazski65e13172009-04-28 15:26:38 +02008451 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07008452 return mSettings.getInstallerPackageNameLPr(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02008453 }
8454 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008455
Amith Yamasani483f3b02012-03-13 16:08:00 -07008456 @Override
8457 public int getApplicationEnabledSetting(String packageName, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07008458 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
Amith Yamasani483f3b02012-03-13 16:08:00 -07008459 int uid = Binder.getCallingUid();
8460 checkValidCaller(uid, userId);
Kenny Root447106f2011-03-23 11:00:15 -07008461 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008462 synchronized (mPackages) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008463 return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008464 }
8465 }
8466
Amith Yamasani483f3b02012-03-13 16:08:00 -07008467 @Override
8468 public int getComponentEnabledSetting(ComponentName componentName, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07008469 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
Amith Yamasani483f3b02012-03-13 16:08:00 -07008470 int uid = Binder.getCallingUid();
8471 checkValidCaller(uid, userId);
Kenny Root447106f2011-03-23 11:00:15 -07008472 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008473 synchronized (mPackages) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008474 return mSettings.getComponentEnabledSettingLPr(componentName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008475 }
8476 }
8477
8478 public void enterSafeMode() {
Kenny Root461ff1f2011-08-09 09:43:03 -07008479 enforceSystemOrRoot("Only the system can request entering safe mode");
8480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008481 if (!mSystemReady) {
8482 mSafeMode = true;
8483 }
8484 }
8485
8486 public void systemReady() {
8487 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07008488
8489 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07008490 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07008491 mContext.getContentResolver(),
8492 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07008493 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07008494 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07008495 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07008496 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008497 }
8498
8499 public boolean isSafeMode() {
8500 return mSafeMode;
8501 }
8502
8503 public boolean hasSystemUidErrors() {
8504 return mHasSystemUidErrors;
8505 }
8506
8507 static String arrayToString(int[] array) {
8508 StringBuffer buf = new StringBuffer(128);
8509 buf.append('[');
8510 if (array != null) {
8511 for (int i=0; i<array.length; i++) {
8512 if (i > 0) buf.append(", ");
8513 buf.append(array[i]);
8514 }
8515 }
8516 buf.append(']');
8517 return buf.toString();
8518 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008519
Kenny Root447106f2011-03-23 11:00:15 -07008520 static class DumpState {
8521 public static final int DUMP_LIBS = 1 << 0;
8522
8523 public static final int DUMP_FEATURES = 1 << 1;
8524
8525 public static final int DUMP_RESOLVERS = 1 << 2;
8526
8527 public static final int DUMP_PERMISSIONS = 1 << 3;
8528
8529 public static final int DUMP_PACKAGES = 1 << 4;
8530
8531 public static final int DUMP_SHARED_USERS = 1 << 5;
8532
8533 public static final int DUMP_MESSAGES = 1 << 6;
8534
8535 public static final int DUMP_PROVIDERS = 1 << 7;
8536
Kenny Root05ca4c92011-09-15 10:36:25 -07008537 public static final int DUMP_VERIFIERS = 1 << 8;
8538
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07008539 public static final int DUMP_PREFERRED = 1 << 9;
8540
8541 public static final int DUMP_PREFERRED_XML = 1 << 10;
8542
Kenny Root447106f2011-03-23 11:00:15 -07008543 public static final int OPTION_SHOW_FILTERS = 1 << 0;
8544
8545 private int mTypes;
8546
8547 private int mOptions;
8548
8549 private boolean mTitlePrinted;
8550
8551 private SharedUserSetting mSharedUser;
8552
8553 public boolean isDumping(int type) {
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07008554 if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
Kenny Root447106f2011-03-23 11:00:15 -07008555 return true;
8556 }
8557
8558 return (mTypes & type) != 0;
8559 }
8560
8561 public void setDump(int type) {
8562 mTypes |= type;
8563 }
8564
8565 public boolean isOptionEnabled(int option) {
8566 return (mOptions & option) != 0;
8567 }
8568
8569 public void setOptionEnabled(int option) {
8570 mOptions |= option;
8571 }
8572
8573 public boolean onTitlePrinted() {
8574 final boolean printed = mTitlePrinted;
8575 mTitlePrinted = true;
8576 return printed;
8577 }
8578
8579 public boolean getTitlePrinted() {
8580 return mTitlePrinted;
8581 }
8582
8583 public void setTitlePrinted(boolean enabled) {
8584 mTitlePrinted = enabled;
8585 }
8586
8587 public SharedUserSetting getSharedUser() {
8588 return mSharedUser;
8589 }
8590
8591 public void setSharedUser(SharedUserSetting user) {
8592 mSharedUser = user;
8593 }
8594 }
8595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008596 @Override
8597 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
8598 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
8599 != PackageManager.PERMISSION_GRANTED) {
8600 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8601 + Binder.getCallingPid()
8602 + ", uid=" + Binder.getCallingUid()
8603 + " without permission "
8604 + android.Manifest.permission.DUMP);
8605 return;
8606 }
8607
Kenny Root447106f2011-03-23 11:00:15 -07008608 DumpState dumpState = new DumpState();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008609
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008610 String packageName = null;
8611
8612 int opti = 0;
8613 while (opti < args.length) {
8614 String opt = args[opti];
8615 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8616 break;
8617 }
8618 opti++;
8619 if ("-a".equals(opt)) {
8620 // Right now we only know how to print all.
8621 } else if ("-h".equals(opt)) {
8622 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008623 pw.println(" [-h] [-f] [cmd] ...");
8624 pw.println(" -f: print details of intent filters");
8625 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008626 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008627 pw.println(" l[ibraries]: list known shared libraries");
8628 pw.println(" f[ibraries]: list device features");
8629 pw.println(" r[esolvers]: dump intent resolvers");
8630 pw.println(" perm[issions]: dump permissions");
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07008631 pw.println(" pref[erred]: print preferred package settings");
8632 pw.println(" preferred-xml: print preferred package settings as xml");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008633 pw.println(" prov[iders]: dump content providers");
8634 pw.println(" p[ackages]: dump installed packages");
8635 pw.println(" s[hared-users]: dump shared user IDs");
8636 pw.println(" m[essages]: print collected runtime messages");
Kenny Root05ca4c92011-09-15 10:36:25 -07008637 pw.println(" v[erifiers]: print package verifier info");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008638 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008639 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008640 } else if ("-f".equals(opt)) {
Kenny Root447106f2011-03-23 11:00:15 -07008641 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008642 } else {
8643 pw.println("Unknown argument: " + opt + "; use -h for help");
8644 }
8645 }
8646
8647 // Is the caller requesting to dump a particular piece of data?
8648 if (opti < args.length) {
8649 String cmd = args[opti];
8650 opti++;
8651 // Is this a package name?
8652 if ("android".equals(cmd) || cmd.contains(".")) {
8653 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008654 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07008655 dumpState.setDump(DumpState.DUMP_LIBS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008656 } else if ("f".equals(cmd) || "features".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07008657 dumpState.setDump(DumpState.DUMP_FEATURES);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008658 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07008659 dumpState.setDump(DumpState.DUMP_RESOLVERS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008660 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07008661 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07008662 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
8663 dumpState.setDump(DumpState.DUMP_PREFERRED);
8664 } else if ("preferred-xml".equals(cmd)) {
8665 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008666 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07008667 dumpState.setDump(DumpState.DUMP_PACKAGES);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008668 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07008669 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008670 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07008671 dumpState.setDump(DumpState.DUMP_PROVIDERS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008672 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07008673 dumpState.setDump(DumpState.DUMP_MESSAGES);
Kenny Root05ca4c92011-09-15 10:36:25 -07008674 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
8675 dumpState.setDump(DumpState.DUMP_VERIFIERS);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008676 }
8677 }
Kenny Root447106f2011-03-23 11:00:15 -07008678
8679 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008680 synchronized (mPackages) {
Kenny Root05ca4c92011-09-15 10:36:25 -07008681 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
8682 if (dumpState.onTitlePrinted())
8683 pw.println(" ");
8684 pw.println("Verifiers:");
8685 pw.print(" Required: ");
8686 pw.print(mRequiredVerifierPackage);
8687 pw.print(" (uid=");
Amith Yamasani483f3b02012-03-13 16:08:00 -07008688 pw.print(getPackageUid(mRequiredVerifierPackage, 0));
Kenny Root05ca4c92011-09-15 10:36:25 -07008689 pw.println(")");
8690 }
8691
Kenny Root447106f2011-03-23 11:00:15 -07008692 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
8693 if (dumpState.onTitlePrinted())
8694 pw.println(" ");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008695 pw.println("Libraries:");
Kenny Root447106f2011-03-23 11:00:15 -07008696 final Iterator<String> it = mSharedLibraries.keySet().iterator();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008697 while (it.hasNext()) {
8698 String name = it.next();
8699 pw.print(" ");
8700 pw.print(name);
8701 pw.print(" -> ");
8702 pw.println(mSharedLibraries.get(name));
8703 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008704 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008705
Kenny Root447106f2011-03-23 11:00:15 -07008706 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
8707 if (dumpState.onTitlePrinted())
8708 pw.println(" ");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008709 pw.println("Features:");
8710 Iterator<String> it = mAvailableFeatures.keySet().iterator();
8711 while (it.hasNext()) {
8712 String name = it.next();
8713 pw.print(" ");
8714 pw.println(name);
8715 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008716 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008717
Kenny Root447106f2011-03-23 11:00:15 -07008718 if (dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
8719 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
8720 : "Activity Resolver Table:", " ", packageName,
8721 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
8722 dumpState.setTitlePrinted(true);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008723 }
Kenny Root447106f2011-03-23 11:00:15 -07008724 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
8725 : "Receiver Resolver Table:", " ", packageName,
8726 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
8727 dumpState.setTitlePrinted(true);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008728 }
Kenny Root447106f2011-03-23 11:00:15 -07008729 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
8730 : "Service Resolver Table:", " ", packageName,
8731 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
8732 dumpState.setTitlePrinted(true);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008733 }
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07008734 }
8735
8736 if (dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
Kenny Root447106f2011-03-23 11:00:15 -07008737 if (mSettings.mPreferredActivities.dump(pw,
8738 dumpState.getTitlePrinted() ? "\nPreferred Activities:"
8739 : "Preferred Activities:", " ",
8740 packageName, dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
8741 dumpState.setTitlePrinted(true);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008742 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008743 }
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07008744
8745 if (dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
8746 pw.flush();
8747 FileOutputStream fout = new FileOutputStream(fd);
8748 BufferedOutputStream str = new BufferedOutputStream(fout);
8749 XmlSerializer serializer = new FastXmlSerializer();
8750 try {
8751 serializer.setOutput(str, "utf-8");
8752 serializer.startDocument(null, true);
8753 serializer.setFeature(
8754 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
8755 mSettings.writePreferredActivitiesLPr(serializer);
8756 serializer.endDocument();
8757 serializer.flush();
8758 } catch (IllegalArgumentException e) {
8759 pw.println("Failed writing: " + e);
8760 } catch (IllegalStateException e) {
8761 pw.println("Failed writing: " + e);
8762 } catch (IOException e) {
8763 pw.println("Failed writing: " + e);
8764 }
8765 }
8766
Kenny Root447106f2011-03-23 11:00:15 -07008767 if (dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
8768 mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008769 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008770
Kenny Root447106f2011-03-23 11:00:15 -07008771 if (dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
8772 boolean printedSomething = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008773 for (PackageParser.Provider p : mProvidersByComponent.values()) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008774 if (packageName != null && !packageName.equals(p.info.packageName)) {
8775 continue;
8776 }
8777 if (!printedSomething) {
Kenny Root447106f2011-03-23 11:00:15 -07008778 if (dumpState.onTitlePrinted())
8779 pw.println(" ");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008780 pw.println("Registered ContentProviders:");
8781 printedSomething = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008782 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008783 pw.print(" "); pw.print(p.getComponentShortName()); pw.println(":");
8784 pw.print(" "); pw.println(p.toString());
8785 }
8786 printedSomething = false;
8787 for (Map.Entry<String, PackageParser.Provider> entry : mProviders.entrySet()) {
8788 PackageParser.Provider p = entry.getValue();
8789 if (packageName != null && !packageName.equals(p.info.packageName)) {
8790 continue;
8791 }
8792 if (!printedSomething) {
8793 if (dumpState.onTitlePrinted())
8794 pw.println(" ");
8795 pw.println("ContentProvider Authorities:");
8796 printedSomething = true;
8797 }
8798 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:");
8799 pw.print(" "); pw.println(p.toString());
Kenny Rooteca64b32012-06-25 16:37:32 -07008800 if (p.info != null && p.info.applicationInfo != null) {
8801 final String appInfo = p.info.applicationInfo.toString();
8802 pw.print(" applicationInfo="); pw.println(appInfo);
8803 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008804 }
8805 }
8806
Kenny Root447106f2011-03-23 11:00:15 -07008807 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
8808 mSettings.dumpPackagesLPr(pw, packageName, dumpState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008809 }
Kenny Root447106f2011-03-23 11:00:15 -07008810
8811 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
8812 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008813 }
Kenny Root447106f2011-03-23 11:00:15 -07008814
8815 if (dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
8816 if (dumpState.onTitlePrinted())
8817 pw.println(" ");
8818 mSettings.dumpReadMessagesLPr(pw, dumpState);
8819
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008820 pw.println(" ");
8821 pw.println("Package warning messages:");
Kenny Root447106f2011-03-23 11:00:15 -07008822 final File fname = getSettingsProblemFile();
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -08008823 FileInputStream in = null;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008824 try {
8825 in = new FileInputStream(fname);
Kenny Root447106f2011-03-23 11:00:15 -07008826 final int avail = in.available();
8827 final byte[] data = new byte[avail];
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008828 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008829 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008830 } catch (FileNotFoundException e) {
8831 } catch (IOException e) {
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -08008832 } finally {
8833 if (in != null) {
8834 try {
8835 in.close();
Kenny Root447106f2011-03-23 11:00:15 -07008836 } catch (IOException e) {
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -08008837 }
8838 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008839 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008841 }
8842 }
8843
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008844 // ------- apps on sdcard specific code -------
8845 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root447106f2011-03-23 11:00:15 -07008846
Kenny Root305bcbf2010-09-03 07:56:38 -07008847 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
Kenny Root447106f2011-03-23 11:00:15 -07008848
Kenny Root305bcbf2010-09-03 07:56:38 -07008849 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
Kenny Root447106f2011-03-23 11:00:15 -07008850
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008851 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008852
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008853 private String getEncryptKey() {
8854 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07008855 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
8856 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008857 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07008858 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
8859 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008860 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008861 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008862 return null;
8863 }
8864 }
8865 return sdEncKey;
8866 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008867 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008868 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07008869 } catch (IOException ioe) {
Kenny Root447106f2011-03-23 11:00:15 -07008870 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
Rich Cannings8d578832010-09-09 15:12:40 -07008871 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008872 }
Rich Cannings8d578832010-09-09 15:12:40 -07008873
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008874 }
8875
Kenny Root447106f2011-03-23 11:00:15 -07008876 /* package */static String getTempContainerId() {
Kenny Rootc78a8072010-07-27 15:18:38 -07008877 int tmpIdx = 1;
8878 String list[] = PackageHelper.getSecureContainerList();
8879 if (list != null) {
8880 for (final String name : list) {
8881 // Ignore null and non-temporary container entries
8882 if (name == null || !name.startsWith(mTempContainerPrefix)) {
8883 continue;
8884 }
8885
8886 String subStr = name.substring(mTempContainerPrefix.length());
8887 try {
8888 int cid = Integer.parseInt(subStr);
8889 if (cid >= tmpIdx) {
8890 tmpIdx = cid + 1;
8891 }
8892 } catch (NumberFormatException e) {
8893 }
8894 }
8895 }
8896 return mTempContainerPrefix + tmpIdx;
8897 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008898
Kenny Root447106f2011-03-23 11:00:15 -07008899 /*
8900 * Update media status on PackageManager.
8901 */
8902 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
8903 int callingUid = Binder.getCallingUid();
8904 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
8905 throw new SecurityException("Media status can only be updated by the system");
8906 }
8907 // reader; this apparently protects mMediaMounted, but should probably
8908 // be a different lock in that case.
8909 synchronized (mPackages) {
8910 Log.i(TAG, "Updating external media status from "
8911 + (mMediaMounted ? "mounted" : "unmounted") + " to "
8912 + (mediaStatus ? "mounted" : "unmounted"));
8913 if (DEBUG_SD_INSTALL)
8914 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
8915 + ", mMediaMounted=" + mMediaMounted);
8916 if (mediaStatus == mMediaMounted) {
8917 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
8918 : 0, -1);
8919 mHandler.sendMessage(msg);
8920 return;
8921 }
8922 mMediaMounted = mediaStatus;
8923 }
8924 // Queue up an async operation since the package installation may take a
8925 // little while.
8926 mHandler.post(new Runnable() {
8927 public void run() {
Kenny Root438a0ef2012-08-09 13:36:16 -07008928 updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
Kenny Root447106f2011-03-23 11:00:15 -07008929 }
8930 });
8931 }
8932
Kenny Root51a573c2012-05-17 13:30:28 -07008933 /**
8934 * Called by MountService when the initial ASECs to scan are available.
8935 * Should block until all the ASEC containers are finished being scanned.
8936 */
8937 public void scanAvailableAsecs() {
Kenny Root438a0ef2012-08-09 13:36:16 -07008938 updateExternalMediaStatusInner(true, false, false);
Kenny Root51a573c2012-05-17 13:30:28 -07008939 }
8940
Kenny Root447106f2011-03-23 11:00:15 -07008941 /*
8942 * Collect information of applications on external media, map them against
8943 * existing containers and update information based on current mount status.
8944 * Please note that we always have to report status if reportStatus has been
8945 * set to true especially when unloading packages.
8946 */
Kenny Root438a0ef2012-08-09 13:36:16 -07008947 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
8948 boolean externalStorage) {
Kenny Root447106f2011-03-23 11:00:15 -07008949 // Collection of uids
8950 int uidArr[] = null;
8951 // Collection of stale containers
8952 HashSet<String> removeCids = new HashSet<String>();
8953 // Collection of packages on external media with valid containers.
Kenny Root6dceb882012-04-12 14:23:49 -07008954 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
Kenny Root447106f2011-03-23 11:00:15 -07008955 // Get list of secure containers.
8956 final String list[] = PackageHelper.getSecureContainerList();
8957 if (list == null || list.length == 0) {
8958 Log.i(TAG, "No secure containers on sdcard");
8959 } else {
8960 // Process list of secure containers and categorize them
8961 // as active or stale based on their package internal state.
8962 int uidList[] = new int[list.length];
8963 int num = 0;
8964 // reader
8965 synchronized (mPackages) {
8966 for (String cid : list) {
Kenny Root447106f2011-03-23 11:00:15 -07008967 if (DEBUG_SD_INSTALL)
8968 Log.i(TAG, "Processing container " + cid);
Kenny Rootc7a89992012-06-05 15:13:17 -07008969 String pkgName = getAsecPackageName(cid);
Kenny Root447106f2011-03-23 11:00:15 -07008970 if (pkgName == null) {
8971 if (DEBUG_SD_INSTALL)
8972 Log.i(TAG, "Container : " + cid + " stale");
8973 removeCids.add(cid);
8974 continue;
8975 }
8976 if (DEBUG_SD_INSTALL)
8977 Log.i(TAG, "Looking for pkg : " + pkgName);
Kenny Rootc7a89992012-06-05 15:13:17 -07008978
8979 final PackageSetting ps = mSettings.mPackages.get(pkgName);
8980 if (ps == null) {
8981 Log.i(TAG, "Deleting container with no matching settings " + cid);
8982 removeCids.add(cid);
8983 continue;
8984 }
8985
Kenny Root438a0ef2012-08-09 13:36:16 -07008986 /*
8987 * Skip packages that are not external if we're unmounting
8988 * external storage.
8989 */
8990 if (externalStorage && !isMounted && !isExternal(ps)) {
8991 continue;
8992 }
8993
Kenny Rootc7a89992012-06-05 15:13:17 -07008994 final AsecInstallArgs args = new AsecInstallArgs(cid, isForwardLocked(ps));
Kenny Root447106f2011-03-23 11:00:15 -07008995 // The package status is changed only if the code path
8996 // matches between settings and the container id.
Kenny Rootc7a89992012-06-05 15:13:17 -07008997 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
8998 if (DEBUG_SD_INSTALL) {
Kenny Root447106f2011-03-23 11:00:15 -07008999 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
9000 + " at code path: " + ps.codePathString);
Kenny Rootc7a89992012-06-05 15:13:17 -07009001 }
9002
Kenny Root447106f2011-03-23 11:00:15 -07009003 // We do have a valid package installed on sdcard
9004 processCids.put(args, ps.codePathString);
Kenny Rootc7a89992012-06-05 15:13:17 -07009005 final int uid = ps.appId;
Kenny Root447106f2011-03-23 11:00:15 -07009006 if (uid != -1) {
9007 uidList[num++] = uid;
9008 }
9009 } else {
Kenny Rootc7a89992012-06-05 15:13:17 -07009010 Log.i(TAG, "Deleting stale container for " + cid);
Kenny Root447106f2011-03-23 11:00:15 -07009011 removeCids.add(cid);
9012 }
9013 }
9014 }
9015
9016 if (num > 0) {
9017 // Sort uid list
9018 Arrays.sort(uidList, 0, num);
9019 // Throw away duplicates
9020 uidArr = new int[num];
9021 uidArr[0] = uidList[0];
9022 int di = 0;
9023 for (int i = 1; i < num; i++) {
9024 if (uidList[i - 1] != uidList[i]) {
9025 uidArr[di++] = uidList[i];
9026 }
9027 }
9028 }
9029 }
9030 // Process packages with valid entries.
Kenny Root6dceb882012-04-12 14:23:49 -07009031 if (isMounted) {
Kenny Root447106f2011-03-23 11:00:15 -07009032 if (DEBUG_SD_INSTALL)
9033 Log.i(TAG, "Loading packages");
9034 loadMediaPackages(processCids, uidArr, removeCids);
9035 startCleaningPackages();
9036 } else {
9037 if (DEBUG_SD_INSTALL)
9038 Log.i(TAG, "Unloading packages");
9039 unloadMediaPackages(processCids, uidArr, reportStatus);
9040 }
9041 }
9042
9043 private void sendResourcesChangedBroadcast(boolean mediaStatus, ArrayList<String> pkgList,
9044 int uidArr[], IIntentReceiver finishedReceiver) {
9045 int size = pkgList.size();
9046 if (size > 0) {
9047 // Send broadcasts here
9048 Bundle extras = new Bundle();
9049 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
9050 .toArray(new String[size]));
9051 if (uidArr != null) {
9052 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9053 }
9054 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9055 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07009056 sendPackageBroadcast(action, null, extras, null, finishedReceiver, UserHandle.USER_ALL);
Kenny Root447106f2011-03-23 11:00:15 -07009057 }
9058 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009059
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009060 /*
Kenny Root447106f2011-03-23 11:00:15 -07009061 * Look at potentially valid container ids from processCids If package
9062 * information doesn't match the one on record or package scanning fails,
9063 * the cid is added to list of removeCids. We currently don't delete stale
9064 * containers.
9065 */
Kenny Root6dceb882012-04-12 14:23:49 -07009066 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
Kenny Root447106f2011-03-23 11:00:15 -07009067 HashSet<String> removeCids) {
9068 ArrayList<String> pkgList = new ArrayList<String>();
Kenny Root6dceb882012-04-12 14:23:49 -07009069 Set<AsecInstallArgs> keys = processCids.keySet();
Kenny Root447106f2011-03-23 11:00:15 -07009070 boolean doGc = false;
Kenny Root6dceb882012-04-12 14:23:49 -07009071 for (AsecInstallArgs args : keys) {
Kenny Root447106f2011-03-23 11:00:15 -07009072 String codePath = processCids.get(args);
9073 if (DEBUG_SD_INSTALL)
9074 Log.i(TAG, "Loading container : " + args.cid);
9075 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9076 try {
9077 // Make sure there are no container errors first.
9078 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
9079 Slog.e(TAG, "Failed to mount cid : " + args.cid
9080 + " when installing from sdcard");
9081 continue;
9082 }
9083 // Check code path here.
9084 if (codePath == null || !codePath.equals(args.getCodePath())) {
9085 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
9086 + " does not match one in settings " + codePath);
9087 continue;
9088 }
9089 // Parse package
Kenny Root51a573c2012-05-17 13:30:28 -07009090 int parseFlags = mDefParseFlags;
9091 if (args.isExternal()) {
9092 parseFlags |= PackageParser.PARSE_ON_SDCARD;
9093 }
Kenny Rootc7a89992012-06-05 15:13:17 -07009094 if (args.isFwdLocked()) {
9095 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
9096 }
Kenny Root51a573c2012-05-17 13:30:28 -07009097
Kenny Root447106f2011-03-23 11:00:15 -07009098 doGc = true;
9099 synchronized (mInstallLock) {
9100 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
9101 0, 0);
9102 // Scan the package
9103 if (pkg != null) {
9104 /*
9105 * TODO why is the lock being held? doPostInstall is
9106 * called in other places without the lock. This needs
9107 * to be straightened out.
9108 */
9109 // writer
9110 synchronized (mPackages) {
9111 retCode = PackageManager.INSTALL_SUCCEEDED;
9112 pkgList.add(pkg.packageName);
9113 // Post process args
Kenny Root6dceb882012-04-12 14:23:49 -07009114 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
9115 pkg.applicationInfo.uid);
Kenny Root447106f2011-03-23 11:00:15 -07009116 }
9117 } else {
9118 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard");
9119 }
9120 }
9121
9122 } finally {
9123 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9124 // Don't destroy container here. Wait till gc clears things
9125 // up.
9126 removeCids.add(args.cid);
9127 }
9128 }
9129 }
9130 // writer
9131 synchronized (mPackages) {
9132 // If the platform SDK has changed since the last time we booted,
9133 // we need to re-grant app permission to catch any new ones that
9134 // appear. This is really a hack, and means that apps can in some
9135 // cases get permissions that the user didn't initially explicitly
9136 // allow... it would be nice to have some better way to handle
9137 // this situation.
9138 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
9139 if (regrantPermissions)
9140 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
9141 + mSdkVersion + "; regranting permissions for external storage");
9142 mSettings.mExternalSdkPlatform = mSdkVersion;
9143
9144 // Make sure group IDs have been assigned, and any permission
9145 // changes in other apps are accounted for
Dianne Hackborne639da72012-02-21 15:11:13 -08009146 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
9147 | (regrantPermissions
9148 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
9149 : 0));
Kenny Root447106f2011-03-23 11:00:15 -07009150 // can downgrade to reader
9151 // Persist settings
9152 mSettings.writeLPr();
9153 }
9154 // Send a broadcast to let everyone know we are done processing
9155 if (pkgList.size() > 0) {
9156 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
9157 }
9158 // Force gc to avoid any stale parser references that we might have.
9159 if (doGc) {
9160 Runtime.getRuntime().gc();
9161 }
9162 // List stale containers and destroy stale temporary containers.
9163 if (removeCids != null) {
9164 for (String cid : removeCids) {
9165 if (cid.startsWith(mTempContainerPrefix)) {
9166 Log.i(TAG, "Destroying stale temporary container " + cid);
9167 PackageHelper.destroySdDir(cid);
9168 } else {
9169 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009170 }
9171 }
Kenny Root447106f2011-03-23 11:00:15 -07009172 }
9173 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009174
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009175 /*
Kenny Root447106f2011-03-23 11:00:15 -07009176 * Utility method to unload a list of specified containers
9177 */
Kenny Root6dceb882012-04-12 14:23:49 -07009178 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
Kenny Root447106f2011-03-23 11:00:15 -07009179 // Just unmount all valid containers.
Kenny Root6dceb882012-04-12 14:23:49 -07009180 for (AsecInstallArgs arg : cidArgs) {
Kenny Root447106f2011-03-23 11:00:15 -07009181 synchronized (mInstallLock) {
9182 arg.doPostDeleteLI(false);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009183 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009184 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009185 }
9186
Kenny Root447106f2011-03-23 11:00:15 -07009187 /*
9188 * Unload packages mounted on external media. This involves deleting package
9189 * data from internal structures, sending broadcasts about diabled packages,
9190 * gc'ing to free up references, unmounting all secure containers
9191 * corresponding to packages on external media, and posting a
9192 * UPDATED_MEDIA_STATUS message if status has been requested. Please note
9193 * that we always have to post this message if status has been requested no
9194 * matter what.
9195 */
Kenny Root6dceb882012-04-12 14:23:49 -07009196 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
Kenny Root447106f2011-03-23 11:00:15 -07009197 final boolean reportStatus) {
9198 if (DEBUG_SD_INSTALL)
9199 Log.i(TAG, "unloading media packages");
9200 ArrayList<String> pkgList = new ArrayList<String>();
Kenny Root6dceb882012-04-12 14:23:49 -07009201 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
9202 final Set<AsecInstallArgs> keys = processCids.keySet();
9203 for (AsecInstallArgs args : keys) {
Kenny Root447106f2011-03-23 11:00:15 -07009204 String pkgName = args.getPackageName();
9205 if (DEBUG_SD_INSTALL)
9206 Log.i(TAG, "Trying to unload pkg : " + pkgName);
9207 // Delete package internally
9208 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9209 synchronized (mInstallLock) {
9210 boolean res = deletePackageLI(pkgName, false, PackageManager.DONT_DELETE_DATA,
9211 outInfo, false);
9212 if (res) {
9213 pkgList.add(pkgName);
9214 } else {
9215 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
9216 failedList.add(args);
9217 }
9218 }
9219 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009220
Kenny Root447106f2011-03-23 11:00:15 -07009221 // reader
9222 synchronized (mPackages) {
9223 // We didn't update the settings after removing each package;
9224 // write them now for all packages.
9225 mSettings.writeLPr();
9226 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009227
Kenny Root447106f2011-03-23 11:00:15 -07009228 // We have to absolutely send UPDATED_MEDIA_STATUS only
9229 // after confirming that all the receivers processed the ordered
9230 // broadcast when packages get disabled, force a gc to clean things up.
9231 // and unload all the containers.
9232 if (pkgList.size() > 0) {
9233 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9234 public void performReceive(Intent intent, int resultCode, String data,
9235 Bundle extras, boolean ordered, boolean sticky) throws RemoteException {
9236 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9237 reportStatus ? 1 : 0, 1, keys);
9238 mHandler.sendMessage(msg);
9239 }
9240 });
9241 } else {
9242 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
9243 keys);
9244 mHandler.sendMessage(msg);
9245 }
9246 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009247
Kenny Root447106f2011-03-23 11:00:15 -07009248 public void movePackage(final String packageName, final IPackageMoveObserver observer,
9249 final int flags) {
9250 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
9251 int returnCode = PackageManager.MOVE_SUCCEEDED;
9252 int currFlags = 0;
9253 int newFlags = 0;
9254 // reader
9255 synchronized (mPackages) {
9256 PackageParser.Package pkg = mPackages.get(packageName);
9257 if (pkg == null) {
9258 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9259 } else {
9260 // Disable moving fwd locked apps and system packages
9261 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
9262 Slog.w(TAG, "Cannot move system application");
9263 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root447106f2011-03-23 11:00:15 -07009264 } else if (pkg.mOperationPending) {
9265 Slog.w(TAG, "Attempt to move package which has pending operations");
9266 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
9267 } else {
9268 // Find install location first
9269 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
9270 && (flags & PackageManager.MOVE_INTERNAL) != 0) {
9271 Slog.w(TAG, "Ambigous flags specified for move location.");
9272 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9273 } else {
9274 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
9275 : PackageManager.INSTALL_INTERNAL;
9276 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9277 : PackageManager.INSTALL_INTERNAL;
Kenny Rootbf023582012-05-02 16:56:15 -07009278
Kenny Root447106f2011-03-23 11:00:15 -07009279 if (newFlags == currFlags) {
9280 Slog.w(TAG, "No move required. Trying to move to same location");
9281 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Kenny Rootbf023582012-05-02 16:56:15 -07009282 } else {
9283 if (isForwardLocked(pkg)) {
9284 currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9285 newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9286 }
Kenny Root447106f2011-03-23 11:00:15 -07009287 }
9288 }
9289 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9290 pkg.mOperationPending = true;
9291 }
9292 }
9293 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009294
Kenny Root447106f2011-03-23 11:00:15 -07009295 /*
9296 * TODO this next block probably shouldn't be inside the lock. We
9297 * can't guarantee these won't change after this is fired off
9298 * anyway.
9299 */
9300 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root6dceb882012-04-12 14:23:49 -07009301 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1),
9302 returnCode);
Kenny Root447106f2011-03-23 11:00:15 -07009303 } else {
9304 Message msg = mHandler.obtainMessage(INIT_COPY);
9305 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -07009306 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
Kenny Root447106f2011-03-23 11:00:15 -07009307 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
Kenny Root6dceb882012-04-12 14:23:49 -07009308 pkg.applicationInfo.dataDir, pkg.applicationInfo.uid);
Kenny Root447106f2011-03-23 11:00:15 -07009309 msg.obj = mp;
9310 mHandler.sendMessage(msg);
9311 }
9312 }
9313 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009314
Kenny Root447106f2011-03-23 11:00:15 -07009315 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9316 // Queue up an async operation since the package deletion may take a
9317 // little while.
9318 mHandler.post(new Runnable() {
9319 public void run() {
9320 // TODO fix this; this does nothing.
9321 mHandler.removeCallbacks(this);
9322 int returnCode = currentStatus;
9323 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9324 int uidArr[] = null;
9325 ArrayList<String> pkgList = null;
9326 synchronized (mPackages) {
9327 PackageParser.Package pkg = mPackages.get(mp.packageName);
9328 if (pkg == null) {
9329 Slog.w(TAG, " Package " + mp.packageName
9330 + " doesn't exist. Aborting move");
9331 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9332 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9333 Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
9334 + mp.srcArgs.getCodePath() + " to "
9335 + pkg.applicationInfo.sourceDir
9336 + " Aborting move and returning error");
9337 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9338 } else {
9339 uidArr = new int[] {
9340 pkg.applicationInfo.uid
9341 };
9342 pkgList = new ArrayList<String>();
9343 pkgList.add(mp.packageName);
9344 }
9345 }
9346 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9347 // Send resources unavailable broadcast
9348 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
9349 // Update package code and resource paths
9350 synchronized (mInstallLock) {
9351 synchronized (mPackages) {
9352 PackageParser.Package pkg = mPackages.get(mp.packageName);
9353 // Recheck for package again.
Kenny Root6a6b0072010-10-07 16:46:10 -07009354 if (pkg == null) {
9355 Slog.w(TAG, " Package " + mp.packageName
9356 + " doesn't exist. Aborting move");
9357 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Kenny Root447106f2011-03-23 11:00:15 -07009358 } else if (!mp.srcArgs.getCodePath().equals(
9359 pkg.applicationInfo.sourceDir)) {
9360 Slog.w(TAG, "Package " + mp.packageName
9361 + " code path changed from " + mp.srcArgs.getCodePath()
9362 + " to " + pkg.applicationInfo.sourceDir
9363 + " Aborting move and returning error");
9364 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9365 } else {
9366 final String oldCodePath = pkg.mPath;
9367 final String newCodePath = mp.targetArgs.getCodePath();
9368 final String newResPath = mp.targetArgs.getResourcePath();
9369 final String newNativePath = mp.targetArgs
9370 .getNativeLibraryPath();
Kenny Root6a6b0072010-10-07 16:46:10 -07009371
Kenny Rootbf023582012-05-02 16:56:15 -07009372 try {
9373 final File newNativeDir = new File(newNativePath);
9374
9375 final String libParentDir = newNativeDir.getParentFile()
9376 .getCanonicalPath();
9377 if (newNativeDir.getParentFile().getCanonicalPath()
9378 .equals(pkg.applicationInfo.dataDir)) {
9379 if (mInstaller
9380 .unlinkNativeLibraryDirectory(pkg.applicationInfo.dataDir) < 0) {
9381 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9382 } else {
9383 NativeLibraryHelper.copyNativeBinariesIfNeededLI(
9384 new File(newCodePath), newNativeDir);
9385 }
Kenny Root6a6b0072010-10-07 16:46:10 -07009386 } else {
Kenny Rootbf023582012-05-02 16:56:15 -07009387 if (mInstaller.linkNativeLibraryDirectory(
9388 pkg.applicationInfo.dataDir, newNativePath) < 0) {
9389 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9390 }
Kenny Root6a6b0072010-10-07 16:46:10 -07009391 }
Kenny Rootbf023582012-05-02 16:56:15 -07009392 } catch (IOException e) {
9393 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Kenny Root6a6b0072010-10-07 16:46:10 -07009394 }
9395
Kenny Rootbf023582012-05-02 16:56:15 -07009396
Kenny Root6a6b0072010-10-07 16:46:10 -07009397 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9398 pkg.mPath = newCodePath;
9399 // Move dex files around
9400 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
9401 // Moving of dex files failed. Set
9402 // error code and abort move.
9403 pkg.mPath = pkg.mScanPath;
9404 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9405 }
9406 }
9407
9408 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
Kenny Root447106f2011-03-23 11:00:15 -07009409 pkg.mScanPath = newCodePath;
9410 pkg.applicationInfo.sourceDir = newCodePath;
9411 pkg.applicationInfo.publicSourceDir = newResPath;
9412 pkg.applicationInfo.nativeLibraryDir = newNativePath;
9413 PackageSetting ps = (PackageSetting) pkg.mExtras;
9414 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9415 ps.codePathString = ps.codePath.getPath();
9416 ps.resourcePath = new File(
9417 pkg.applicationInfo.publicSourceDir);
9418 ps.resourcePathString = ps.resourcePath.getPath();
9419 ps.nativeLibraryPathString = newNativePath;
9420 // Set the application info flag
9421 // correctly.
9422 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9423 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9424 } else {
9425 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9426 }
9427 ps.setFlags(pkg.applicationInfo.flags);
9428 mAppDirs.remove(oldCodePath);
9429 mAppDirs.put(newCodePath, pkg);
9430 // Persist settings
9431 mSettings.writeLPr();
9432 }
9433 }
9434 }
9435 }
9436 // Send resources available broadcast
9437 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
9438 }
9439 }
9440 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9441 // Clean up failed installation
9442 if (mp.targetArgs != null) {
Kenny Root6dceb882012-04-12 14:23:49 -07009443 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
9444 -1);
Kenny Root447106f2011-03-23 11:00:15 -07009445 }
9446 } else {
9447 // Force a gc to clear things up.
9448 Runtime.getRuntime().gc();
9449 // Delete older code
9450 synchronized (mInstallLock) {
9451 mp.srcArgs.doPostDeleteLI(true);
9452 }
9453 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009454
Kenny Root447106f2011-03-23 11:00:15 -07009455 // Allow more operations on this file if we didn't fail because
9456 // an operation was already pending for this package.
9457 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
9458 synchronized (mPackages) {
9459 PackageParser.Package pkg = mPackages.get(mp.packageName);
9460 if (pkg != null) {
9461 pkg.mOperationPending = false;
Kenny Rootdeb11262010-08-02 11:36:21 -07009462 }
9463 }
Kenny Root447106f2011-03-23 11:00:15 -07009464 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009465
Kenny Root447106f2011-03-23 11:00:15 -07009466 IPackageMoveObserver observer = mp.observer;
9467 if (observer != null) {
9468 try {
9469 observer.packageMoved(mp.packageName, returnCode);
9470 } catch (RemoteException e) {
9471 Log.i(TAG, "Observer no longer exists.");
9472 }
9473 }
9474 }
9475 });
9476 }
9477
9478 public boolean setInstallLocation(int loc) {
9479 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
9480 null);
9481 if (getInstallLocation() == loc) {
9482 return true;
9483 }
9484 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
9485 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9486 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9487 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9488 return true;
9489 }
9490 return false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009491 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009492
Kenny Root447106f2011-03-23 11:00:15 -07009493 public int getInstallLocation() {
9494 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9495 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION,
9496 PackageHelper.APP_INSTALL_AUTO);
9497 }
Amith Yamasani0b285492011-04-14 17:35:23 -07009498
Amith Yamasani258848d2012-08-10 17:06:33 -07009499 /** Called by UserManagerService */
9500 void cleanUpUser(int userHandle) {
Amith Yamasani13593602012-03-22 16:16:17 -07009501 // Disable all the packages for the user first
9502 synchronized (mPackages) {
9503 Set<Entry<String, PackageSetting>> entries = mSettings.mPackages.entrySet();
9504 for (Entry<String, PackageSetting> entry : entries) {
Amith Yamasani258848d2012-08-10 17:06:33 -07009505 entry.getValue().removeUser(userHandle);
Amith Yamasani13593602012-03-22 16:16:17 -07009506 }
Amith Yamasani258848d2012-08-10 17:06:33 -07009507 if (mDirtyUsers.remove(userHandle));
9508 mSettings.removeUserLPr(userHandle);
Amith Yamasani13593602012-03-22 16:16:17 -07009509 }
9510 }
9511
Kenny Root0aaa0d92011-09-12 16:42:55 -07009512 @Override
9513 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
9514 mContext.enforceCallingOrSelfPermission(
9515 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9516 "Only package verification agents can read the verifier device identity");
9517
9518 synchronized (mPackages) {
9519 return mSettings.getVerifierDeviceIdentityLPw();
9520 }
9521 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009522
Amith Yamasani13593602012-03-22 16:16:17 -07009523 @Override
Jeff Sharkey5d32e772012-04-12 15:59:23 -07009524 public void setPermissionEnforced(String permission, boolean enforced) {
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07009525 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
9526 if (READ_EXTERNAL_STORAGE.equals(permission)) {
9527 synchronized (mPackages) {
Jeff Sharkeyf5385772012-05-11 14:04:41 -07009528 if (mSettings.mReadExternalStorageEnforced == null
9529 || mSettings.mReadExternalStorageEnforced != enforced) {
Jeff Sharkey5d32e772012-04-12 15:59:23 -07009530 mSettings.mReadExternalStorageEnforced = enforced;
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07009531 mSettings.writeLPr();
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07009532
9533 // kill any non-foreground processes so we restart them and
9534 // grant/revoke the GID.
9535 final IActivityManager am = ActivityManagerNative.getDefault();
9536 if (am != null) {
9537 final long token = Binder.clearCallingIdentity();
9538 try {
9539 am.killProcessesBelowForeground("setPermissionEnforcement");
9540 } catch (RemoteException e) {
9541 } finally {
9542 Binder.restoreCallingIdentity(token);
9543 }
9544 }
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07009545 }
9546 }
9547 } else {
9548 throw new IllegalArgumentException("No selective enforcement for " + permission);
9549 }
9550 }
9551
9552 @Override
Jeff Sharkey5d32e772012-04-12 15:59:23 -07009553 public boolean isPermissionEnforced(String permission) {
Jeff Sharkey5d32e772012-04-12 15:59:23 -07009554 synchronized (mPackages) {
9555 return isPermissionEnforcedLocked(permission);
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07009556 }
9557 }
9558
9559 private boolean isPermissionEnforcedLocked(String permission) {
9560 if (READ_EXTERNAL_STORAGE.equals(permission)) {
Jeff Sharkeyf5385772012-05-11 14:04:41 -07009561 if (mSettings.mReadExternalStorageEnforced != null) {
9562 return mSettings.mReadExternalStorageEnforced;
9563 } else {
9564 // if user hasn't defined, fall back to secure default
9565 return Secure.getInt(mContext.getContentResolver(),
9566 Secure.READ_EXTERNAL_STORAGE_ENFORCED_DEFAULT, 0) != 0;
9567 }
Jeff Sharkey5d32e772012-04-12 15:59:23 -07009568 } else {
9569 return true;
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07009570 }
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07009571 }
Jeff Sharkeyf6f7f1d2012-06-12 17:12:08 -07009572
9573 public boolean isStorageLow() {
9574 final long token = Binder.clearCallingIdentity();
9575 try {
9576 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
9577 .getService(DeviceStorageMonitorService.SERVICE);
9578 return dsm.isMemoryLow();
9579 } finally {
9580 Binder.restoreCallingIdentity(token);
9581 }
9582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009583}