blob: 5220a7d20169565327a938c767732e9221af5229 [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;
Dianne Hackborn7767eac2012-08-23 18:25:40 -070067import android.content.pm.PackageCleanItem;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080069import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.content.pm.PackageManager;
Jason parksa3cdaa52011-01-13 14:15:43 -060071import android.content.pm.PackageParser;
Dianne Hackborn7767eac2012-08-23 18:25:40 -070072import android.content.pm.PackageUserState;
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -070073import android.content.pm.PackageParser.ActivityIntentInfo;
Kenny Root27989422011-02-23 16:28:26 -080074import android.content.pm.PackageStats;
Kenny Root0e2c0f32011-04-15 17:50:10 -070075import android.content.pm.ParceledListSlice;
Jason parksa3cdaa52011-01-13 14:15:43 -060076import android.content.pm.PermissionGroupInfo;
Kenny Root27989422011-02-23 16:28:26 -080077import android.content.pm.PermissionInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.content.pm.ProviderInfo;
79import android.content.pm.ResolveInfo;
80import android.content.pm.ServiceInfo;
81import android.content.pm.Signature;
Kenny Root5ab21572011-07-27 11:11:19 -070082import android.content.pm.ManifestDigest;
rich cannings706e8ba2012-08-20 13:20:14 -070083import android.content.pm.VerificationParams;
Kenny Root0aaa0d92011-09-12 16:42:55 -070084import android.content.pm.VerifierDeviceIdentity;
Kenny Root05ca4c92011-09-15 10:36:25 -070085import android.content.pm.VerifierInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.net.Uri;
87import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070088import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.os.Bundle;
Kenny Root27989422011-02-23 16:28:26 -080090import android.os.Environment;
91import android.os.FileObserver;
92import android.os.FileUtils;
93import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080095import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070096import android.os.Looper;
97import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import android.os.Parcel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import android.os.ParcelFileDescriptor;
100import android.os.Process;
Kenny Root27989422011-02-23 16:28:26 -0800101import android.os.RemoteException;
rpcraig554cb0c2012-07-05 06:41:43 -0400102import android.os.SELinux;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import android.os.ServiceManager;
104import android.os.SystemClock;
105import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700106import android.os.UserHandle;
Jeff Sharkeyf5385772012-05-11 14:04:41 -0700107import android.provider.Settings.Secure;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800108import android.security.SystemKeyStore;
Kenny Root27989422011-02-23 16:28:26 -0800109import android.util.DisplayMetrics;
110import android.util.EventLog;
111import android.util.Log;
112import android.util.LogPrinter;
113import android.util.Slog;
114import android.util.SparseArray;
115import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116import android.view.Display;
117import android.view.WindowManager;
118
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -0700119import java.io.BufferedOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120import java.io.File;
121import java.io.FileDescriptor;
122import java.io.FileInputStream;
123import java.io.FileNotFoundException;
124import java.io.FileOutputStream;
125import java.io.FileReader;
126import java.io.FilenameFilter;
127import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800129import java.security.NoSuchAlgorithmException;
Kenny Root05ca4c92011-09-15 10:36:25 -0700130import java.security.PublicKey;
131import java.security.cert.CertificateException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800132import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133import java.util.ArrayList;
134import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700135import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136import java.util.Collections;
137import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800138import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139import java.util.HashMap;
140import java.util.HashSet;
141import java.util.Iterator;
142import java.util.List;
143import java.util.Map;
Amith Yamasani13593602012-03-22 16:16:17 -0700144import java.util.Map.Entry;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146
Kenny Root66269ea2011-07-12 14:14:01 -0700147import libcore.io.ErrnoException;
Kenny Root3f99afc2012-04-14 10:13:10 -0700148import libcore.io.IoUtils;
Kenny Root66269ea2011-07-12 14:14:01 -0700149import libcore.io.Libcore;
Kenny Root786cbca2012-08-16 11:10:58 -0700150import libcore.io.StructStat;
Kenny Root66269ea2011-07-12 14:14:01 -0700151
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700152/**
153 * Keep track of all those .apks everywhere.
154 *
155 * This is very central to the platform's security; please run the unit
156 * tests whenever making modifications here:
157 *
158mmm frameworks/base/tests/AndroidTests
159adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
160adb 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 -0700161 *
162 * {@hide}
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700163 */
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700164public class PackageManagerService extends IPackageManager.Stub {
165 static final String TAG = "PackageManager";
166 static final boolean DEBUG_SETTINGS = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 private static final boolean DEBUG_PREFERRED = false;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700168 static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800169 private static final boolean DEBUG_INSTALL = false;
Kenny Root9718cf52011-02-23 16:45:26 -0800170 private static final boolean DEBUG_REMOVE = false;
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700171 private static final boolean DEBUG_BROADCASTS = false;
Kenny Root9718cf52011-02-23 16:45:26 -0800172 private static final boolean DEBUG_SHOW_INFO = false;
173 private static final boolean DEBUG_PACKAGE_INFO = false;
174 private static final boolean DEBUG_INTENT_MATCHING = false;
175 private static final boolean DEBUG_PACKAGE_SCANNING = false;
176 private static final boolean DEBUG_APP_DIR_OBSERVER = false;
Kenny Root05ca4c92011-09-15 10:36:25 -0700177 private static final boolean DEBUG_VERIFY = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400180 private static final int LOG_UID = Process.LOG_UID;
Nick Pellycd0e8392010-10-13 17:25:24 -0700181 private static final int NFC_UID = Process.NFC_UID;
Jaikumar Ganesh1abb1cb2012-01-25 16:14:50 -0800182 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 private static final boolean GET_CERTIFICATES = true;
185
186 private static final int REMOVE_EVENTS =
187 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
188 private static final int ADD_EVENTS =
189 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
190
191 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800192 // Suffix used during package installation when copying/moving
193 // package apks to install directory.
194 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195
196 static final int SCAN_MONITOR = 1<<0;
197 static final int SCAN_NO_DEX = 1<<1;
198 static final int SCAN_FORCE_DEX = 1<<2;
199 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800200 static final int SCAN_NEW_INSTALL = 1<<4;
201 static final int SCAN_NO_PATHS = 1<<5;
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700202 static final int SCAN_UPDATE_TIME = 1<<6;
Dianne Hackborn661cd522011-08-22 00:26:20 -0700203 static final int SCAN_DEFER_DEX = 1<<7;
Dianne Hackbornd0c5f512012-06-07 16:53:59 -0700204 static final int SCAN_BOOTING = 1<<8;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700206 static final int REMOVE_CHATTY = 1<<16;
Kenny Root11128572010-10-11 10:51:32 -0700207
Kenny Root5ab21572011-07-27 11:11:19 -0700208 /**
209 * Whether verification is enabled by default.
210 */
Brett Chabotae05e862011-08-24 18:38:26 -0700211 // STOPSHIP: change this to true
212 private static final boolean DEFAULT_VERIFY_ENABLE = false;
Kenny Root5ab21572011-07-27 11:11:19 -0700213
214 /**
215 * The default maximum time to wait for the verification agent to return in
216 * milliseconds.
217 */
rich canningsaa8513e2012-05-21 16:15:23 -0700218 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
Kenny Root5ab21572011-07-27 11:11:19 -0700219
rich canningsa6cfe522012-05-21 15:50:56 -0700220 /**
221 * The default response for package verification timeout.
222 *
223 * This can be either PackageManager.VERIFICATION_ALLOW or
224 * PackageManager.VERIFICATION_REJECT.
225 */
226 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
227
Kenny Root11128572010-10-11 10:51:32 -0700228 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
229
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800230 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
Kenny Root11128572010-10-11 10:51:32 -0700231 DEFAULT_CONTAINER_PACKAGE,
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800232 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700233
Kenny Root05ca4c92011-09-15 10:36:25 -0700234 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
235
Kenny Root85387d72010-08-26 10:13:11 -0700236 private static final String LIB_DIR_NAME = "lib";
237
Kenny Rootc78a8072010-07-27 15:18:38 -0700238 static final String mTempContainerPrefix = "smdl2tmp";
239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
241 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700242 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
Dianne Hackborn851a5412009-05-08 12:06:44 -0700244 final int mSdkVersion = Build.VERSION.SDK_INT;
245 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
246 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 final Context mContext;
249 final boolean mFactoryTest;
Dianne Hackbornd2509fd2011-09-12 12:29:43 -0700250 final boolean mOnlyCore;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700251 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 final DisplayMetrics mMetrics;
253 final int mDefParseFlags;
254 final String[] mSeparateProcesses;
255
256 // This is where all application persistent data goes.
257 final File mAppDataDir;
258
Amith Yamasani0b285492011-04-14 17:35:23 -0700259 // This is where all application persistent data goes for secondary users.
260 final File mUserAppDataDir;
261
Kenny Root51a573c2012-05-17 13:30:28 -0700262 /** The location for ASEC container files on internal storage. */
263 final String mAsecInternalPath;
264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 // This is the object monitoring the framework dir.
266 final FileObserver mFrameworkInstallObserver;
267
268 // This is the object monitoring the system app dir.
269 final FileObserver mSystemInstallObserver;
270
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700271 // This is the object monitoring the system app dir.
272 final FileObserver mVendorInstallObserver;
273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274 // This is the object monitoring mAppInstallDir.
275 final FileObserver mAppInstallObserver;
276
277 // This is the object monitoring mDrmAppPrivateInstallDir.
278 final FileObserver mDrmAppInstallObserver;
279
280 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
281 // LOCK HELD. Can be called with mInstallLock held.
282 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284 final File mFrameworkDir;
285 final File mSystemAppDir;
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700286 final File mVendorAppDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700288 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289
290 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
291 // apps.
292 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296 // Lock for state used when installing and doing other long running
297 // operations. Methods that must be called with this lock held have
298 // the prefix "LI".
299 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 // These are the directories in the 3rd party applications installed dir
302 // that we have currently loaded packages from. Keys are the application's
303 // installed zip file (absolute codePath), and values are Package.
304 final HashMap<String, PackageParser.Package> mAppDirs =
305 new HashMap<String, PackageParser.Package>();
306
307 // Information for the parser to write more useful error messages.
308 File mScanningPath;
309 int mLastScanError;
310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 // Keys are String (package name), values are Package. This also serves
314 // as the lock for the global state. Methods that must be called with
315 // this lock held have the prefix "LP".
316 final HashMap<String, PackageParser.Package> mPackages =
317 new HashMap<String, PackageParser.Package>();
318
319 final Settings mSettings;
320 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321
322 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
323 int[] mGlobalGids;
324
325 // These are the built-in uid -> permission mappings that were read from the
326 // etc/permissions.xml file.
327 final SparseArray<HashSet<String>> mSystemPermissions =
328 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 // These are the built-in shared libraries that were read from the
331 // etc/permissions.xml file.
332 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800333
Dianne Hackborn49237342009-08-27 20:08:01 -0700334 // Temporary for building the final shared libraries for an .apk.
335 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800336
Dianne Hackborn49237342009-08-27 20:08:01 -0700337 // These are the features this devices supports that were read from the
338 // etc/permissions.xml file.
339 final HashMap<String, FeatureInfo> mAvailableFeatures =
340 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342 // All available activities, for your resolving pleasure.
343 final ActivityIntentResolver mActivities =
344 new ActivityIntentResolver();
345
346 // All available receivers, for your resolving pleasure.
347 final ActivityIntentResolver mReceivers =
348 new ActivityIntentResolver();
349
350 // All available services, for your resolving pleasure.
351 final ServiceIntentResolver mServices = new ServiceIntentResolver();
352
353 // Keys are String (provider class name), values are Provider.
354 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
355 new HashMap<ComponentName, PackageParser.Provider>();
356
357 // Mapping from provider base names (first directory in content URI codePath)
358 // to the provider information.
359 final HashMap<String, PackageParser.Provider> mProviders =
360 new HashMap<String, PackageParser.Provider>();
361
362 // Mapping from instrumentation class names to info about them.
363 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
364 new HashMap<ComponentName, PackageParser.Instrumentation>();
365
366 // Mapping from permission names to info about them.
367 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
368 new HashMap<String, PackageParser.PermissionGroup>();
369
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800370 // Packages whose data we have transfered into another package, thus
371 // should no longer exist.
372 final HashSet<String> mTransferedPackages = new HashSet<String>();
373
Dianne Hackborn854060af2009-07-09 18:14:31 -0700374 // Broadcast actions that are only available to the system.
375 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800376
Kenny Root5ab21572011-07-27 11:11:19 -0700377 /** List of packages waiting for verification. */
Kenny Root05ca4c92011-09-15 10:36:25 -0700378 final SparseArray<PackageVerificationState> mPendingVerification
379 = new SparseArray<PackageVerificationState>();
Kenny Root5ab21572011-07-27 11:11:19 -0700380
Dianne Hackborn661cd522011-08-22 00:26:20 -0700381 final ArrayList<PackageParser.Package> mDeferredDexOpt =
382 new ArrayList<PackageParser.Package>();
383
Kenny Root5ab21572011-07-27 11:11:19 -0700384 /** Token for keys in mPendingVerification. */
385 private int mPendingVerificationToken = 0;
386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 boolean mSystemReady;
388 boolean mSafeMode;
389 boolean mHasSystemUidErrors;
390
391 ApplicationInfo mAndroidApplication;
392 final ActivityInfo mResolveActivity = new ActivityInfo();
393 final ResolveInfo mResolveInfo = new ResolveInfo();
394 ComponentName mResolveComponentName;
395 PackageParser.Package mPlatformPackage;
396
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700397 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800398 final HashMap<String, ArrayList<String>> mPendingBroadcasts
399 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800400 // Service Connection to remote media container service to copy
401 // package uri's from external media onto secure containers
402 // or internal storage.
403 private IMediaContainerService mContainerService = null;
Amith Yamasani6ec10122012-08-23 13:49:25 -0700404 private int mContainerServiceUserId;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800405
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700406 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800407 static final int MCS_BOUND = 3;
408 static final int END_COPY = 4;
409 static final int INIT_COPY = 5;
410 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800411 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800412 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800413 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800414 static final int MCS_RECONNECT = 10;
415 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700416 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700417 static final int WRITE_SETTINGS = 13;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700418 static final int WRITE_PACKAGE_RESTRICTIONS = 14;
Kenny Root5ab21572011-07-27 11:11:19 -0700419 static final int PACKAGE_VERIFIED = 15;
420 static final int CHECK_PENDING_VERIFICATION = 16;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700421
422 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800423
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700424 // Delay time in millisecs
425 static final int BROADCAST_DELAY = 10 * 1000;
Kenny Root9718cf52011-02-23 16:45:26 -0800426
Amith Yamasani258848d2012-08-10 17:06:33 -0700427 static UserManagerService sUserManager;
Amith Yamasani0b285492011-04-14 17:35:23 -0700428
Amith Yamasani483f3b02012-03-13 16:08:00 -0700429 // Stores a list of users whose package restrictions file needs to be updated
430 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
431
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800432 final private DefaultContainerConnection mDefContainerConn =
433 new DefaultContainerConnection();
434 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800435 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800436 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800437 IMediaContainerService imcs =
438 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800439 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800440 }
441
442 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800443 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800444 }
445 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700446
Christopher Tate1bb69062010-02-19 17:02:12 -0800447 // Recordkeeping of restore-after-install operations that are currently in flight
448 // between the Package Manager and the Backup Manager
449 class PostInstallData {
450 public InstallArgs args;
451 public PackageInstalledInfo res;
452
453 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
454 args = _a;
455 res = _r;
456 }
457 };
458 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
459 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
460
Kenny Root05ca4c92011-09-15 10:36:25 -0700461 private final String mRequiredVerifierPackage;
462
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700463 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800464 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800465 final ArrayList<HandlerParams> mPendingInstalls =
466 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800467
468 private boolean connectToService() {
469 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
470 " DefaultContainerService");
471 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700472 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Amith Yamasani6ec10122012-08-23 13:49:25 -0700473 mContainerServiceUserId = 0;
474 if (mPendingInstalls.size() > 0) {
475 mContainerServiceUserId = mPendingInstalls.get(0).getUser().getIdentifier();
Amith Yamasani2b914652012-08-27 12:04:40 -0700476 if (mContainerServiceUserId == UserHandle.USER_ALL) {
477 mContainerServiceUserId = 0;
478 }
Amith Yamasani6ec10122012-08-23 13:49:25 -0700479 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800480 if (mContext.bindService(service, mDefContainerConn,
Amith Yamasani6ec10122012-08-23 13:49:25 -0700481 Context.BIND_AUTO_CREATE, mContainerServiceUserId)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700482 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800483 mBound = true;
484 return true;
485 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700486 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800487 return false;
488 }
489
490 private void disconnectService() {
491 mContainerService = null;
492 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700493 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800494 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700495 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800496 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800497
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700498 PackageHandler(Looper looper) {
499 super(looper);
500 }
Dianne Hackborn7d608422011-08-07 16:24:18 -0700501
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700502 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700503 try {
504 doHandleMessage(msg);
505 } finally {
506 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
507 }
508 }
509
510 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700511 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800512 case INIT_COPY: {
Kenny Root5ab21572011-07-27 11:11:19 -0700513 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800514 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800515 int idx = mPendingInstalls.size();
Kenny Root5ab21572011-07-27 11:11:19 -0700516 if (DEBUG_INSTALL) Slog.i(TAG, "idx=" + idx);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800517 // If a bind was already initiated we dont really
518 // need to do anything. The pending install
519 // will be processed later on.
520 if (!mBound) {
521 // If this is the only one pending we might
522 // have to bind to the service again.
523 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800524 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800525 params.serviceError();
526 return;
527 } else {
528 // Once we bind to the service, the first
529 // pending request will be processed.
530 mPendingInstalls.add(idx, params);
531 }
532 } else {
533 mPendingInstalls.add(idx, params);
534 // Already bound to the service. Just make
535 // sure we trigger off processing the first request.
536 if (idx == 0) {
537 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800538 }
539 }
540 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800541 }
542 case MCS_BOUND: {
Kenny Root5ab21572011-07-27 11:11:19 -0700543 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800544 if (msg.obj != null) {
545 mContainerService = (IMediaContainerService) msg.obj;
546 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800547 if (mContainerService == null) {
548 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800549 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800550 for (HandlerParams params : mPendingInstalls) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800551 // Indicate service bind error
552 params.serviceError();
553 }
554 mPendingInstalls.clear();
555 } else if (mPendingInstalls.size() > 0) {
556 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800557 if (params != null) {
Amith Yamasani6ec10122012-08-23 13:49:25 -0700558 // Check if we're connected to the correct service, if it's an install
559 // request.
Amith Yamasani2b914652012-08-27 12:04:40 -0700560 final int installFor = params.getUser().getIdentifier();
561 if (installFor != mContainerServiceUserId
562 && (installFor == UserHandle.USER_ALL
563 && mContainerServiceUserId != 0)) {
Amith Yamasani6ec10122012-08-23 13:49:25 -0700564 mHandler.sendEmptyMessage(MCS_RECONNECT);
565 return;
566 }
Dianne Hackborn7d608422011-08-07 16:24:18 -0700567 if (params.startCopy()) {
568 // We are done... look for more work or to
569 // go idle.
570 if (DEBUG_SD_INSTALL) Log.i(TAG,
571 "Checking for more work or unbind...");
572 // Delete pending install
573 if (mPendingInstalls.size() > 0) {
574 mPendingInstalls.remove(0);
575 }
576 if (mPendingInstalls.size() == 0) {
577 if (mBound) {
578 if (DEBUG_SD_INSTALL) Log.i(TAG,
579 "Posting delayed MCS_UNBIND");
580 removeMessages(MCS_UNBIND);
581 Message ubmsg = obtainMessage(MCS_UNBIND);
582 // Unbind after a little delay, to avoid
583 // continual thrashing.
584 sendMessageDelayed(ubmsg, 10000);
585 }
586 } else {
587 // There are more pending requests in queue.
588 // Just post MCS_BOUND message to trigger processing
589 // of next pending install.
590 if (DEBUG_SD_INSTALL) Log.i(TAG,
591 "Posting MCS_BOUND for next woek");
592 mHandler.sendEmptyMessage(MCS_BOUND);
593 }
594 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800595 }
596 } else {
597 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800598 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800599 }
600 break;
601 }
Kenny Root5ab21572011-07-27 11:11:19 -0700602 case MCS_RECONNECT: {
603 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800604 if (mPendingInstalls.size() > 0) {
605 if (mBound) {
606 disconnectService();
607 }
608 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800609 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800610 for (HandlerParams params : mPendingInstalls) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800611 // Indicate service bind error
612 params.serviceError();
613 }
614 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800615 }
616 }
617 break;
618 }
Kenny Root5ab21572011-07-27 11:11:19 -0700619 case MCS_UNBIND: {
Dianne Hackborn7d608422011-08-07 16:24:18 -0700620 // If there is no actual work left, then time to unbind.
Kenny Root5ab21572011-07-27 11:11:19 -0700621 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
622
623 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800624 if (mBound) {
Kenny Root5ab21572011-07-27 11:11:19 -0700625 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
626
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800627 disconnectService();
628 }
Kenny Root5ab21572011-07-27 11:11:19 -0700629 } else if (mPendingInstalls.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800630 // There are more pending requests in queue.
631 // Just post MCS_BOUND message to trigger processing
632 // of next pending install.
633 mHandler.sendEmptyMessage(MCS_BOUND);
634 }
Kenny Root5ab21572011-07-27 11:11:19 -0700635
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800636 break;
637 }
638 case MCS_GIVE_UP: {
Kenny Root5ab21572011-07-27 11:11:19 -0700639 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
Kenny Root60f7ad82011-03-22 12:49:06 -0700640 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800641 break;
642 }
Kenny Root5ab21572011-07-27 11:11:19 -0700643 case SEND_PENDING_BROADCAST: {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800644 String packages[];
Kenny Root60f7ad82011-03-22 12:49:06 -0700645 ArrayList<String> components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700646 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700647 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700648 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700649 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800650 if (mPendingBroadcasts == null) {
651 return;
652 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700653 size = mPendingBroadcasts.size();
654 if (size <= 0) {
655 // Nothing to be done. Just return
656 return;
657 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800658 packages = new String[size];
659 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700660 uids = new int[size];
Andy McFadden2f362292012-01-20 14:43:38 -0800661 Iterator<Map.Entry<String, ArrayList<String>>>
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800662 it = mPendingBroadcasts.entrySet().iterator();
663 int i = 0;
664 while (it.hasNext() && i < size) {
Andy McFadden2f362292012-01-20 14:43:38 -0800665 Map.Entry<String, ArrayList<String>> ent = it.next();
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800666 packages[i] = ent.getKey();
667 components[i] = ent.getValue();
668 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Amith Yamasani13593602012-03-22 16:16:17 -0700669 uids[i] = (ps != null) ? ps.appId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800670 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700671 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800672 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700673 mPendingBroadcasts.clear();
674 }
675 // Send broadcasts
676 for (int i = 0; i < size; i++) {
Kenny Root60f7ad82011-03-22 12:49:06 -0700677 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700678 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700679 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700680 break;
681 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800682 case START_CLEANING_PACKAGE: {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700683 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700684 PackageCleanItem item = new PackageCleanItem((String)msg.obj,
685 msg.arg2 != 0);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800686 synchronized (mPackages) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700687 if (msg.arg1 == UserHandle.USER_ALL) {
688 int[] users = sUserManager.getUserIds();
689 for (int user : users) {
690 mSettings.addPackageToCleanLPw(user, item);
691 }
692 } else {
693 mSettings.addPackageToCleanLPw(msg.arg1, item);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800694 }
695 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700696 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700697 startCleaningPackages(-1);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800698 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800699 case POST_INSTALL: {
700 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
701 PostInstallData data = mRunningInstalls.get(msg.arg1);
702 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700703 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800704
705 if (data != null) {
706 InstallArgs args = data.args;
707 PackageInstalledInfo res = data.res;
708
709 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700710 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800711 Bundle extras = new Bundle(1);
712 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackborn786b4402012-08-27 15:14:02 -0700713 // Determine the set of users who are adding this
714 // package for the first time vs. those who are seeing
715 // an update.
716 int[] firstUsers;
717 int[] updateUsers = new int[0];
718 if (res.origUsers == null || res.origUsers.length == 0) {
719 firstUsers = res.newUsers;
720 } else {
721 firstUsers = new int[0];
722 for (int i=0; i<res.newUsers.length; i++) {
723 int user = res.newUsers[i];
724 boolean isNew = true;
725 for (int j=0; j<res.origUsers.length; j++) {
726 if (res.origUsers[j] == user) {
727 isNew = false;
728 break;
729 }
730 }
731 if (isNew) {
732 int[] newFirst = new int[firstUsers.length+1];
733 System.arraycopy(firstUsers, 0, newFirst, 0,
734 firstUsers.length);
735 newFirst[firstUsers.length] = user;
736 firstUsers = newFirst;
737 } else {
738 int[] newUpdate = new int[updateUsers.length+1];
739 System.arraycopy(updateUsers, 0, newUpdate, 0,
740 updateUsers.length);
741 newUpdate[updateUsers.length] = user;
742 updateUsers = newUpdate;
743 }
744 }
745 }
746 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
747 res.pkg.applicationInfo.packageName,
748 extras, null, null, firstUsers);
Christopher Tate1bb69062010-02-19 17:02:12 -0800749 final boolean update = res.removedInfo.removedPackage != null;
750 if (update) {
751 extras.putBoolean(Intent.EXTRA_REPLACING, true);
752 }
753 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
754 res.pkg.applicationInfo.packageName,
Dianne Hackborn786b4402012-08-27 15:14:02 -0700755 extras, null, null, updateUsers);
Christopher Tate1bb69062010-02-19 17:02:12 -0800756 if (update) {
757 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
758 res.pkg.applicationInfo.packageName,
Dianne Hackborn786b4402012-08-27 15:14:02 -0700759 extras, null, null, updateUsers);
Dianne Hackborne7f97212011-02-24 14:40:20 -0800760 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
761 null, null,
Dianne Hackborn786b4402012-08-27 15:14:02 -0700762 res.pkg.applicationInfo.packageName, null, updateUsers);
Christopher Tate1bb69062010-02-19 17:02:12 -0800763 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700764 if (res.removedInfo.args != null) {
765 // Remove the replaced package's older resources safely now
766 deleteOld = true;
767 }
Matt Finifterf8a98ed2012-05-14 15:43:34 -0700768
769 // Log current value of "unknown sources" setting
770 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
771 getUnknownSourcesSettings());
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700772 }
773 // Force a gc to clear up things
774 Runtime.getRuntime().gc();
775 // We delete after a gc for applications on sdcard.
776 if (deleteOld) {
777 synchronized (mInstallLock) {
778 res.removedInfo.args.doPostDeleteLI(true);
779 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800780 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800781 if (args.observer != null) {
782 try {
783 args.observer.packageInstalled(res.name, res.returnCode);
784 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800785 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800786 }
787 }
788 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800789 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800790 }
791 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700792 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700793 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
794 boolean reportStatus = msg.arg1 == 1;
795 boolean doGc = msg.arg2 == 1;
796 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
797 if (doGc) {
798 // Force a gc to clear up stale containers.
799 Runtime.getRuntime().gc();
800 }
801 if (msg.obj != null) {
Dianne Hackbornba24e4d2011-09-01 11:17:06 -0700802 @SuppressWarnings("unchecked")
Kenny Root6dceb882012-04-12 14:23:49 -0700803 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700804 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
805 // Unload containers
806 unloadAllContainers(args);
807 }
808 if (reportStatus) {
809 try {
810 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
811 PackageHelper.getMountService().finishMediaUpdate();
812 } catch (RemoteException e) {
813 Log.e(TAG, "MountService not running?");
814 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700815 }
816 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700817 case WRITE_SETTINGS: {
818 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
819 synchronized (mPackages) {
820 removeMessages(WRITE_SETTINGS);
Amith Yamasani483f3b02012-03-13 16:08:00 -0700821 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
Kenny Root447106f2011-03-23 11:00:15 -0700822 mSettings.writeLPr();
Amith Yamasani483f3b02012-03-13 16:08:00 -0700823 mDirtyUsers.clear();
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700824 }
825 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
826 } break;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700827 case WRITE_PACKAGE_RESTRICTIONS: {
Dianne Hackborne7f97212011-02-24 14:40:20 -0800828 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
829 synchronized (mPackages) {
Amith Yamasani483f3b02012-03-13 16:08:00 -0700830 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
831 for (int userId : mDirtyUsers) {
832 mSettings.writePackageRestrictionsLPr(userId);
833 }
834 mDirtyUsers.clear();
Dianne Hackborne7f97212011-02-24 14:40:20 -0800835 }
836 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
837 } break;
Kenny Root5ab21572011-07-27 11:11:19 -0700838 case CHECK_PENDING_VERIFICATION: {
839 final int verificationId = msg.arg1;
Kenny Root05ca4c92011-09-15 10:36:25 -0700840 final PackageVerificationState state = mPendingVerification.get(verificationId);
Kenny Root5ab21572011-07-27 11:11:19 -0700841
rich canningsd9ef3e52012-08-22 14:28:05 -0700842 if ((state != null) && !state.timeoutExtended()) {
Kenny Root05ca4c92011-09-15 10:36:25 -0700843 final InstallArgs args = state.getInstallArgs();
Kenny Roota503a0f2011-10-03 14:45:28 -0700844 Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
Kenny Root5ab21572011-07-27 11:11:19 -0700845 mPendingVerification.remove(verificationId);
846
rich canningsa6cfe522012-05-21 15:50:56 -0700847 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
848
849 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
rich canningsd9ef3e52012-08-22 14:28:05 -0700850 Slog.i(TAG, "Continuing with installation of "
851 + args.packageURI.toString());
852 state.setVerifierResponse(Binder.getCallingUid(),
853 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
854 try {
855 ret = args.copyApk(mContainerService, true);
856 } catch (RemoteException e) {
857 Slog.e(TAG, "Could not contact the ContainerService");
858 }
rich canningsa6cfe522012-05-21 15:50:56 -0700859 }
860
Kenny Root5ab21572011-07-27 11:11:19 -0700861 processPendingInstall(args, ret);
Kenny Root5ab21572011-07-27 11:11:19 -0700862 mHandler.sendEmptyMessage(MCS_UNBIND);
863 }
Kenny Root5ab21572011-07-27 11:11:19 -0700864 break;
865 }
866 case PACKAGE_VERIFIED: {
867 final int verificationId = msg.arg1;
Kenny Root5ab21572011-07-27 11:11:19 -0700868
Kenny Root05ca4c92011-09-15 10:36:25 -0700869 final PackageVerificationState state = mPendingVerification.get(verificationId);
870 if (state == null) {
Kenny Roota503a0f2011-10-03 14:45:28 -0700871 Slog.w(TAG, "Invalid verification token " + verificationId + " received");
Kenny Root5ab21572011-07-27 11:11:19 -0700872 break;
873 }
874
Kenny Root05ca4c92011-09-15 10:36:25 -0700875 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
Kenny Root5ab21572011-07-27 11:11:19 -0700876
Kenny Root05ca4c92011-09-15 10:36:25 -0700877 state.setVerifierResponse(response.callerUid, response.code);
878
879 if (state.isVerificationComplete()) {
880 mPendingVerification.remove(verificationId);
881
882 final InstallArgs args = state.getInstallArgs();
883
884 int ret;
885 if (state.isInstallAllowed()) {
886 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
887 try {
888 ret = args.copyApk(mContainerService, true);
889 } catch (RemoteException e) {
890 Slog.e(TAG, "Could not contact the ContainerService");
891 }
892 } else {
893 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
Kenny Root5ab21572011-07-27 11:11:19 -0700894 }
Kenny Root05ca4c92011-09-15 10:36:25 -0700895
896 processPendingInstall(args, ret);
897
898 mHandler.sendEmptyMessage(MCS_UNBIND);
Kenny Root5ab21572011-07-27 11:11:19 -0700899 }
900
Kenny Root5ab21572011-07-27 11:11:19 -0700901 break;
902 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700903 }
904 }
905 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800906
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700907 void scheduleWriteSettingsLocked() {
908 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
909 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
910 }
911 }
Amith Yamasani483f3b02012-03-13 16:08:00 -0700912
913 void scheduleWritePackageRestrictionsLocked(int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -0700914 if (!sUserManager.exists(userId)) return;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700915 mDirtyUsers.add(userId);
916 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
917 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
Dianne Hackborne7f97212011-02-24 14:40:20 -0800918 }
919 }
920
Dianne Hackbornd2509fd2011-09-12 12:29:43 -0700921 public static final IPackageManager main(Context context, boolean factoryTest,
922 boolean onlyCore) {
923 PackageManagerService m = new PackageManagerService(context, factoryTest, onlyCore);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 ServiceManager.addService("package", m);
925 return m;
926 }
927
928 static String[] splitString(String str, char sep) {
929 int count = 1;
930 int i = 0;
931 while ((i=str.indexOf(sep, i)) >= 0) {
932 count++;
933 i++;
934 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 String[] res = new String[count];
937 i=0;
938 count = 0;
939 int lastI=0;
940 while ((i=str.indexOf(sep, i)) >= 0) {
941 res[count] = str.substring(lastI, i);
942 count++;
943 i++;
944 lastI = i;
945 }
946 res[count] = str.substring(lastI, str.length());
947 return res;
948 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800949
Dianne Hackbornd2509fd2011-09-12 12:29:43 -0700950 public PackageManagerService(Context context, boolean factoryTest, boolean onlyCore) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800951 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800955 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 mContext = context;
959 mFactoryTest = factoryTest;
Dianne Hackbornd2509fd2011-09-12 12:29:43 -0700960 mOnlyCore = onlyCore;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700961 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 mMetrics = new DisplayMetrics();
Amith Yamasani258848d2012-08-10 17:06:33 -0700963 mSettings = new Settings(context);
Kenny Root447106f2011-03-23 11:00:15 -0700964 mSettings.addSharedUserLPw("android.uid.system",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800966 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, ApplicationInfo.FLAG_SYSTEM);
967 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, ApplicationInfo.FLAG_SYSTEM);
968 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, ApplicationInfo.FLAG_SYSTEM);
Jaikumar Ganesh1abb1cb2012-01-25 16:14:50 -0800969 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970
971 String separateProcesses = SystemProperties.get("debug.separate_processes");
972 if (separateProcesses != null && separateProcesses.length() > 0) {
973 if ("*".equals(separateProcesses)) {
974 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
975 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800976 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 } else {
978 mDefParseFlags = 0;
979 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800980 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 + separateProcesses);
982 }
983 } else {
984 mDefParseFlags = 0;
985 mSeparateProcesses = null;
986 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800987
Jeff Brown5d6d90f2011-07-11 13:04:53 -0700988 mInstaller = new Installer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989
990 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
991 Display d = wm.getDefaultDisplay();
992 d.getMetrics(mMetrics);
993
994 synchronized (mInstallLock) {
Kenny Root447106f2011-03-23 11:00:15 -0700995 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 synchronized (mPackages) {
997 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700998 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 File dataDir = Environment.getDataDirectory();
1001 mAppDataDir = new File(dataDir, "data");
Kenny Root51a573c2012-05-17 13:30:28 -07001002 mAsecInternalPath = new File(dataDir, "app-asec").getPath();
Amith Yamasani0b285492011-04-14 17:35:23 -07001003 mUserAppDataDir = new File(dataDir, "user");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1005
Dianne Hackborn4428e172012-08-24 17:43:05 -07001006 sUserManager = new UserManagerService(context, this,
1007 mInstallLock, mPackages);
Amith Yamasani0b285492011-04-14 17:35:23 -07001008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 readPermissions();
1010
Amith Yamasani258848d2012-08-10 17:06:33 -07001011 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001013
1014 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001016
Suchi Amalapurapudaec1722010-01-14 21:25:16 -08001017 // Set flag to monitor and not change apk file paths when
1018 // scanning install directories.
Dianne Hackbornd0c5f512012-06-07 16:53:59 -07001019 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001020 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001021 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001022 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001023 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001024
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001028 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001029
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001030 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001031
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001032 /**
1033 * Out of paranoia, ensure that everything in the boot class
1034 * path has been dexed.
1035 */
1036 String bootClassPath = System.getProperty("java.boot.class.path");
1037 if (bootClassPath != null) {
1038 String[] paths = splitString(bootClassPath, ':');
1039 for (int i=0; i<paths.length; i++) {
1040 try {
1041 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
1042 libFiles.add(paths[i]);
1043 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
1044 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001046 } catch (FileNotFoundException e) {
1047 Slog.w(TAG, "Boot class path not found: " + paths[i]);
1048 } catch (IOException e) {
Kenny Rootfec5e752011-09-23 10:09:58 -07001049 Slog.w(TAG, "Cannot dexopt " + paths[i] + "; is it an APK or JAR? "
1050 + e.getMessage());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 }
1052 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001053 } else {
1054 Slog.w(TAG, "No BOOTCLASSPATH found!");
1055 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001056
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001057 /**
1058 * Also ensure all external libraries have had dexopt run on them.
1059 */
1060 if (mSharedLibraries.size() > 0) {
1061 Iterator<String> libs = mSharedLibraries.values().iterator();
1062 while (libs.hasNext()) {
1063 String lib = libs.next();
1064 try {
1065 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
1066 libFiles.add(lib);
1067 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
1068 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001070 } catch (FileNotFoundException e) {
1071 Slog.w(TAG, "Library not found: " + lib);
1072 } catch (IOException e) {
Kenny Rootfec5e752011-09-23 10:09:58 -07001073 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1074 + e.getMessage());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 }
1076 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001077 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001078
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001079 // Gross hack for now: we know this file doesn't contain any
1080 // code, so don't dexopt it to avoid the resulting log spew.
1081 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
1082
1083 /**
1084 * And there are a number of commands implemented in Java, which
1085 * we currently need to do the dexopt on so that they can be
1086 * run from a non-root shell.
1087 */
1088 String[] frameworkFiles = mFrameworkDir.list();
1089 if (frameworkFiles != null) {
1090 for (int i=0; i<frameworkFiles.length; i++) {
1091 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
1092 String path = libPath.getPath();
1093 // Skip the file if we alrady did it.
1094 if (libFiles.contains(path)) {
1095 continue;
1096 }
1097 // Skip the file if it is not a type we want to dexopt.
1098 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1099 continue;
1100 }
1101 try {
1102 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
1103 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
1104 didDexOpt = true;
1105 }
1106 } catch (FileNotFoundException e) {
1107 Slog.w(TAG, "Jar not found: " + path);
1108 } catch (IOException e) {
1109 Slog.w(TAG, "Exception reading jar: " + path, e);
1110 }
1111 }
1112 }
1113
1114 if (didDexOpt) {
1115 // If we had to do a dexopt of one of the previous
1116 // things, then something on the system has changed.
1117 // Consider this significant, and wipe away all other
1118 // existing dexopt files to ensure we don't leave any
1119 // dangling around.
1120 String[] files = mDalvikCacheDir.list();
1121 if (files != null) {
1122 for (int i=0; i<files.length; i++) {
1123 String fn = files[i];
1124 if (fn.startsWith("data@app@")
1125 || fn.startsWith("data@app-private@")) {
1126 Slog.i(TAG, "Pruning dalvik file: " + fn);
1127 (new File(mDalvikCacheDir, fn)).delete();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001128 }
1129 }
1130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001132
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001133 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 mFrameworkInstallObserver = new AppDirObserver(
1135 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
1136 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -07001137 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
1138 | PackageParser.PARSE_IS_SYSTEM_DIR,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001139 scanMode | SCAN_NO_DEX, 0);
Kenny Root51a573c2012-05-17 13:30:28 -07001140
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001141 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
1143 mSystemInstallObserver = new AppDirObserver(
1144 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
1145 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -07001146 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001147 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Kenny Root208d3412012-05-07 19:42:35 -07001148
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07001149 // Collect all vendor packages.
1150 mVendorAppDir = new File("/vendor/app");
1151 mVendorInstallObserver = new AppDirObserver(
1152 mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
1153 mVendorInstallObserver.startWatching();
1154 scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001155 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07001156
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001157 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1158 mInstaller.moveFiles();
1159
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001160 // Prune any system packages that no longer exist.
Kenny Root87b5d7b2012-05-16 13:36:18 -07001161 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001162 if (!mOnlyCore) {
1163 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1164 while (psit.hasNext()) {
1165 PackageSetting ps = psit.next();
Kenny Root208d3412012-05-07 19:42:35 -07001166
1167 /*
1168 * If this is not a system app, it can't be a
1169 * disable system app.
1170 */
1171 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1172 continue;
1173 }
1174
1175 /*
1176 * If the package is scanned, it's not erased.
1177 */
Kenny Rooteca64b32012-06-25 16:37:32 -07001178 final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1179 if (scannedPkg != null) {
Kenny Root208d3412012-05-07 19:42:35 -07001180 /*
1181 * If the system app is both scanned and in the
1182 * disabled packages list, then it must have been
1183 * added via OTA. Remove it from the currently
1184 * scanned package so the previously user-installed
1185 * application can be scanned.
1186 */
1187 if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
Kenny Rooteca64b32012-06-25 16:37:32 -07001188 Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1189 + "; removing system app");
1190 removePackageLI(scannedPkg, true);
Kenny Root208d3412012-05-07 19:42:35 -07001191 }
1192
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001193 continue;
1194 }
1195
1196 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001197 psit.remove();
1198 String msg = "System package " + ps.name
1199 + " no longer exists; wiping its data";
1200 reportSettingsProblem(Log.WARN, msg);
Dianne Hackborn4428e172012-08-24 17:43:05 -07001201 removeDataDirsLI(ps.name);
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001202 } else {
Kenny Root87b5d7b2012-05-16 13:36:18 -07001203 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1204 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1205 possiblyDeletedUpdatedSystemApps.add(ps.name);
1206 }
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001207 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001208 }
1209 }
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 mAppInstallDir = new File(dataDir, "app");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 //look for any incomplete package installations
Kenny Root447106f2011-03-23 11:00:15 -07001213 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 //clean up list
1215 for(int i = 0; i < deletePkgsList.size(); i++) {
1216 //clean up here
1217 cleanupInstallFailedPackage(deletePkgsList.get(i));
1218 }
1219 //delete tmp files
1220 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001221
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001222 if (!mOnlyCore) {
1223 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1224 SystemClock.uptimeMillis());
1225 mAppInstallObserver = new AppDirObserver(
1226 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
1227 mAppInstallObserver.startWatching();
1228 scanDirLI(mAppInstallDir, 0, scanMode, 0);
1229
1230 mDrmAppInstallObserver = new AppDirObserver(
1231 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
1232 mDrmAppInstallObserver.startWatching();
1233 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1234 scanMode, 0);
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001235
1236 /**
Kenny Root87b5d7b2012-05-16 13:36:18 -07001237 * Remove disable package settings for any updated system
1238 * apps that were removed via an OTA. If they're not a
1239 * previously-updated app, remove them completely.
1240 * Otherwise, just revoke their system-level permissions.
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001241 */
Kenny Root87b5d7b2012-05-16 13:36:18 -07001242 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001243 PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
Kenny Root87b5d7b2012-05-16 13:36:18 -07001244 mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1245
1246 String msg;
1247 if (deletedPkg == null) {
1248 msg = "Updated system package " + deletedAppName
1249 + " no longer exists; wiping its data";
Dianne Hackborn4428e172012-08-24 17:43:05 -07001250 removeDataDirsLI(deletedAppName);
Kenny Root87b5d7b2012-05-16 13:36:18 -07001251 } else {
1252 msg = "Updated system app + " + deletedAppName
1253 + " no longer present; removing system privileges for "
1254 + deletedAppName;
1255
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001256 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1257
1258 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1259 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1260 }
Kenny Root87b5d7b2012-05-16 13:36:18 -07001261 reportSettingsProblem(Log.WARN, msg);
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001262 }
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001263 } else {
1264 mAppInstallObserver = null;
1265 mDrmAppInstallObserver = null;
1266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001268 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001270 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 + ((SystemClock.uptimeMillis()-startTime)/1000f)
1272 + " seconds");
1273
Dianne Hackbornf22221f2010-04-05 18:35:42 -07001274 // If the platform SDK has changed since the last time we booted,
1275 // we need to re-grant app permission to catch any new ones that
1276 // appear. This is really a hack, and means that apps can in some
1277 // cases get permissions that the user didn't initially explicitly
1278 // allow... it would be nice to have some better way to handle
1279 // this situation.
1280 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1281 != mSdkVersion;
1282 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1283 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1284 + "; regranting permissions for internal storage");
1285 mSettings.mInternalSdkPlatform = mSdkVersion;
1286
Dianne Hackborne639da72012-02-21 15:11:13 -08001287 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1288 | (regrantPermissions
1289 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1290 : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291
Dianne Hackborn04505102012-02-29 12:34:04 -08001292 // Verify that all of the preferred activity components actually
1293 // exist. It is possible for applications to be updated and at
1294 // that point remove a previously declared activity component that
1295 // had been set as a preferred activity. We try to clean this up
1296 // the next time we encounter that preferred activity, but it is
1297 // possible for the user flow to never be able to return to that
1298 // situation so here we do a sanity check to make sure we haven't
1299 // left any junk around.
1300 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
1301 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
1302 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
1303 removed.add(pa);
1304 }
1305 }
1306 for (int i=0; i<removed.size(); i++) {
1307 PreferredActivity pa = removed.get(i);
1308 Slog.w(TAG, "Removing dangling preferred activity: "
1309 + pa.mPref.mComponent);
1310 mSettings.mPreferredActivities.removeFilter(pa);
1311 }
1312
Kenny Root447106f2011-03-23 11:00:15 -07001313 // can downgrade to reader
1314 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001316 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 // Now after opening every single application zip, make sure they
1320 // are all flushed. Not really needed, but keeps things nice and
1321 // tidy.
1322 Runtime.getRuntime().gc();
Kenny Root05ca4c92011-09-15 10:36:25 -07001323
1324 mRequiredVerifierPackage = getRequiredVerifierLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 } // synchronized (mPackages)
1326 } // synchronized (mInstallLock)
1327 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001328
Dianne Hackborn58f42a52011-10-10 13:46:34 -07001329 public boolean isFirstBoot() {
1330 return !mRestoredSettings;
1331 }
1332
Kenny Root05ca4c92011-09-15 10:36:25 -07001333 private String getRequiredVerifierLPr() {
1334 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1335 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
Amith Yamasani483f3b02012-03-13 16:08:00 -07001336 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
Kenny Root05ca4c92011-09-15 10:36:25 -07001337
1338 String requiredVerifier = null;
1339
1340 final int N = receivers.size();
1341 for (int i = 0; i < N; i++) {
1342 final ResolveInfo info = receivers.get(i);
1343
1344 if (info.activityInfo == null) {
1345 continue;
1346 }
1347
1348 final String packageName = info.activityInfo.packageName;
1349
1350 final PackageSetting ps = mSettings.mPackages.get(packageName);
1351 if (ps == null) {
1352 continue;
1353 }
1354
1355 if (!ps.grantedPermissions
1356 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1357 continue;
1358 }
1359
1360 if (requiredVerifier != null) {
1361 throw new RuntimeException("There can be only one required verifier");
1362 }
1363
1364 requiredVerifier = packageName;
1365 }
1366
1367 return requiredVerifier;
1368 }
1369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 @Override
1371 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1372 throws RemoteException {
1373 try {
1374 return super.onTransact(code, data, reply, flags);
1375 } catch (RuntimeException e) {
1376 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001377 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 }
1379 throw e;
1380 }
1381 }
1382
Dianne Hackborne6620b22010-01-22 14:46:21 -08001383 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001384 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
Dianne Hackborn4428e172012-08-24 17:43:05 -07001385 removeDataDirsLI(ps.name);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001386 if (ps.codePath != null) {
1387 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001388 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001389 }
1390 }
1391 if (ps.resourcePath != null) {
1392 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001393 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001394 }
1395 }
Kenny Root447106f2011-03-23 11:00:15 -07001396 mSettings.removePackageLPw(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 }
1398
1399 void readPermissions() {
1400 // Read permissions from .../etc/permission directory.
1401 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1402 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001403 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 return;
1405 }
1406 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001407 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 return;
1409 }
1410
1411 // Iterate over the files in the directory and scan .xml files
1412 for (File f : libraryDir.listFiles()) {
1413 // We'll read platform.xml last
1414 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1415 continue;
1416 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001419 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 continue;
1421 }
1422 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001423 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 continue;
1425 }
1426
1427 readPermissionsFromXml(f);
1428 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1431 final File permFile = new File(Environment.getRootDirectory(),
1432 "etc/permissions/platform.xml");
1433 readPermissionsFromXml(permFile);
1434 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001435
1436 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 FileReader permReader = null;
1438 try {
1439 permReader = new FileReader(permFile);
1440 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001441 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 return;
1443 }
1444
1445 try {
1446 XmlPullParser parser = Xml.newPullParser();
1447 parser.setInput(permReader);
1448
1449 XmlUtils.beginDocument(parser, "permissions");
1450
1451 while (true) {
1452 XmlUtils.nextElement(parser);
1453 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1454 break;
1455 }
1456
1457 String name = parser.getName();
1458 if ("group".equals(name)) {
1459 String gidStr = parser.getAttributeValue(null, "gid");
1460 if (gidStr != null) {
1461 int gid = Integer.parseInt(gidStr);
1462 mGlobalGids = appendInt(mGlobalGids, gid);
1463 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001464 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 + parser.getPositionDescription());
1466 }
1467
1468 XmlUtils.skipCurrentTag(parser);
1469 continue;
1470 } else if ("permission".equals(name)) {
1471 String perm = parser.getAttributeValue(null, "name");
1472 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001473 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 + parser.getPositionDescription());
1475 XmlUtils.skipCurrentTag(parser);
1476 continue;
1477 }
1478 perm = perm.intern();
1479 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 } else if ("assign-permission".equals(name)) {
1482 String perm = parser.getAttributeValue(null, "name");
1483 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001484 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 + parser.getPositionDescription());
1486 XmlUtils.skipCurrentTag(parser);
1487 continue;
1488 }
1489 String uidStr = parser.getAttributeValue(null, "uid");
1490 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001491 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 + parser.getPositionDescription());
1493 XmlUtils.skipCurrentTag(parser);
1494 continue;
1495 }
1496 int uid = Process.getUidForName(uidStr);
1497 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001498 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 + uidStr + "\" at "
1500 + parser.getPositionDescription());
1501 XmlUtils.skipCurrentTag(parser);
1502 continue;
1503 }
1504 perm = perm.intern();
1505 HashSet<String> perms = mSystemPermissions.get(uid);
1506 if (perms == null) {
1507 perms = new HashSet<String>();
1508 mSystemPermissions.put(uid, perms);
1509 }
1510 perms.add(perm);
1511 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 } else if ("library".equals(name)) {
1514 String lname = parser.getAttributeValue(null, "name");
1515 String lfile = parser.getAttributeValue(null, "file");
1516 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001517 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 + parser.getPositionDescription());
1519 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001520 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 + parser.getPositionDescription());
1522 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001523 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001524 mSharedLibraries.put(lname, lfile);
1525 }
1526 XmlUtils.skipCurrentTag(parser);
1527 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001528
Dianne Hackborn49237342009-08-27 20:08:01 -07001529 } else if ("feature".equals(name)) {
1530 String fname = parser.getAttributeValue(null, "name");
1531 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001532 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001533 + parser.getPositionDescription());
1534 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001535 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001536 FeatureInfo fi = new FeatureInfo();
1537 fi.name = fname;
1538 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
1540 XmlUtils.skipCurrentTag(parser);
1541 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 } else {
1544 XmlUtils.skipCurrentTag(parser);
1545 continue;
1546 }
1547
1548 }
Brian Carlstromfd9ddd12010-11-04 11:24:58 -07001549 permReader.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001551 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001553 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 }
1555 }
1556
1557 void readPermission(XmlPullParser parser, String name)
1558 throws IOException, XmlPullParserException {
1559
1560 name = name.intern();
1561
1562 BasePermission bp = mSettings.mPermissions.get(name);
1563 if (bp == null) {
1564 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1565 mSettings.mPermissions.put(name, bp);
1566 }
1567 int outerDepth = parser.getDepth();
1568 int type;
1569 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1570 && (type != XmlPullParser.END_TAG
1571 || parser.getDepth() > outerDepth)) {
1572 if (type == XmlPullParser.END_TAG
1573 || type == XmlPullParser.TEXT) {
1574 continue;
1575 }
1576
1577 String tagName = parser.getName();
1578 if ("group".equals(tagName)) {
1579 String gidStr = parser.getAttributeValue(null, "gid");
1580 if (gidStr != null) {
1581 int gid = Process.getGidForName(gidStr);
1582 bp.gids = appendInt(bp.gids, gid);
1583 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001584 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 + parser.getPositionDescription());
1586 }
1587 }
1588 XmlUtils.skipCurrentTag(parser);
1589 }
1590 }
1591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 static int[] appendInts(int[] cur, int[] add) {
1593 if (add == null) return cur;
1594 if (cur == null) return add;
1595 final int N = add.length;
1596 for (int i=0; i<N; i++) {
1597 cur = appendInt(cur, add[i]);
1598 }
1599 return cur;
1600 }
1601
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001602 static int[] removeInts(int[] cur, int[] rem) {
1603 if (rem == null) return cur;
1604 if (cur == null) return cur;
1605 final int N = rem.length;
1606 for (int i=0; i<N; i++) {
1607 cur = removeInt(cur, rem[i]);
1608 }
1609 return cur;
1610 }
1611
Amith Yamasani13593602012-03-22 16:16:17 -07001612 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1613 if (!sUserManager.exists(userId)) return null;
1614 PackageInfo pi;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001615 final PackageSetting ps = (PackageSetting) p.mExtras;
1616 if (ps == null) {
1617 return null;
1618 }
1619 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1620 final PackageUserState state = ps.readUserState(userId);
1621 pi = PackageParser.generatePackageInfo(p, gp.gids, flags,
1622 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1623 state, userId);
1624 if (pi != null) {
1625 pi.applicationInfo.enabledSetting = state.enabled;
Amith Yamasani13593602012-03-22 16:16:17 -07001626 pi.applicationInfo.enabled =
1627 pi.applicationInfo.enabledSetting == COMPONENT_ENABLED_STATE_DEFAULT
1628 || pi.applicationInfo.enabledSetting == COMPONENT_ENABLED_STATE_ENABLED;
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001629 }
Amith Yamasani13593602012-03-22 16:16:17 -07001630 return pi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 }
1632
Amith Yamasani483f3b02012-03-13 16:08:00 -07001633 @Override
1634 public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001635 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07001636 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
Kenny Root447106f2011-03-23 11:00:15 -07001637 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 synchronized (mPackages) {
1639 PackageParser.Package p = mPackages.get(packageName);
Kenny Root9718cf52011-02-23 16:45:26 -08001640 if (DEBUG_PACKAGE_INFO)
1641 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 if (p != null) {
Amith Yamasani13593602012-03-22 16:16:17 -07001643 return generatePackageInfo(p, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 }
1645 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001646 return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 }
1648 }
1649 return null;
1650 }
1651
Dianne Hackborn47096932010-02-11 15:57:09 -08001652 public String[] currentToCanonicalPackageNames(String[] names) {
1653 String[] out = new String[names.length];
Kenny Root447106f2011-03-23 11:00:15 -07001654 // reader
Dianne Hackborn47096932010-02-11 15:57:09 -08001655 synchronized (mPackages) {
1656 for (int i=names.length-1; i>=0; i--) {
1657 PackageSetting ps = mSettings.mPackages.get(names[i]);
1658 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1659 }
1660 }
1661 return out;
1662 }
1663
1664 public String[] canonicalToCurrentPackageNames(String[] names) {
1665 String[] out = new String[names.length];
Kenny Root447106f2011-03-23 11:00:15 -07001666 // reader
Dianne Hackborn47096932010-02-11 15:57:09 -08001667 synchronized (mPackages) {
1668 for (int i=names.length-1; i>=0; i--) {
1669 String cur = mSettings.mRenamedPackages.get(names[i]);
1670 out[i] = cur != null ? cur : names[i];
1671 }
1672 }
1673 return out;
1674 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07001675
1676 @Override
1677 public int getPackageUid(String packageName, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001678 if (!sUserManager.exists(userId)) return -1;
Amith Yamasanif203aee2012-08-29 18:41:53 -07001679 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
Kenny Root447106f2011-03-23 11:00:15 -07001680 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 synchronized (mPackages) {
1682 PackageParser.Package p = mPackages.get(packageName);
1683 if(p != null) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001684 return UserHandle.getUid(userId, p.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 }
1686 PackageSetting ps = mSettings.mPackages.get(packageName);
1687 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1688 return -1;
1689 }
1690 p = ps.pkg;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001691 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 }
1693 }
1694
1695 public int[] getPackageGids(String packageName) {
Kenny Root447106f2011-03-23 11:00:15 -07001696 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 synchronized (mPackages) {
1698 PackageParser.Package p = mPackages.get(packageName);
Kenny Root9718cf52011-02-23 16:45:26 -08001699 if (DEBUG_PACKAGE_INFO)
1700 Log.v(TAG, "getPackageGids" + packageName + ": " + p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 if (p != null) {
1702 final PackageSetting ps = (PackageSetting)p.mExtras;
1703 final SharedUserSetting suid = ps.sharedUser;
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07001704 int[] gids = suid != null ? suid.gids : ps.gids;
1705
1706 // include GIDs for any unenforced permissions
1707 if (!isPermissionEnforcedLocked(READ_EXTERNAL_STORAGE)) {
1708 final BasePermission basePerm = mSettings.mPermissions.get(
1709 READ_EXTERNAL_STORAGE);
1710 gids = appendInts(gids, basePerm.gids);
1711 }
1712
1713 return gids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 }
1715 }
1716 // stupid thing to indicate an error.
1717 return new int[0];
1718 }
1719
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001720 static final PermissionInfo generatePermissionInfo(
1721 BasePermission bp, int flags) {
1722 if (bp.perm != null) {
1723 return PackageParser.generatePermissionInfo(bp.perm, flags);
1724 }
1725 PermissionInfo pi = new PermissionInfo();
1726 pi.name = bp.name;
1727 pi.packageName = bp.sourcePackage;
1728 pi.nonLocalizedLabel = bp.name;
1729 pi.protectionLevel = bp.protectionLevel;
1730 return pi;
1731 }
1732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 public PermissionInfo getPermissionInfo(String name, int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001734 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 synchronized (mPackages) {
1736 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001737 if (p != null) {
1738 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 }
1740 return null;
1741 }
1742 }
1743
1744 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001745 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 synchronized (mPackages) {
1747 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1748 for (BasePermission p : mSettings.mPermissions.values()) {
1749 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001750 if (p.perm == null || p.perm.info.group == null) {
1751 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 }
1753 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001754 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1756 }
1757 }
1758 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 if (out.size() > 0) {
1761 return out;
1762 }
1763 return mPermissionGroups.containsKey(group) ? out : null;
1764 }
1765 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001768 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 synchronized (mPackages) {
1770 return PackageParser.generatePermissionGroupInfo(
1771 mPermissionGroups.get(name), flags);
1772 }
1773 }
1774
1775 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001776 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 synchronized (mPackages) {
1778 final int N = mPermissionGroups.size();
1779 ArrayList<PermissionGroupInfo> out
1780 = new ArrayList<PermissionGroupInfo>(N);
1781 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1782 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1783 }
1784 return out;
1785 }
1786 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001787
Amith Yamasani483f3b02012-03-13 16:08:00 -07001788 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
1789 int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001790 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 PackageSetting ps = mSettings.mPackages.get(packageName);
Kenny Root447106f2011-03-23 11:00:15 -07001792 if (ps != null) {
1793 if (ps.pkg == null) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001794 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
1795 flags, userId);
Kenny Root447106f2011-03-23 11:00:15 -07001796 if (pInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 return pInfo.applicationInfo;
1798 }
1799 return null;
1800 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001801 return PackageParser.generateApplicationInfo(ps.pkg, flags,
1802 ps.readUserState(userId), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 }
1804 return null;
1805 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001806
Amith Yamasani483f3b02012-03-13 16:08:00 -07001807 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
1808 int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001809 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 PackageSetting ps = mSettings.mPackages.get(packageName);
Kenny Root447106f2011-03-23 11:00:15 -07001811 if (ps != null) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001812 PackageParser.Package pkg = ps.pkg;
1813 if (pkg == null) {
1814 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
1815 return null;
1816 }
1817 pkg = new PackageParser.Package(packageName);
1818 pkg.applicationInfo.packageName = packageName;
1819 pkg.applicationInfo.flags = ps.pkgFlags;
1820 pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1821 pkg.applicationInfo.sourceDir = ps.codePathString;
1822 pkg.applicationInfo.dataDir =
Amith Yamasani317046a2012-08-29 18:48:08 -07001823 getDataPathForPackage(packageName, 0).getPath();
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001824 pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001826 // pkg.mSetEnabled = ps.getEnabled(userId);
1827 // pkg.mSetStopped = ps.getStopped(userId);
1828 return generatePackageInfo(pkg, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 }
1830 return null;
1831 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001832
Amith Yamasani483f3b02012-03-13 16:08:00 -07001833 @Override
1834 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001835 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07001836 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
Kenny Root447106f2011-03-23 11:00:15 -07001837 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 synchronized (mPackages) {
1839 PackageParser.Package p = mPackages.get(packageName);
Kenny Root9718cf52011-02-23 16:45:26 -08001840 if (DEBUG_PACKAGE_INFO) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 TAG, "getApplicationInfo " + packageName
1842 + ": " + p);
1843 if (p != null) {
Amith Yamasani13593602012-03-22 16:16:17 -07001844 PackageSetting ps = mSettings.mPackages.get(packageName);
1845 if (ps == null) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 // Note: isEnabledLP() does not apply here - always return info
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001847 return PackageParser.generateApplicationInfo(p, flags, ps.readUserState(userId));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 }
1849 if ("android".equals(packageName)||"system".equals(packageName)) {
1850 return mAndroidApplication;
1851 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001852 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001853 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 }
1855 }
1856 return null;
1857 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001858
1859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1861 mContext.enforceCallingOrSelfPermission(
1862 android.Manifest.permission.CLEAR_APP_CACHE, null);
1863 // Queue up an async operation since clearing cache may take a little while.
1864 mHandler.post(new Runnable() {
1865 public void run() {
1866 mHandler.removeCallbacks(this);
1867 int retCode = -1;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001868 synchronized (mInstallLock) {
1869 retCode = mInstaller.freeCache(freeStorageSize);
1870 if (retCode < 0) {
1871 Slog.w(TAG, "Couldn't clear application caches");
1872 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 if (observer != null) {
1875 try {
1876 observer.onRemoveCompleted(null, (retCode >= 0));
1877 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001878 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 }
1880 }
1881 }
1882 });
1883 }
1884
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001885 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001886 mContext.enforceCallingOrSelfPermission(
1887 android.Manifest.permission.CLEAR_APP_CACHE, null);
1888 // Queue up an async operation since clearing cache may take a little while.
1889 mHandler.post(new Runnable() {
1890 public void run() {
1891 mHandler.removeCallbacks(this);
1892 int retCode = -1;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001893 synchronized (mInstallLock) {
1894 retCode = mInstaller.freeCache(freeStorageSize);
1895 if (retCode < 0) {
1896 Slog.w(TAG, "Couldn't clear application caches");
1897 }
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001898 }
1899 if(pi != null) {
1900 try {
1901 // Callback via pending intent
1902 int code = (retCode >= 0) ? 1 : 0;
1903 pi.sendIntent(null, code, null,
1904 null, null);
1905 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001906 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001907 }
1908 }
1909 }
1910 });
1911 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001912
Amith Yamasani483f3b02012-03-13 16:08:00 -07001913 @Override
1914 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001915 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07001916 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 synchronized (mPackages) {
1918 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001919
Kenny Root9718cf52011-02-23 16:45:26 -08001920 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001921 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
Amith Yamasani13593602012-03-22 16:16:17 -07001922 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
1923 if (ps == null) return null;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001924 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
1925 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 }
1927 if (mResolveComponentName.equals(component)) {
1928 return mResolveActivity;
1929 }
1930 }
1931 return null;
1932 }
1933
Amith Yamasani483f3b02012-03-13 16:08:00 -07001934 @Override
1935 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001936 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07001937 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 synchronized (mPackages) {
1939 PackageParser.Activity a = mReceivers.mActivities.get(component);
Kenny Root9718cf52011-02-23 16:45:26 -08001940 if (DEBUG_PACKAGE_INFO) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 TAG, "getReceiverInfo " + component + ": " + a);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001942 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
Amith Yamasani13593602012-03-22 16:16:17 -07001943 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
1944 if (ps == null) return null;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001945 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
1946 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 }
1948 }
1949 return null;
1950 }
1951
Amith Yamasani483f3b02012-03-13 16:08:00 -07001952 @Override
1953 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001954 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07001955 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 synchronized (mPackages) {
1957 PackageParser.Service s = mServices.mServices.get(component);
Kenny Root9718cf52011-02-23 16:45:26 -08001958 if (DEBUG_PACKAGE_INFO) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 TAG, "getServiceInfo " + component + ": " + s);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001960 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
Amith Yamasani13593602012-03-22 16:16:17 -07001961 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
1962 if (ps == null) return null;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001963 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
1964 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 }
1966 }
1967 return null;
1968 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001969
Amith Yamasani483f3b02012-03-13 16:08:00 -07001970 @Override
1971 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001972 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07001973 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
Dianne Hackborn361199b2010-08-30 17:42:07 -07001974 synchronized (mPackages) {
1975 PackageParser.Provider p = mProvidersByComponent.get(component);
Kenny Root9718cf52011-02-23 16:45:26 -08001976 if (DEBUG_PACKAGE_INFO) Log.v(
Dianne Hackborn361199b2010-08-30 17:42:07 -07001977 TAG, "getProviderInfo " + component + ": " + p);
Amith Yamasani483f3b02012-03-13 16:08:00 -07001978 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
Amith Yamasani13593602012-03-22 16:16:17 -07001979 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
1980 if (ps == null) return null;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001981 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
1982 userId);
Dianne Hackborn361199b2010-08-30 17:42:07 -07001983 }
1984 }
1985 return null;
1986 }
1987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988 public String[] getSystemSharedLibraryNames() {
1989 Set<String> libSet;
1990 synchronized (mPackages) {
1991 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001992 int size = libSet.size();
1993 if (size > 0) {
1994 String[] libs = new String[size];
1995 libSet.toArray(libs);
1996 return libs;
1997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001999 return null;
2000 }
2001
2002 public FeatureInfo[] getSystemAvailableFeatures() {
2003 Collection<FeatureInfo> featSet;
2004 synchronized (mPackages) {
2005 featSet = mAvailableFeatures.values();
2006 int size = featSet.size();
2007 if (size > 0) {
2008 FeatureInfo[] features = new FeatureInfo[size+1];
2009 featSet.toArray(features);
2010 FeatureInfo fi = new FeatureInfo();
2011 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2012 FeatureInfo.GL_ES_VERSION_UNDEFINED);
2013 features[size] = fi;
2014 return features;
2015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 }
2017 return null;
2018 }
2019
Dianne Hackborn039c68e2009-09-26 16:39:23 -07002020 public boolean hasSystemFeature(String name) {
2021 synchronized (mPackages) {
2022 return mAvailableFeatures.containsKey(name);
2023 }
2024 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002025
Amith Yamasani483f3b02012-03-13 16:08:00 -07002026 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002027 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
Amith Yamasani483f3b02012-03-13 16:08:00 -07002028 return;
2029
2030 throw new SecurityException("Caller uid=" + uid
2031 + " is not privileged to communicate with user=" + userId);
2032 }
2033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 public int checkPermission(String permName, String pkgName) {
2035 synchronized (mPackages) {
2036 PackageParser.Package p = mPackages.get(pkgName);
2037 if (p != null && p.mExtras != null) {
2038 PackageSetting ps = (PackageSetting)p.mExtras;
2039 if (ps.sharedUser != null) {
2040 if (ps.sharedUser.grantedPermissions.contains(permName)) {
2041 return PackageManager.PERMISSION_GRANTED;
2042 }
2043 } else if (ps.grantedPermissions.contains(permName)) {
2044 return PackageManager.PERMISSION_GRANTED;
2045 }
2046 }
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07002047 if (!isPermissionEnforcedLocked(permName)) {
2048 return PackageManager.PERMISSION_GRANTED;
2049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 }
2051 return PackageManager.PERMISSION_DENIED;
2052 }
2053
2054 public int checkUidPermission(String permName, int uid) {
2055 synchronized (mPackages) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002056 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002058 GrantedPermissions gp = (GrantedPermissions)obj;
2059 if (gp.grantedPermissions.contains(permName)) {
2060 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 }
2062 } else {
2063 HashSet<String> perms = mSystemPermissions.get(uid);
2064 if (perms != null && perms.contains(permName)) {
2065 return PackageManager.PERMISSION_GRANTED;
2066 }
2067 }
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07002068 if (!isPermissionEnforcedLocked(permName)) {
2069 return PackageManager.PERMISSION_GRANTED;
2070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 }
2072 return PackageManager.PERMISSION_DENIED;
2073 }
2074
Amith Yamasanif203aee2012-08-29 18:41:53 -07002075 /**
2076 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2077 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2078 * @param message the message to log on security exception
2079 * @return
2080 */
2081 private void enforceCrossUserPermission(int callingUid, int userId,
2082 boolean requireFullPermission, String message) {
2083 if (userId < 0) {
2084 throw new IllegalArgumentException("Invalid userId " + userId);
2085 }
2086 if (userId == UserHandle.getUserId(callingUid)) return;
2087 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2088 if (requireFullPermission) {
2089 mContext.enforceCallingOrSelfPermission(
2090 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2091 } else {
2092 try {
2093 mContext.enforceCallingOrSelfPermission(
2094 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2095 } catch (SecurityException se) {
2096 mContext.enforceCallingOrSelfPermission(
2097 android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2098 }
2099 }
2100 }
2101 }
2102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 private BasePermission findPermissionTreeLP(String permName) {
2104 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2105 if (permName.startsWith(bp.name) &&
2106 permName.length() > bp.name.length() &&
2107 permName.charAt(bp.name.length()) == '.') {
2108 return bp;
2109 }
2110 }
2111 return null;
2112 }
2113
2114 private BasePermission checkPermissionTreeLP(String permName) {
2115 if (permName != null) {
2116 BasePermission bp = findPermissionTreeLP(permName);
2117 if (bp != null) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002118 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 return bp;
2120 }
2121 throw new SecurityException("Calling uid "
2122 + Binder.getCallingUid()
2123 + " is not allowed to add to permission tree "
2124 + bp.name + " owned by uid " + bp.uid);
2125 }
2126 }
2127 throw new SecurityException("No permission tree found for " + permName);
2128 }
2129
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002130 static boolean compareStrings(CharSequence s1, CharSequence s2) {
2131 if (s1 == null) {
2132 return s2 == null;
2133 }
2134 if (s2 == null) {
2135 return false;
2136 }
2137 if (s1.getClass() != s2.getClass()) {
2138 return false;
2139 }
2140 return s1.equals(s2);
2141 }
2142
2143 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2144 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07002145 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002146 if (pi1.protectionLevel != pi2.protectionLevel) return false;
2147 if (!compareStrings(pi1.name, pi2.name)) return false;
2148 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2149 // We'll take care of setting this one.
2150 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2151 // These are not currently stored in settings.
2152 //if (!compareStrings(pi1.group, pi2.group)) return false;
2153 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2154 //if (pi1.labelRes != pi2.labelRes) return false;
2155 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2156 return true;
2157 }
2158
2159 boolean addPermissionLocked(PermissionInfo info, boolean async) {
2160 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2161 throw new SecurityException("Label must be specified in permission");
2162 }
2163 BasePermission tree = checkPermissionTreeLP(info.name);
2164 BasePermission bp = mSettings.mPermissions.get(info.name);
2165 boolean added = bp == null;
2166 boolean changed = true;
Dianne Hackborne639da72012-02-21 15:11:13 -08002167 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002168 if (added) {
2169 bp = new BasePermission(info.name, tree.sourcePackage,
2170 BasePermission.TYPE_DYNAMIC);
2171 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2172 throw new SecurityException(
2173 "Not allowed to modify non-dynamic permission "
2174 + info.name);
2175 } else {
Dianne Hackborne639da72012-02-21 15:11:13 -08002176 if (bp.protectionLevel == fixedLevel
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002177 && bp.perm.owner.equals(tree.perm.owner)
2178 && bp.uid == tree.uid
2179 && comparePermissionInfos(bp.perm.info, info)) {
2180 changed = false;
2181 }
2182 }
Dianne Hackborne639da72012-02-21 15:11:13 -08002183 bp.protectionLevel = fixedLevel;
2184 info = new PermissionInfo(info);
2185 info.protectionLevel = fixedLevel;
2186 bp.perm = new PackageParser.Permission(tree.perm.owner, info);
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002187 bp.perm.info.packageName = tree.perm.info.packageName;
2188 bp.uid = tree.uid;
2189 if (added) {
2190 mSettings.mPermissions.put(info.name, bp);
2191 }
2192 if (changed) {
2193 if (!async) {
Kenny Root447106f2011-03-23 11:00:15 -07002194 mSettings.writeLPr();
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002195 } else {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002196 scheduleWriteSettingsLocked();
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002197 }
2198 }
2199 return added;
2200 }
2201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 public boolean addPermission(PermissionInfo info) {
2203 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002204 return addPermissionLocked(info, false);
2205 }
2206 }
2207
2208 public boolean addPermissionAsync(PermissionInfo info) {
2209 synchronized (mPackages) {
2210 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211 }
2212 }
2213
2214 public void removePermission(String name) {
2215 synchronized (mPackages) {
2216 checkPermissionTreeLP(name);
2217 BasePermission bp = mSettings.mPermissions.get(name);
2218 if (bp != null) {
2219 if (bp.type != BasePermission.TYPE_DYNAMIC) {
2220 throw new SecurityException(
2221 "Not allowed to modify non-dynamic permission "
2222 + name);
2223 }
2224 mSettings.mPermissions.remove(name);
Kenny Root447106f2011-03-23 11:00:15 -07002225 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 }
2227 }
2228 }
2229
Dianne Hackborne639da72012-02-21 15:11:13 -08002230 public void grantPermission(String packageName, String permissionName) {
2231 mContext.enforceCallingOrSelfPermission(
2232 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2233 synchronized (mPackages) {
2234 final PackageParser.Package pkg = mPackages.get(packageName);
2235 if (pkg == null) {
2236 throw new IllegalArgumentException("Unknown package: " + packageName);
2237 }
2238 final BasePermission bp = mSettings.mPermissions.get(permissionName);
2239 if (bp == null) {
2240 throw new IllegalArgumentException("Unknown permission: " + packageName);
2241 }
2242 if (!pkg.requestedPermissions.contains(permissionName)) {
2243 throw new SecurityException("Package " + packageName
2244 + " has not requested permission " + permissionName);
2245 }
2246 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) == 0) {
2247 throw new SecurityException("Permission " + permissionName
2248 + " is not a development permission");
2249 }
2250 final PackageSetting ps = (PackageSetting) pkg.mExtras;
2251 if (ps == null) {
2252 return;
2253 }
2254 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2255 if (gp.grantedPermissions.add(permissionName)) {
2256 if (ps.haveGids) {
2257 gp.gids = appendInts(gp.gids, bp.gids);
2258 }
2259 mSettings.writeLPr();
2260 }
2261 }
2262 }
2263
2264 public void revokePermission(String packageName, String permissionName) {
2265 synchronized (mPackages) {
2266 final PackageParser.Package pkg = mPackages.get(packageName);
2267 if (pkg == null) {
2268 throw new IllegalArgumentException("Unknown package: " + packageName);
2269 }
2270 if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2271 mContext.enforceCallingOrSelfPermission(
2272 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2273 }
2274 final BasePermission bp = mSettings.mPermissions.get(permissionName);
2275 if (bp == null) {
2276 throw new IllegalArgumentException("Unknown permission: " + packageName);
2277 }
2278 if (!pkg.requestedPermissions.contains(permissionName)) {
2279 throw new SecurityException("Package " + packageName
2280 + " has not requested permission " + permissionName);
2281 }
2282 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) == 0) {
2283 throw new SecurityException("Permission " + permissionName
2284 + " is not a development permission");
2285 }
2286 final PackageSetting ps = (PackageSetting) pkg.mExtras;
2287 if (ps == null) {
2288 return;
2289 }
2290 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2291 if (gp.grantedPermissions.remove(permissionName)) {
2292 gp.grantedPermissions.remove(permissionName);
2293 if (ps.haveGids) {
2294 gp.gids = removeInts(gp.gids, bp.gids);
2295 }
2296 mSettings.writeLPr();
2297 }
2298 }
2299 }
2300
Dianne Hackborn854060af2009-07-09 18:14:31 -07002301 public boolean isProtectedBroadcast(String actionName) {
2302 synchronized (mPackages) {
2303 return mProtectedBroadcasts.contains(actionName);
2304 }
2305 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002307 public int checkSignatures(String pkg1, String pkg2) {
2308 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002309 final PackageParser.Package p1 = mPackages.get(pkg1);
2310 final PackageParser.Package p2 = mPackages.get(pkg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 if (p1 == null || p1.mExtras == null
2312 || p2 == null || p2.mExtras == null) {
2313 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2314 }
Kenny Root447106f2011-03-23 11:00:15 -07002315 return compareSignatures(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002316 }
2317 }
2318
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002319 public int checkUidSignatures(int uid1, int uid2) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002320 // Map to base uids.
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002321 uid1 = UserHandle.getAppId(uid1);
2322 uid2 = UserHandle.getAppId(uid2);
Kenny Root447106f2011-03-23 11:00:15 -07002323 // reader
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002324 synchronized (mPackages) {
2325 Signature[] s1;
2326 Signature[] s2;
Kenny Root447106f2011-03-23 11:00:15 -07002327 Object obj = mSettings.getUserIdLPr(uid1);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002328 if (obj != null) {
2329 if (obj instanceof SharedUserSetting) {
2330 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2331 } else if (obj instanceof PackageSetting) {
2332 s1 = ((PackageSetting)obj).signatures.mSignatures;
2333 } else {
2334 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2335 }
2336 } else {
2337 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2338 }
Kenny Root447106f2011-03-23 11:00:15 -07002339 obj = mSettings.getUserIdLPr(uid2);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002340 if (obj != null) {
2341 if (obj instanceof SharedUserSetting) {
2342 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2343 } else if (obj instanceof PackageSetting) {
2344 s2 = ((PackageSetting)obj).signatures.mSignatures;
2345 } else {
2346 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2347 }
2348 } else {
2349 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2350 }
Kenny Root447106f2011-03-23 11:00:15 -07002351 return compareSignatures(s1, s2);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002352 }
2353 }
2354
Kenny Root447106f2011-03-23 11:00:15 -07002355 static int compareSignatures(Signature[] s1, Signature[] s2) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002356 if (s1 == null) {
2357 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002358 ? PackageManager.SIGNATURE_NEITHER_SIGNED
2359 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2360 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002361 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002362 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2363 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002364 HashSet<Signature> set1 = new HashSet<Signature>();
2365 for (Signature sig : s1) {
2366 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002368 HashSet<Signature> set2 = new HashSet<Signature>();
2369 for (Signature sig : s2) {
2370 set2.add(sig);
2371 }
2372 // Make sure s2 contains all signatures in s1.
2373 if (set1.equals(set2)) {
2374 return PackageManager.SIGNATURE_MATCH;
2375 }
2376 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377 }
2378
2379 public String[] getPackagesForUid(int uid) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002380 uid = UserHandle.getAppId(uid);
Kenny Root447106f2011-03-23 11:00:15 -07002381 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002382 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002383 Object obj = mSettings.getUserIdLPr(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384 if (obj instanceof SharedUserSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002385 final SharedUserSetting sus = (SharedUserSetting) obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002386 final int N = sus.packages.size();
Kenny Root447106f2011-03-23 11:00:15 -07002387 final String[] res = new String[N];
2388 final Iterator<PackageSetting> it = sus.packages.iterator();
2389 int i = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 while (it.hasNext()) {
2391 res[i++] = it.next().name;
2392 }
2393 return res;
2394 } else if (obj instanceof PackageSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002395 final PackageSetting ps = (PackageSetting) obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396 return new String[] { ps.name };
2397 }
2398 }
2399 return null;
2400 }
2401
2402 public String getNameForUid(int uid) {
Kenny Root447106f2011-03-23 11:00:15 -07002403 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002404 synchronized (mPackages) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002405 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406 if (obj instanceof SharedUserSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002407 final SharedUserSetting sus = (SharedUserSetting) obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002408 return sus.name + ":" + sus.userId;
2409 } else if (obj instanceof PackageSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002410 final PackageSetting ps = (PackageSetting) obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 return ps.name;
2412 }
2413 }
2414 return null;
2415 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 public int getUidForSharedUser(String sharedUserName) {
2418 if(sharedUserName == null) {
2419 return -1;
2420 }
Kenny Root447106f2011-03-23 11:00:15 -07002421 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002423 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
Amith Yamasani742a6712011-05-04 14:49:28 -07002424 if (suid == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002425 return -1;
2426 }
2427 return suid.userId;
2428 }
2429 }
2430
Amith Yamasani483f3b02012-03-13 16:08:00 -07002431 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002433 int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002434 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07002435 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
Amith Yamasani483f3b02012-03-13 16:08:00 -07002436 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2437 return chooseBestActivity(intent, resolvedType, flags, query, userId);
Mihai Predaeae850c2009-05-13 10:13:48 +02002438 }
2439
Mihai Predaeae850c2009-05-13 10:13:48 +02002440 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002441 int flags, List<ResolveInfo> query, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 if (query != null) {
2443 final int N = query.size();
2444 if (N == 1) {
2445 return query.get(0);
2446 } else if (N > 1) {
2447 // If there is more than one activity with the same priority,
2448 // then let the user decide between them.
2449 ResolveInfo r0 = query.get(0);
2450 ResolveInfo r1 = query.get(1);
Kenny Root4dfe6ff2011-02-23 17:00:43 -08002451 if (DEBUG_INTENT_MATCHING) {
2452 Log.d(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2453 + r1.activityInfo.name + "=" + r1.priority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 }
2455 // If the first activity has a higher priority, or a different
2456 // default, then it is always desireable to pick it.
2457 if (r0.priority != r1.priority
2458 || r0.preferredOrder != r1.preferredOrder
2459 || r0.isDefault != r1.isDefault) {
2460 return query.get(0);
2461 }
2462 // If we have saved a preference for a preferred activity for
2463 // this Intent, use that.
2464 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002465 flags, query, r0.priority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002466 if (ri != null) {
2467 return ri;
2468 }
2469 return mResolveInfo;
2470 }
2471 }
2472 return null;
2473 }
2474
2475 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002476 int flags, List<ResolveInfo> query, int priority, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002477 if (!sUserManager.exists(userId)) return null;
Kenny Root447106f2011-03-23 11:00:15 -07002478 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 synchronized (mPackages) {
Dianne Hackbornf5b86712011-12-05 17:42:41 -08002480 if (intent.getSelector() != null) {
2481 intent = intent.getSelector();
2482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002483 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
2484 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02002485 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002486 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 if (prefs != null && prefs.size() > 0) {
2488 // First figure out how good the original match set is.
2489 // We will only allow preferred activities that came
2490 // from the same match quality.
2491 int match = 0;
Kenny Root447106f2011-03-23 11:00:15 -07002492
2493 if (DEBUG_PREFERRED) {
2494 Log.v(TAG, "Figuring out best match...");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 }
Kenny Root447106f2011-03-23 11:00:15 -07002496
2497 final int N = query.size();
2498 for (int j=0; j<N; j++) {
2499 final ResolveInfo ri = query.get(j);
2500 if (DEBUG_PREFERRED) {
2501 Log.v(TAG, "Match for " + ri.activityInfo + ": 0x"
2502 + Integer.toHexString(match));
2503 }
2504 if (ri.match > match) {
2505 match = ri.match;
2506 }
2507 }
2508
2509 if (DEBUG_PREFERRED) {
2510 Log.v(TAG, "Best match: 0x" + Integer.toHexString(match));
2511 }
2512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 match &= IntentFilter.MATCH_CATEGORY_MASK;
2514 final int M = prefs.size();
2515 for (int i=0; i<M; i++) {
Kenny Root447106f2011-03-23 11:00:15 -07002516 final PreferredActivity pa = prefs.get(i);
Amith Yamasania3f133a2012-08-09 17:11:28 -07002517 if (pa.mUserId != userId) {
2518 continue;
2519 }
Dianne Hackbornf8b8a3f2011-03-04 00:05:31 -08002520 if (pa.mPref.mMatch != match) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 continue;
2522 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07002523 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 if (DEBUG_PREFERRED) {
2525 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002526 if (ai != null) {
2527 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2528 } else {
2529 Log.v(TAG, " null");
2530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531 }
Dianne Hackborn04505102012-02-29 12:34:04 -08002532 if (ai == null) {
2533 // This previously registered preferred activity
2534 // component is no longer known. Most likely an update
2535 // to the app was installed and in the new version this
2536 // component no longer exists. Clean it up by removing
2537 // it from the preferred activities list, and skip it.
2538 Slog.w(TAG, "Removing dangling preferred activity: "
2539 + pa.mPref.mComponent);
2540 mSettings.mPreferredActivities.removeFilter(pa);
2541 continue;
2542 }
2543 for (int j=0; j<N; j++) {
2544 final ResolveInfo ri = query.get(j);
2545 if (!ri.activityInfo.applicationInfo.packageName
2546 .equals(ai.applicationInfo.packageName)) {
2547 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 }
Dianne Hackborn04505102012-02-29 12:34:04 -08002549 if (!ri.activityInfo.name.equals(ai.name)) {
2550 continue;
2551 }
2552
2553 // Okay we found a previously set preferred app.
2554 // If the result set is different from when this
2555 // was created, we need to clear it and re-ask the
2556 // user their preference.
2557 if (!pa.mPref.sameSet(query, priority)) {
2558 Slog.i(TAG, "Result set changed, dropping preferred activity for "
2559 + intent + " type " + resolvedType);
2560 mSettings.mPreferredActivities.removeFilter(pa);
2561 return null;
2562 }
2563
2564 // Yay!
2565 return ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 }
2567 }
2568 }
2569 }
2570 return null;
2571 }
2572
Amith Yamasani483f3b02012-03-13 16:08:00 -07002573 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 public List<ResolveInfo> queryIntentActivities(Intent intent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002575 String resolvedType, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002576 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07002577 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
Dianne Hackbornf5b86712011-12-05 17:42:41 -08002578 ComponentName comp = intent.getComponent();
2579 if (comp == null) {
2580 if (intent.getSelector() != null) {
2581 intent = intent.getSelector();
2582 comp = intent.getComponent();
2583 }
2584 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 if (comp != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002587 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
Amith Yamasani483f3b02012-03-13 16:08:00 -07002588 final ActivityInfo ai = getActivityInfo(comp, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 if (ai != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002590 final ResolveInfo ri = new ResolveInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 ri.activityInfo = ai;
2592 list.add(ri);
2593 }
2594 return list;
2595 }
2596
Kenny Root447106f2011-03-23 11:00:15 -07002597 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002598 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002599 final String pkgName = intent.getPackage();
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002600 if (pkgName == null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002601 return mActivities.queryIntent(intent, resolvedType, flags, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002602 }
Kenny Root447106f2011-03-23 11:00:15 -07002603 final PackageParser.Package pkg = mPackages.get(pkgName);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002604 if (pkg != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002605 return mActivities.queryIntentForPackage(intent, resolvedType, flags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002606 pkg.activities, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002607 }
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002608 return new ArrayList<ResolveInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 }
2610 }
2611
Amith Yamasani483f3b02012-03-13 16:08:00 -07002612 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2614 Intent[] specifics, String[] specificTypes, Intent intent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002615 String resolvedType, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002616 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07002617 enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
2618 "query intent activity options");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 final String resultsAction = intent.getAction();
2620
Kenny Root447106f2011-03-23 11:00:15 -07002621 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
Amith Yamasani483f3b02012-03-13 16:08:00 -07002622 | PackageManager.GET_RESOLVED_FILTER, userId);
Kenny Root447106f2011-03-23 11:00:15 -07002623
2624 if (DEBUG_INTENT_MATCHING) {
2625 Log.v(TAG, "Query " + intent + ": " + results);
2626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627
2628 int specificsPos = 0;
2629 int N;
2630
2631 // todo: note that the algorithm used here is O(N^2). This
2632 // isn't a problem in our current environment, but if we start running
2633 // into situations where we have more than 5 or 10 matches then this
2634 // should probably be changed to something smarter...
2635
2636 // First we go through and resolve each of the specific items
2637 // that were supplied, taking care of removing any corresponding
2638 // duplicate items in the generic resolve list.
2639 if (specifics != null) {
2640 for (int i=0; i<specifics.length; i++) {
2641 final Intent sintent = specifics[i];
2642 if (sintent == null) {
2643 continue;
2644 }
2645
Kenny Root447106f2011-03-23 11:00:15 -07002646 if (DEBUG_INTENT_MATCHING) {
2647 Log.v(TAG, "Specific #" + i + ": " + sintent);
2648 }
2649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 String action = sintent.getAction();
2651 if (resultsAction != null && resultsAction.equals(action)) {
2652 // If this action was explicitly requested, then don't
2653 // remove things that have it.
2654 action = null;
2655 }
Kenny Root447106f2011-03-23 11:00:15 -07002656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002657 ResolveInfo ri = null;
2658 ActivityInfo ai = null;
Kenny Root447106f2011-03-23 11:00:15 -07002659
2660 ComponentName comp = sintent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 if (comp == null) {
2662 ri = resolveIntent(
2663 sintent,
2664 specificTypes != null ? specificTypes[i] : null,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002665 flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 if (ri == null) {
2667 continue;
2668 }
2669 if (ri == mResolveInfo) {
2670 // ACK! Must do something better with this.
2671 }
2672 ai = ri.activityInfo;
2673 comp = new ComponentName(ai.applicationInfo.packageName,
2674 ai.name);
2675 } else {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002676 ai = getActivityInfo(comp, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 if (ai == null) {
2678 continue;
2679 }
2680 }
2681
2682 // Look for any generic query activities that are duplicates
2683 // of this specific one, and remove them from the results.
Kenny Root9718cf52011-02-23 16:45:26 -08002684 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 N = results.size();
2686 int j;
2687 for (j=specificsPos; j<N; j++) {
2688 ResolveInfo sri = results.get(j);
2689 if ((sri.activityInfo.name.equals(comp.getClassName())
2690 && sri.activityInfo.applicationInfo.packageName.equals(
2691 comp.getPackageName()))
2692 || (action != null && sri.filter.matchAction(action))) {
2693 results.remove(j);
Kenny Root9718cf52011-02-23 16:45:26 -08002694 if (DEBUG_INTENT_MATCHING) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002695 TAG, "Removing duplicate item from " + j
2696 + " due to specific " + specificsPos);
2697 if (ri == null) {
2698 ri = sri;
2699 }
2700 j--;
2701 N--;
2702 }
2703 }
2704
2705 // Add this specific item to its proper place.
2706 if (ri == null) {
2707 ri = new ResolveInfo();
2708 ri.activityInfo = ai;
2709 }
2710 results.add(specificsPos, ri);
2711 ri.specificIndex = i;
2712 specificsPos++;
2713 }
2714 }
2715
2716 // Now we go through the remaining generic results and remove any
2717 // duplicate actions that are found here.
2718 N = results.size();
2719 for (int i=specificsPos; i<N-1; i++) {
2720 final ResolveInfo rii = results.get(i);
2721 if (rii.filter == null) {
2722 continue;
2723 }
2724
2725 // Iterate over all of the actions of this result's intent
2726 // filter... typically this should be just one.
2727 final Iterator<String> it = rii.filter.actionsIterator();
2728 if (it == null) {
2729 continue;
2730 }
2731 while (it.hasNext()) {
2732 final String action = it.next();
2733 if (resultsAction != null && resultsAction.equals(action)) {
2734 // If this action was explicitly requested, then don't
2735 // remove things that have it.
2736 continue;
2737 }
2738 for (int j=i+1; j<N; j++) {
2739 final ResolveInfo rij = results.get(j);
2740 if (rij.filter != null && rij.filter.hasAction(action)) {
2741 results.remove(j);
Kenny Root9718cf52011-02-23 16:45:26 -08002742 if (DEBUG_INTENT_MATCHING) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002743 TAG, "Removing duplicate item from " + j
2744 + " due to action " + action + " at " + i);
2745 j--;
2746 N--;
2747 }
2748 }
2749 }
2750
2751 // If the caller didn't request filter information, drop it now
2752 // so we don't have to marshall/unmarshall it.
2753 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2754 rii.filter = null;
2755 }
2756 }
2757
2758 // Filter out the caller activity if so requested.
2759 if (caller != null) {
2760 N = results.size();
2761 for (int i=0; i<N; i++) {
2762 ActivityInfo ainfo = results.get(i).activityInfo;
2763 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2764 && caller.getClassName().equals(ainfo.name)) {
2765 results.remove(i);
2766 break;
2767 }
2768 }
2769 }
2770
2771 // If the caller didn't request filter information,
2772 // drop them now so we don't have to
2773 // marshall/unmarshall it.
2774 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2775 N = results.size();
2776 for (int i=0; i<N; i++) {
2777 results.get(i).filter = null;
2778 }
2779 }
2780
Kenny Root9718cf52011-02-23 16:45:26 -08002781 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 return results;
2783 }
2784
Amith Yamasani483f3b02012-03-13 16:08:00 -07002785 @Override
2786 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
2787 int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002788 if (!sUserManager.exists(userId)) return null;
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002789 ComponentName comp = intent.getComponent();
Dianne Hackbornf5b86712011-12-05 17:42:41 -08002790 if (comp == null) {
2791 if (intent.getSelector() != null) {
2792 intent = intent.getSelector();
2793 comp = intent.getComponent();
2794 }
2795 }
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002796 if (comp != null) {
2797 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
Amith Yamasani483f3b02012-03-13 16:08:00 -07002798 ActivityInfo ai = getReceiverInfo(comp, flags, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002799 if (ai != null) {
2800 ResolveInfo ri = new ResolveInfo();
2801 ri.activityInfo = ai;
2802 list.add(ri);
2803 }
2804 return list;
2805 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002806
Kenny Root447106f2011-03-23 11:00:15 -07002807 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 synchronized (mPackages) {
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002809 String pkgName = intent.getPackage();
2810 if (pkgName == null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002811 return mReceivers.queryIntent(intent, resolvedType, flags, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002812 }
Kenny Root447106f2011-03-23 11:00:15 -07002813 final PackageParser.Package pkg = mPackages.get(pkgName);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002814 if (pkg != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002815 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
2816 userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002817 }
2818 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 }
2820 }
2821
Amith Yamasani483f3b02012-03-13 16:08:00 -07002822 @Override
2823 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
2824 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
Amith Yamasani13593602012-03-22 16:16:17 -07002825 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 if (query != null) {
2827 if (query.size() >= 1) {
2828 // If there is more than one service with the same priority,
2829 // just arbitrarily pick the first one.
2830 return query.get(0);
2831 }
2832 }
2833 return null;
2834 }
2835
Amith Yamasani483f3b02012-03-13 16:08:00 -07002836 @Override
2837 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
2838 int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002839 if (!sUserManager.exists(userId)) return null;
Dianne Hackbornf5b86712011-12-05 17:42:41 -08002840 ComponentName comp = intent.getComponent();
2841 if (comp == null) {
2842 if (intent.getSelector() != null) {
2843 intent = intent.getSelector();
2844 comp = intent.getComponent();
2845 }
2846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002847 if (comp != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002848 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
Amith Yamasani483f3b02012-03-13 16:08:00 -07002849 final ServiceInfo si = getServiceInfo(comp, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 if (si != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002851 final ResolveInfo ri = new ResolveInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 ri.serviceInfo = si;
2853 list.add(ri);
2854 }
2855 return list;
2856 }
2857
Kenny Root447106f2011-03-23 11:00:15 -07002858 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 synchronized (mPackages) {
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002860 String pkgName = intent.getPackage();
2861 if (pkgName == null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002862 return mServices.queryIntent(intent, resolvedType, flags, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002863 }
Kenny Root447106f2011-03-23 11:00:15 -07002864 final PackageParser.Package pkg = mPackages.get(pkgName);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002865 if (pkg != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002866 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
2867 userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002868 }
2869 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 }
2871 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002872
Kenny Root0e2c0f32011-04-15 17:50:10 -07002873 private static final int getContinuationPoint(final String[] keys, final String key) {
2874 final int index;
2875 if (key == null) {
2876 index = 0;
2877 } else {
2878 final int insertPoint = Arrays.binarySearch(keys, key);
2879 if (insertPoint < 0) {
2880 index = -insertPoint;
2881 } else {
2882 index = insertPoint + 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 }
2884 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002885 return index;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 }
2887
Kenny Root0e2c0f32011-04-15 17:50:10 -07002888 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, String lastRead) {
2889 final ParceledListSlice<PackageInfo> list = new ParceledListSlice<PackageInfo>();
2890 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
2891 final String[] keys;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002892 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893
Kenny Root447106f2011-03-23 11:00:15 -07002894 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 synchronized (mPackages) {
Kenny Root0e2c0f32011-04-15 17:50:10 -07002896 if (listUninstalled) {
2897 keys = mSettings.mPackages.keySet().toArray(new String[mSettings.mPackages.size()]);
2898 } else {
2899 keys = mPackages.keySet().toArray(new String[mPackages.size()]);
2900 }
2901
2902 Arrays.sort(keys);
2903 int i = getContinuationPoint(keys, lastRead);
2904 final int N = keys.length;
2905
2906 while (i < N) {
2907 final String packageName = keys[i++];
2908
2909 PackageInfo pi = null;
2910 if (listUninstalled) {
2911 final PackageSetting ps = mSettings.mPackages.get(packageName);
2912 if (ps != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002913 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002915 } else {
2916 final PackageParser.Package p = mPackages.get(packageName);
2917 if (p != null) {
Amith Yamasani13593602012-03-22 16:16:17 -07002918 pi = generatePackageInfo(p, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 }
2920 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002921
Henrik Engström9771a312012-02-21 09:05:17 +01002922 if (pi != null && list.append(pi)) {
Kenny Root0e2c0f32011-04-15 17:50:10 -07002923 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002924 }
2925 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002926
2927 if (i == N) {
2928 list.setLastSlice(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002931
2932 return list;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002933 }
2934
Amith Yamasani483f3b02012-03-13 16:08:00 -07002935 @Override
Kenny Root0e2c0f32011-04-15 17:50:10 -07002936 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002937 String lastRead, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002938 if (!sUserManager.exists(userId)) return null;
Kenny Root0e2c0f32011-04-15 17:50:10 -07002939 final ParceledListSlice<ApplicationInfo> list = new ParceledListSlice<ApplicationInfo>();
2940 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
2941 final String[] keys;
2942
Kenny Root447106f2011-03-23 11:00:15 -07002943 // writer
Kenny Root0e2c0f32011-04-15 17:50:10 -07002944 synchronized (mPackages) {
2945 if (listUninstalled) {
2946 keys = mSettings.mPackages.keySet().toArray(new String[mSettings.mPackages.size()]);
2947 } else {
2948 keys = mPackages.keySet().toArray(new String[mPackages.size()]);
2949 }
2950
2951 Arrays.sort(keys);
2952 int i = getContinuationPoint(keys, lastRead);
2953 final int N = keys.length;
2954
2955 while (i < N) {
2956 final String packageName = keys[i++];
2957
2958 ApplicationInfo ai = null;
Amith Yamasani13593602012-03-22 16:16:17 -07002959 final PackageSetting ps = mSettings.mPackages.get(packageName);
Kenny Root0e2c0f32011-04-15 17:50:10 -07002960 if (listUninstalled) {
Kenny Root0e2c0f32011-04-15 17:50:10 -07002961 if (ps != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002962 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
Kenny Root0e2c0f32011-04-15 17:50:10 -07002963 }
2964 } else {
2965 final PackageParser.Package p = mPackages.get(packageName);
Amith Yamasani13593602012-03-22 16:16:17 -07002966 if (p != null && ps != null) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002967 ai = PackageParser.generateApplicationInfo(p, flags,
2968 ps.readUserState(userId), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002969 }
2970 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002971
Henrik Engström9771a312012-02-21 09:05:17 +01002972 if (ai != null && list.append(ai)) {
Kenny Root0e2c0f32011-04-15 17:50:10 -07002973 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 }
2975 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002976
2977 if (i == N) {
2978 list.setLastSlice(true);
2979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002981
2982 return list;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002983 }
2984
2985 public List<ApplicationInfo> getPersistentApplications(int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07002986 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002987
Kenny Root447106f2011-03-23 11:00:15 -07002988 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002989 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002990 final Iterator<PackageParser.Package> i = mPackages.values().iterator();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002991 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 while (i.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07002993 final PackageParser.Package p = i.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002994 if (p.applicationInfo != null
2995 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002996 && (!mSafeMode || isSystemApp(p))) {
Amith Yamasani13593602012-03-22 16:16:17 -07002997 PackageSetting ps = mSettings.mPackages.get(p.packageName);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002998 if (ps != null) {
2999 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3000 ps.readUserState(userId), userId);
3001 if (ai != null) {
3002 finalList.add(ai);
3003 }
3004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003005 }
3006 }
3007 }
3008
3009 return finalList;
3010 }
3011
Amith Yamasani483f3b02012-03-13 16:08:00 -07003012 @Override
3013 public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07003014 if (!sUserManager.exists(userId)) return null;
Kenny Root447106f2011-03-23 11:00:15 -07003015 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016 synchronized (mPackages) {
3017 final PackageParser.Provider provider = mProviders.get(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003018 PackageSetting ps = provider != null
3019 ? mSettings.mPackages.get(provider.owner.packageName)
3020 : null;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003021 return ps != null
Amith Yamasani483f3b02012-03-13 16:08:00 -07003022 && mSettings.isEnabledLPr(provider.info, flags, userId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023 && (!mSafeMode || (provider.info.applicationInfo.flags
3024 &ApplicationInfo.FLAG_SYSTEM) != 0)
Amith Yamasani13593602012-03-22 16:16:17 -07003025 ? PackageParser.generateProviderInfo(provider, flags,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003026 ps.readUserState(userId), userId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003027 : null;
3028 }
3029 }
3030
Fred Quintana718d8a22009-04-29 17:53:20 -07003031 /**
3032 * @deprecated
3033 */
Kenny Root60f7ad82011-03-22 12:49:06 -07003034 @Deprecated
3035 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
Kenny Root447106f2011-03-23 11:00:15 -07003036 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003037 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07003038 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProviders.entrySet()
3039 .iterator();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003040 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003041 while (i.hasNext()) {
3042 Map.Entry<String, PackageParser.Provider> entry = i.next();
3043 PackageParser.Provider p = entry.getValue();
Amith Yamasani13593602012-03-22 16:16:17 -07003044 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003045
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003046 if (ps != null && p.syncable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047 && (!mSafeMode || (p.info.applicationInfo.flags
3048 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003049 ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3050 ps.readUserState(userId), userId);
3051 if (info != null) {
3052 outNames.add(entry.getKey());
3053 outInfo.add(info);
3054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003055 }
3056 }
3057 }
3058 }
3059
3060 public List<ProviderInfo> queryContentProviders(String processName,
3061 int uid, int flags) {
3062 ArrayList<ProviderInfo> finalList = null;
3063
Kenny Root447106f2011-03-23 11:00:15 -07003064 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07003066 final Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
Amith Yamasani483f3b02012-03-13 16:08:00 -07003067 final int userId = processName != null ?
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003068 UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003069 while (i.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07003070 final PackageParser.Provider p = i.next();
Amith Yamasani13593602012-03-22 16:16:17 -07003071 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003072 if (ps != null && p.info.authority != null
Kenny Root447106f2011-03-23 11:00:15 -07003073 && (processName == null
3074 || (p.info.processName.equals(processName)
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003075 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
Amith Yamasani483f3b02012-03-13 16:08:00 -07003076 && mSettings.isEnabledLPr(p.info, flags, userId)
Kenny Root447106f2011-03-23 11:00:15 -07003077 && (!mSafeMode
3078 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003079 if (finalList == null) {
3080 finalList = new ArrayList<ProviderInfo>(3);
3081 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003082 ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3083 ps.readUserState(userId), userId);
Dianne Hackborn4428e172012-08-24 17:43:05 -07003084 if (info != null) {
3085 finalList.add(info);
3086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 }
3088 }
3089 }
3090
3091 if (finalList != null) {
3092 Collections.sort(finalList, mProviderInitOrderSorter);
3093 }
3094
3095 return finalList;
3096 }
3097
3098 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3099 int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07003100 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003101 synchronized (mPackages) {
3102 final PackageParser.Instrumentation i = mInstrumentation.get(name);
3103 return PackageParser.generateInstrumentationInfo(i, flags);
3104 }
3105 }
3106
3107 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3108 int flags) {
3109 ArrayList<InstrumentationInfo> finalList =
3110 new ArrayList<InstrumentationInfo>();
3111
Kenny Root447106f2011-03-23 11:00:15 -07003112 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003113 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07003114 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003115 while (i.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07003116 final PackageParser.Instrumentation p = i.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003117 if (targetPackage == null
3118 || targetPackage.equals(p.info.targetPackage)) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07003119 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3120 flags);
3121 if (ii != null) {
3122 finalList.add(ii);
3123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003124 }
3125 }
3126 }
3127
3128 return finalList;
3129 }
3130
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003131 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 String[] files = dir.list();
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07003133 if (files == null) {
3134 Log.d(TAG, "No files in app dir " + dir);
3135 return;
3136 }
3137
Kenny Root4dfe6ff2011-02-23 17:00:43 -08003138 if (DEBUG_PACKAGE_SCANNING) {
Joe Onorato431bb222010-10-18 19:13:23 -04003139 Log.d(TAG, "Scanning app dir " + dir);
3140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141
3142 int i;
3143 for (i=0; i<files.length; i++) {
3144 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003145 if (!isPackageFilename(files[i])) {
3146 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08003147 continue;
3148 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003149 PackageParser.Package pkg = scanPackageLI(file,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003150 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003151 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08003152 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
3153 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003154 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003155 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003156 file.delete();
3157 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 }
3159 }
3160
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003161 private static File getSettingsProblemFile() {
3162 File dataDir = Environment.getDataDirectory();
3163 File systemDir = new File(dataDir, "system");
3164 File fname = new File(systemDir, "uiderrors.txt");
3165 return fname;
3166 }
3167
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003168 static void reportSettingsProblem(int priority, String msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003169 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003170 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003171 FileOutputStream out = new FileOutputStream(fname, true);
3172 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003173 SimpleDateFormat formatter = new SimpleDateFormat();
3174 String dateString = formatter.format(new Date(System.currentTimeMillis()));
3175 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003176 pw.close();
3177 FileUtils.setPermissions(
3178 fname.toString(),
3179 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
3180 -1, -1);
3181 } catch (java.io.IOException e) {
3182 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003183 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003184 }
3185
3186 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
3187 PackageParser.Package pkg, File srcFile, int parseFlags) {
3188 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07003189 if (ps != null
3190 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07003191 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07003192 if (ps.signatures.mSignatures != null
3193 && ps.signatures.mSignatures.length != 0) {
3194 // Optimization: reuse the existing cached certificates
3195 // if the package appears to be unchanged.
3196 pkg.mSignatures = ps.signatures.mSignatures;
3197 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 }
Jeff Browne7600722010-04-07 18:28:23 -07003199
3200 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003201 } else {
Jeff Browne7600722010-04-07 18:28:23 -07003202 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
3203 }
3204
3205 if (!pp.collectCertificates(pkg, parseFlags)) {
3206 mLastScanError = pp.getParseError();
3207 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 }
3209 }
3210 return true;
3211 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213 /*
3214 * Scan a package and return the newly parsed package.
3215 * Returns null in case of errors and the error code is stored in mLastScanError
3216 */
3217 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003218 int parseFlags, int scanMode, long currentTime, UserHandle user) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003219 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003220 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003222 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 pp.setSeparateProcesses(mSeparateProcesses);
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07003224 pp.setOnlyCoreApps(mOnlyCore);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003226 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003227 if (pkg == null) {
3228 mLastScanError = pp.getParseError();
3229 return null;
3230 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003231 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003232 PackageSetting updatedPkg;
Kenny Root447106f2011-03-23 11:00:15 -07003233 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003234 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003235 // Look to see if we already know about this package.
3236 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08003237 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003238 // This package has been renamed to its original name. Let's
3239 // use that.
Kenny Root447106f2011-03-23 11:00:15 -07003240 ps = mSettings.peekPackageLPr(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003241 }
3242 // If there was no original package, see one for the real package name.
3243 if (ps == null) {
Kenny Root447106f2011-03-23 11:00:15 -07003244 ps = mSettings.peekPackageLPr(pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003245 }
3246 // Check to see if this package could be hiding/updating a system
3247 // package. Must look for it either under the original or real
3248 // package name depending on our state.
Kenny Rootc52d6fd2012-05-07 23:04:52 -07003249 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003251 // First check if this is a system package that may involve an update
3252 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07003253 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003254 // The path has changed from what was last scanned... check the
3255 // version of the new path against what we have stored to determine
3256 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003257 if (pkg.mVersionCode < ps.versionCode) {
3258 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003259 // Ignore entry. Skip it.
3260 Log.i(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborncef65ee2010-09-30 18:27:22 -07003261 + " ignored: updated version " + ps.versionCode
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003262 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003263 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3264 return null;
3265 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003266 // The current app on the system partion is better than
3267 // what we have updated to on the data partition; switch
3268 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003269 // At this point, its safely assumed that package installation for
3270 // apps in system partition will go through. If not there won't be a working
3271 // version of the app
Kenny Root447106f2011-03-23 11:00:15 -07003272 // writer
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003273 synchronized (mPackages) {
3274 // Just remove the loaded entries from package lists.
3275 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003276 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003277 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003278 + "reverting from " + ps.codePathString
3279 + ": new version " + pkg.mVersionCode
3280 + " better than installed " + ps.versionCode);
Kenny Root88670d82012-05-09 15:47:35 -07003281
3282 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3283 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
Dianne Hackborn4428e172012-08-24 17:43:05 -07003284 synchronized (mInstallLock) {
Kenny Root208d3412012-05-07 19:42:35 -07003285 args.cleanUpResourcesLI();
3286 }
3287 synchronized (mPackages) {
3288 mSettings.enableSystemPackageLPw(ps.name);
3289 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 }
3292 }
Kenny Root208d3412012-05-07 19:42:35 -07003293
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003294 if (updatedPkg != null) {
Kenny Root208d3412012-05-07 19:42:35 -07003295 // An updated system app will not have the PARSE_IS_SYSTEM flag set
3296 // initially
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003297 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
3298 }
3299 // Verify certificates against what was last scanned
3300 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003301 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003302 return null;
3303 }
Kenny Root208d3412012-05-07 19:42:35 -07003304
3305 /*
3306 * A new system app appeared, but we already had a non-system one of the
3307 * same name installed earlier.
3308 */
3309 boolean shouldHideSystemApp = false;
3310 if (updatedPkg == null && ps != null
3311 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
3312 /*
3313 * Check to make sure the signatures match first. If they don't,
3314 * wipe the installed application and its data.
3315 */
3316 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
3317 != PackageManager.SIGNATURE_MATCH) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003318 deletePackageLI(pkg.packageName, null, true, 0, null, false);
Kenny Root208d3412012-05-07 19:42:35 -07003319 ps = null;
3320 } else {
3321 /*
3322 * If the newly-added system app is an older version than the
3323 * already installed version, hide it. It will be scanned later
3324 * and re-added like an update.
3325 */
3326 if (pkg.mVersionCode < ps.versionCode) {
3327 shouldHideSystemApp = true;
3328 } else {
3329 /*
3330 * The newly found system app is a newer version that the
3331 * one previously installed. Simply remove the
3332 * already-installed application and replace it with our own
3333 * while keeping the application data.
3334 */
3335 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
3336 + ps.codePathString + ": new version " + pkg.mVersionCode
3337 + " better than installed " + ps.versionCode);
Kenny Root88670d82012-05-09 15:47:35 -07003338 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3339 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
Dianne Hackborn4428e172012-08-24 17:43:05 -07003340 synchronized (mInstallLock) {
Kenny Root208d3412012-05-07 19:42:35 -07003341 args.cleanUpResourcesLI();
3342 }
3343 }
3344 }
3345 }
3346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003347 // The apk is forward locked (not public) if its code and resources
3348 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003349 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003351 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07003352 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003353
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003354 String codePath = null;
3355 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003356 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
3357 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003358 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003359 } else {
3360 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003361 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003362 }
3363 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003364 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003365 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003366 codePath = pkg.mScanPath;
3367 // Set application objects path explicitly.
3368 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 // Note that we invoke the following method only if we are about to unpack an application
Kenny Root208d3412012-05-07 19:42:35 -07003370 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003371 | SCAN_UPDATE_SIGNATURE, currentTime, user);
Kenny Root208d3412012-05-07 19:42:35 -07003372
3373 /*
3374 * If the system app should be overridden by a previously installed
3375 * data, hide the system app now and let the /data/app scan pick it up
3376 * again.
3377 */
3378 if (shouldHideSystemApp) {
3379 synchronized (mPackages) {
3380 /*
3381 * We have to grant systems permissions before we hide, because
3382 * grantPermissions will assume the package update is trying to
3383 * expand its permissions.
3384 */
3385 grantPermissionsLPw(pkg, true);
3386 mSettings.disableSystemPackageLPw(pkg.packageName);
3387 }
3388 }
3389
3390 return scannedPkg;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003391 }
3392
Kenny Root85387d72010-08-26 10:13:11 -07003393 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
3394 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003395 pkg.mPath = pkg.mScanPath = destCodePath;
3396 pkg.applicationInfo.sourceDir = destCodePath;
3397 pkg.applicationInfo.publicSourceDir = destResPath;
3398 }
3399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003400 private static String fixProcessName(String defProcessName,
3401 String processName, int uid) {
3402 if (processName == null) {
3403 return defProcessName;
3404 }
3405 return processName;
3406 }
3407
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003408 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003409 PackageParser.Package pkg) {
3410 if (pkgSetting.signatures.mSignatures != null) {
3411 // Already existing package. Make sure signatures match
Kenny Root447106f2011-03-23 11:00:15 -07003412 if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003413 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003414 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003415 + " signatures do not match the previously installed version; ignoring!");
3416 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 return false;
3418 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003419 }
3420 // Check for shared user signatures
3421 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
Kenny Root447106f2011-03-23 11:00:15 -07003422 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003423 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3424 Slog.e(TAG, "Package " + pkg.packageName
3425 + " has no signatures that match those in shared user "
3426 + pkgSetting.sharedUser.name + "; ignoring!");
3427 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
3428 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003429 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 }
3431 return true;
3432 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003433
Kenny Root461ff1f2011-08-09 09:43:03 -07003434 /**
3435 * Enforces that only the system UID or root's UID can call a method exposed
3436 * via Binder.
3437 *
3438 * @param message used as message if SecurityException is thrown
3439 * @throws SecurityException if the caller is not system or root
3440 */
3441 private static final void enforceSystemOrRoot(String message) {
3442 final int uid = Binder.getCallingUid();
3443 if (uid != Process.SYSTEM_UID && uid != 0) {
3444 throw new SecurityException(message);
3445 }
3446 }
3447
Dianne Hackborn661cd522011-08-22 00:26:20 -07003448 public void performBootDexOpt() {
3449 ArrayList<PackageParser.Package> pkgs = null;
3450 synchronized (mPackages) {
3451 if (mDeferredDexOpt.size() > 0) {
3452 pkgs = new ArrayList<PackageParser.Package>(mDeferredDexOpt);
3453 mDeferredDexOpt.clear();
3454 }
3455 }
3456 if (pkgs != null) {
3457 for (int i=0; i<pkgs.size(); i++) {
Dianne Hackborn58f42a52011-10-10 13:46:34 -07003458 if (!isFirstBoot()) {
3459 try {
3460 ActivityManagerNative.getDefault().showBootMessage(
3461 mContext.getResources().getString(
3462 com.android.internal.R.string.android_upgrading_apk,
3463 i+1, pkgs.size()), true);
3464 } catch (RemoteException e) {
3465 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07003466 }
3467 PackageParser.Package p = pkgs.get(i);
3468 synchronized (mInstallLock) {
3469 if (!p.mDidDexOpt) {
3470 performDexOptLI(p, false, false);
3471 }
3472 }
3473 }
3474 }
3475 }
3476
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003477 public boolean performDexOpt(String packageName) {
Kenny Root461ff1f2011-08-09 09:43:03 -07003478 enforceSystemOrRoot("Only the system can request dexopt be performed");
3479
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003480 if (!mNoDexOpt) {
3481 return false;
3482 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003483
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003484 PackageParser.Package p;
3485 synchronized (mPackages) {
3486 p = mPackages.get(packageName);
3487 if (p == null || p.mDidDexOpt) {
3488 return false;
3489 }
3490 }
3491 synchronized (mInstallLock) {
Dianne Hackborn661cd522011-08-22 00:26:20 -07003492 return performDexOptLI(p, false, false) == DEX_OPT_PERFORMED;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003493 }
3494 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003495
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003496 static final int DEX_OPT_SKIPPED = 0;
3497 static final int DEX_OPT_PERFORMED = 1;
Dianne Hackborn661cd522011-08-22 00:26:20 -07003498 static final int DEX_OPT_DEFERRED = 2;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003499 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003500
Dianne Hackborn661cd522011-08-22 00:26:20 -07003501 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003502 boolean performed = false;
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003503 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003504 String path = pkg.mScanPath;
3505 int ret = 0;
3506 try {
3507 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Dianne Hackborn661cd522011-08-22 00:26:20 -07003508 if (!forceDex && defer) {
3509 mDeferredDexOpt.add(pkg);
3510 return DEX_OPT_DEFERRED;
3511 } else {
3512 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
3513 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
3514 !isForwardLocked(pkg));
3515 pkg.mDidDexOpt = true;
3516 performed = true;
3517 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003518 }
3519 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003520 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003521 ret = -1;
3522 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07003523 Slog.w(TAG, "IOException reading apk: " + path, e);
3524 ret = -1;
3525 } catch (dalvik.system.StaleDexCacheError e) {
3526 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
3527 ret = -1;
3528 } catch (Exception e) {
3529 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003530 ret = -1;
3531 }
3532 if (ret < 0) {
3533 //error from installer
3534 return DEX_OPT_FAILED;
3535 }
3536 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003537
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003538 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
3539 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08003540
Kenny Root447106f2011-03-23 11:00:15 -07003541 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003542 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003543 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003544 + " to " + newPkg.packageName
3545 + ": old package not in system partition");
3546 return false;
3547 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003548 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003549 + " to " + newPkg.packageName
3550 + ": old package still exists");
3551 return false;
3552 }
3553 return true;
3554 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003555
Amith Yamasani0b285492011-04-14 17:35:23 -07003556 File getDataPathForUser(int userId) {
3557 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003558 }
Amith Yamasani0b285492011-04-14 17:35:23 -07003559
3560 private File getDataPathForPackage(String packageName, int userId) {
Kenny Root9c8625e2011-07-25 09:42:22 -07003561 /*
3562 * Until we fully support multiple users, return the directory we
3563 * previously would have. The PackageManagerTests will need to be
3564 * revised when this is changed back..
3565 */
3566 if (userId == 0) {
3567 return new File(mAppDataDir, packageName);
3568 } else {
3569 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
Amith Yamasani0f3f29b2011-05-09 14:17:14 -07003570 + File.separator + packageName);
Kenny Root9c8625e2011-07-25 09:42:22 -07003571 }
Amith Yamasani0b285492011-04-14 17:35:23 -07003572 }
3573
Dianne Hackborn4428e172012-08-24 17:43:05 -07003574 private int createDataDirsLI(String packageName, int uid) {
3575 int[] users = sUserManager.getUserIds();
3576 int res = mInstaller.install(packageName, uid, uid);
3577 if (res < 0) {
3578 return res;
3579 }
3580 for (int user : users) {
3581 if (user != 0) {
3582 res = mInstaller.createUserData(packageName,
3583 UserHandle.getUid(user, uid), user);
3584 if (res < 0) {
3585 return res;
3586 }
3587 }
3588 }
3589 return res;
3590 }
3591
3592 private int removeDataDirsLI(String packageName) {
3593 int[] users = sUserManager.getUserIds();
3594 int res = 0;
3595 for (int user : users) {
3596 int resInner = mInstaller.remove(packageName, user);
3597 if (resInner < 0) {
3598 res = resInner;
3599 }
3600 }
3601 return res;
3602 }
3603
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003604 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003605 int parseFlags, int scanMode, long currentTime, UserHandle user) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003606 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08003607 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
3608 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003609 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003610 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003611 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
3612 return null;
3613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003614 mScanningPath = scanFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003616 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3617 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
3618 }
3619
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003620 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003621 synchronized (mPackages) {
3622 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003623 Slog.w(TAG, "*************************************************");
3624 Slog.w(TAG, "Core android package being redefined. Skipping.");
3625 Slog.w(TAG, " file=" + mScanningPath);
3626 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003627 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3628 return null;
3629 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003631 // Set up information for our fall-back user intent resolution
3632 // activity.
3633 mPlatformPackage = pkg;
3634 pkg.mVersionCode = mSdkVersion;
3635 mAndroidApplication = pkg.applicationInfo;
3636 mResolveActivity.applicationInfo = mAndroidApplication;
3637 mResolveActivity.name = ResolverActivity.class.getName();
3638 mResolveActivity.packageName = mAndroidApplication.packageName;
3639 mResolveActivity.processName = mAndroidApplication.processName;
3640 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
3641 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
Joe Onorato646f46e2010-11-08 15:08:56 -08003642 mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 mResolveActivity.exported = true;
3644 mResolveActivity.enabled = true;
3645 mResolveInfo.activityInfo = mResolveActivity;
3646 mResolveInfo.priority = 0;
3647 mResolveInfo.preferredOrder = 0;
3648 mResolveInfo.match = 0;
3649 mResolveComponentName = new ComponentName(
3650 mAndroidApplication.packageName, mResolveActivity.name);
3651 }
3652 }
3653
Kenny Root4dfe6ff2011-02-23 17:00:43 -08003654 if (DEBUG_PACKAGE_SCANNING) {
3655 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
3656 Log.d(TAG, "Scanning package " + pkg.packageName);
3657 }
3658
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003659 if (mPackages.containsKey(pkg.packageName)
3660 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003661 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662 + " already installed. Skipping duplicate.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003663 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3664 return null;
3665 }
3666
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003667 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003668 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
3669 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003671 SharedUserSetting suid = null;
3672 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003673
Kenny Root502e9a42011-01-10 13:48:15 -08003674 if (!isSystemApp(pkg)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003675 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08003676 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003677 pkg.mRealPackage = null;
3678 pkg.mAdoptPermissions = null;
3679 }
Kenny Root502e9a42011-01-10 13:48:15 -08003680
Kenny Root447106f2011-03-23 11:00:15 -07003681 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003682 synchronized (mPackages) {
3683 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07003684 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
3685 if (mTmpSharedLibraries == null ||
3686 mTmpSharedLibraries.length < mSharedLibraries.size()) {
3687 mTmpSharedLibraries = new String[mSharedLibraries.size()];
3688 }
3689 int num = 0;
3690 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
3691 for (int i=0; i<N; i++) {
Kenny Root447106f2011-03-23 11:00:15 -07003692 final String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003693 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003694 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003695 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07003696 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003697 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
3698 return null;
3699 }
Dianne Hackborn49237342009-08-27 20:08:01 -07003700 mTmpSharedLibraries[num] = file;
3701 num++;
3702 }
3703 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
3704 for (int i=0; i<N; i++) {
Kenny Root447106f2011-03-23 11:00:15 -07003705 final String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
Dianne Hackborn49237342009-08-27 20:08:01 -07003706 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003707 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07003708 + " desires unavailable shared library "
3709 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
3710 } else {
3711 mTmpSharedLibraries[num] = file;
3712 num++;
3713 }
3714 }
3715 if (num > 0) {
3716 pkg.usesLibraryFiles = new String[num];
3717 System.arraycopy(mTmpSharedLibraries, 0,
3718 pkg.usesLibraryFiles, 0, num);
3719 }
Kenny Root1683afa2011-01-07 14:27:50 -08003720 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722 if (pkg.mSharedUserId != null) {
Kenny Root447106f2011-03-23 11:00:15 -07003723 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 pkg.applicationInfo.flags, true);
3725 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003726 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003727 + " for shared user failed");
3728 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3729 return null;
3730 }
Kenny Root4dfe6ff2011-02-23 17:00:43 -08003731 if (DEBUG_PACKAGE_SCANNING) {
3732 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
3733 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
3734 + "): packages=" + suid.packages);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 }
3736 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003737
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003738 // Check if we are renaming from an original package name.
3739 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003740 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08003741 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003742 // This package may need to be renamed to a previously
3743 // installed name. Let's check on that...
Kenny Root447106f2011-03-23 11:00:15 -07003744 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08003745 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003746 // This package had originally been installed as the
3747 // original name, and we have already taken care of
3748 // transitioning to the new one. Just update the new
3749 // one to continue using the old name.
3750 realName = pkg.mRealPackage;
3751 if (!pkg.packageName.equals(renamed)) {
3752 // Callers into this function may have already taken
3753 // care of renaming the package; only do it here if
3754 // it is not already done.
3755 pkg.setPackageName(renamed);
3756 }
3757
Dianne Hackbornc1552392010-03-03 16:19:01 -08003758 } else {
3759 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
Kenny Root447106f2011-03-23 11:00:15 -07003760 if ((origPackage = mSettings.peekPackageLPr(
Dianne Hackbornc1552392010-03-03 16:19:01 -08003761 pkg.mOriginalPackages.get(i))) != null) {
3762 // We do have the package already installed under its
3763 // original name... should we use it?
Kenny Root447106f2011-03-23 11:00:15 -07003764 if (!verifyPackageUpdateLPr(origPackage, pkg)) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08003765 // New package is not compatible with original.
3766 origPackage = null;
3767 continue;
3768 } else if (origPackage.sharedUser != null) {
3769 // Make sure uid is compatible between packages.
3770 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003771 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003772 + " to " + pkg.packageName + ": old uid "
3773 + origPackage.sharedUser.name
3774 + " differs from " + pkg.mSharedUserId);
3775 origPackage = null;
3776 continue;
3777 }
3778 } else {
3779 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3780 + pkg.packageName + " to old name " + origPackage.name);
3781 }
3782 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003783 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003784 }
3785 }
3786 }
3787
3788 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003789 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003790 + " was transferred to another, but its .apk remains");
3791 }
3792
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003793 // Just create the setting, don't add it yet. For already existing packages
3794 // the PkgSetting exists already and doesn't have to be created.
Kenny Root447106f2011-03-23 11:00:15 -07003795 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07003796 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003797 pkg.applicationInfo.flags, user, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003798 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003799 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003800 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3801 return null;
3802 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003803
3804 if (pkgSetting.origPackage != null) {
3805 // If we are first transitioning from an original package,
3806 // fix up the new package's name now. We need to do this after
3807 // looking up the package under its new name, so getPackageLP
3808 // can take care of fiddling things correctly.
3809 pkg.setPackageName(origPackage.name);
3810
3811 // File a report about this.
3812 String msg = "New package " + pkgSetting.realName
3813 + " renamed to replace old package " + pkgSetting.name;
3814 reportSettingsProblem(Log.WARN, msg);
3815
3816 // Make a note of it.
3817 mTransferedPackages.add(origPackage.name);
3818
3819 // No longer need to retain this.
3820 pkgSetting.origPackage = null;
3821 }
3822
3823 if (realName != null) {
3824 // Make a note of it.
3825 mTransferedPackages.add(pkg.packageName);
3826 }
3827
Kenny Rootc52d6fd2012-05-07 23:04:52 -07003828 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003829 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3830 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003831
Amith Yamasani13593602012-03-22 16:16:17 -07003832 pkg.applicationInfo.uid = pkgSetting.appId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003834
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003835 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003836 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 return null;
3838 }
3839 // The signature has changed, but this package is in the system
3840 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003841 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842 // However... if this package is part of a shared user, but it
3843 // doesn't match the signature of the shared user, let's fail.
3844 // What this means is that you can't change the signatures
3845 // associated with an overall shared user, which doesn't seem all
3846 // that unreasonable.
3847 if (pkgSetting.sharedUser != null) {
Kenny Root447106f2011-03-23 11:00:15 -07003848 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003849 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3850 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3852 return null;
3853 }
3854 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003855 // File a report about this.
3856 String msg = "System package " + pkg.packageName
3857 + " signature changed; retaining data.";
3858 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003860
The Android Open Source Project10592532009-03-18 17:39:46 -07003861 // Verify that this new package doesn't have any content providers
3862 // that conflict with existing packages. Only do this if the
3863 // package isn't already installed, since we don't want to break
3864 // things that are installed.
3865 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
Kenny Root62cc6902011-02-23 16:49:21 -08003866 final int N = pkg.providers.size();
The Android Open Source Project10592532009-03-18 17:39:46 -07003867 int i;
3868 for (i=0; i<N; i++) {
3869 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003870 if (p.info.authority != null) {
3871 String names[] = p.info.authority.split(";");
3872 for (int j = 0; j < names.length; j++) {
3873 if (mProviders.containsKey(names[j])) {
3874 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003875 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003876 " (in package " + pkg.applicationInfo.packageName +
3877 ") is already used by "
3878 + ((other != null && other.getComponentName() != null)
3879 ? other.getComponentName().getPackageName() : "?"));
3880 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3881 return null;
3882 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003883 }
3884 }
3885 }
3886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003887
Kenny Root447106f2011-03-23 11:00:15 -07003888 if (pkg.mAdoptPermissions != null) {
3889 // This package wants to adopt ownership of permissions from
3890 // another package.
3891 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
3892 final String origName = pkg.mAdoptPermissions.get(i);
3893 final PackageSetting orig = mSettings.peekPackageLPr(origName);
3894 if (orig != null) {
3895 if (verifyPackageUpdateLPr(orig, pkg)) {
3896 Slog.i(TAG, "Adopting permissions from " + origName + " to "
3897 + pkg.packageName);
3898 mSettings.transferPermissionsLPw(origName, pkg.packageName);
3899 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003900 }
3901 }
3902 }
3903 }
Kenny Root447106f2011-03-23 11:00:15 -07003904
3905 final String pkgName = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003906
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003907 final long scanFileTime = scanFile.lastModified();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003909 pkg.applicationInfo.processName = fixProcessName(
3910 pkg.applicationInfo.packageName,
3911 pkg.applicationInfo.processName,
3912 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003913
3914 File dataPath;
3915 if (mPlatformPackage == pkg) {
3916 // The system package is special.
3917 dataPath = new File (Environment.getDataDirectory(), "system");
3918 pkg.applicationInfo.dataDir = dataPath.getPath();
3919 } else {
3920 // This is a normal package, need to make its data directory.
Amith Yamasani0b285492011-04-14 17:35:23 -07003921 dataPath = getDataPathForPackage(pkg.packageName, 0);
Dianne Hackbornd0c5f512012-06-07 16:53:59 -07003922
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003923 boolean uidError = false;
Dianne Hackbornd0c5f512012-06-07 16:53:59 -07003924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 if (dataPath.exists()) {
Kenny Root786cbca2012-08-16 11:10:58 -07003926 int currentUid = 0;
3927 try {
3928 StructStat stat = Libcore.os.stat(dataPath.getPath());
3929 currentUid = stat.st_uid;
3930 } catch (ErrnoException e) {
3931 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
3932 }
Kenny Root85387d72010-08-26 10:13:11 -07003933
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003934 // If we have mismatched owners for the data path, we have a problem.
Kenny Root786cbca2012-08-16 11:10:58 -07003935 if (currentUid != pkg.applicationInfo.uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 boolean recovered = false;
Kenny Root786cbca2012-08-16 11:10:58 -07003937 if (currentUid == 0) {
Dianne Hackbornd0c5f512012-06-07 16:53:59 -07003938 // The directory somehow became owned by root. Wow.
3939 // This is probably because the system was stopped while
3940 // installd was in the middle of messing with its libs
3941 // directory. Ask installd to fix that.
3942 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
3943 pkg.applicationInfo.uid);
3944 if (ret >= 0) {
3945 recovered = true;
3946 String msg = "Package " + pkg.packageName
3947 + " unexpectedly changed to uid 0; recovered to " +
3948 + pkg.applicationInfo.uid;
3949 reportSettingsProblem(Log.WARN, msg);
3950 }
3951 }
3952 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
3953 || (scanMode&SCAN_BOOTING) != 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 // If this is a system app, we can at least delete its
3955 // current data so the application will still work.
Dianne Hackborn4428e172012-08-24 17:43:05 -07003956 int ret = removeDataDirsLI(pkgName);
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003957 if (ret >= 0) {
3958 // TODO: Kill the processes first
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003959 // Old data gone!
Dianne Hackbornd0c5f512012-06-07 16:53:59 -07003960 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
3961 ? "System package " : "Third party package ";
3962 String msg = prefix + pkg.packageName
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003963 + " has changed from uid: "
Kenny Root786cbca2012-08-16 11:10:58 -07003964 + currentUid + " to "
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003965 + pkg.applicationInfo.uid + "; old data erased";
3966 reportSettingsProblem(Log.WARN, msg);
3967 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003968
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003969 // And now re-install the app.
Dianne Hackborn4428e172012-08-24 17:43:05 -07003970 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid);
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003971 if (ret == -1) {
3972 // Ack should not happen!
Dianne Hackbornd0c5f512012-06-07 16:53:59 -07003973 msg = prefix + pkg.packageName
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003974 + " could not have data directory re-created after delete.";
3975 reportSettingsProblem(Log.WARN, msg);
3976 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3977 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 if (!recovered) {
3981 mHasSystemUidErrors = true;
3982 }
Dianne Hackbornd0c5f512012-06-07 16:53:59 -07003983 } else if (!recovered) {
3984 // If we allow this install to proceed, we will be broken.
3985 // Abort, abort!
3986 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
3987 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003988 }
3989 if (!recovered) {
3990 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3991 + pkg.applicationInfo.uid + "/fs_"
Kenny Root786cbca2012-08-16 11:10:58 -07003992 + currentUid;
Kenny Root85387d72010-08-26 10:13:11 -07003993 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003994 String msg = "Package " + pkg.packageName
3995 + " has mismatched uid: "
Kenny Root786cbca2012-08-16 11:10:58 -07003996 + currentUid + " on disk, "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 + pkg.applicationInfo.uid + " in settings";
Kenny Root447106f2011-03-23 11:00:15 -07003998 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08004000 mSettings.mReadMessages.append(msg);
4001 mSettings.mReadMessages.append('\n');
4002 uidError = true;
4003 if (!pkgSetting.uidError) {
4004 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 }
4007 }
4008 }
4009 pkg.applicationInfo.dataDir = dataPath.getPath();
4010 } else {
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004011 if (DEBUG_PACKAGE_SCANNING) {
4012 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4013 Log.v(TAG, "Want this data dir: " + dataPath);
4014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004015 //invoke installer to do the actual installation
Dianne Hackborn4428e172012-08-24 17:43:05 -07004016 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid);
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004017 if (ret < 0) {
4018 // Error from installer
4019 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4020 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004023 if (dataPath.exists()) {
4024 pkg.applicationInfo.dataDir = dataPath.getPath();
4025 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004026 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 pkg.applicationInfo.dataDir = null;
4028 }
4029 }
Kenny Root85387d72010-08-26 10:13:11 -07004030
4031 /*
4032 * Set the data dir to the default "/data/data/<package name>/lib"
4033 * if we got here without anyone telling us different (e.g., apps
4034 * stored on SD card have their native libraries stored in the ASEC
4035 * container with the APK).
Kenny Root806cc132010-09-12 08:34:19 -07004036 *
4037 * This happens during an upgrade from a package settings file that
4038 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07004039 */
Kenny Rootbd135c12010-10-05 12:26:27 -07004040 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
4041 if (pkgSetting.nativeLibraryPathString == null) {
4042 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
4043 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
4044 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
4045 } else {
4046 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
4047 }
Kenny Root85387d72010-08-26 10:13:11 -07004048 }
4049
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08004050 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 }
4052
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004053 String path = scanFile.getPath();
4054 /* Note: We don't want to unpack the native binaries for
4055 * system applications, unless they have been updated
4056 * (the binaries are already under /system/lib).
4057 * Also, don't unpack libs for apps on the external card
4058 * since they should have their libraries in the ASEC
4059 * container already.
4060 *
4061 * In other words, we're going to unpack the binaries
4062 * only for non-system apps and system app upgrades.
4063 */
4064 if (pkg.applicationInfo.nativeLibraryDir != null) {
4065 try {
4066 final File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
Kenny Root5832ead2011-08-02 15:47:08 -07004067 final String dataPathString = dataPath.getCanonicalPath();
Kenny Roote68d58a2010-10-18 16:08:54 -07004068
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004069 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4070 /*
4071 * Upgrading from a previous version of the OS sometimes
4072 * leaves native libraries in the /data/data/<app>/lib
4073 * directory for system apps even when they shouldn't be.
4074 * Recent changes in the JNI library search path
4075 * necessitates we remove those to match previous behavior.
4076 */
4077 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
4078 Log.i(TAG, "removed obsolete native libraries for system package "
4079 + path);
Kenny Root831baa22010-10-05 12:29:25 -07004080 }
Kenny Root5832ead2011-08-02 15:47:08 -07004081 } else if (nativeLibraryDir.getParentFile().getCanonicalPath()
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004082 .equals(dataPathString)) {
4083 /*
Kenny Root66269ea2011-07-12 14:14:01 -07004084 * Make sure the native library dir isn't a symlink to
4085 * something. If it is, ask installd to remove it and create
4086 * a directory so we can copy to it afterwards.
4087 */
4088 boolean isSymLink;
4089 try {
4090 isSymLink = S_ISLNK(Libcore.os.lstat(nativeLibraryDir.getPath()).st_mode);
4091 } catch (ErrnoException e) {
4092 // This shouldn't happen, but we'll fail-safe.
4093 isSymLink = true;
4094 }
4095 if (isSymLink) {
4096 mInstaller.unlinkNativeLibraryDirectory(dataPathString);
4097 }
4098
4099 /*
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004100 * If this is an internal application or our
4101 * nativeLibraryPath points to our data directory, unpack
Kenny Root66269ea2011-07-12 14:14:01 -07004102 * the libraries if necessary.
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004103 */
Kenny Root66269ea2011-07-12 14:14:01 -07004104 NativeLibraryHelper.copyNativeBinariesIfNeededLI(scanFile, nativeLibraryDir);
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004105 } else {
4106 Slog.i(TAG, "Linking native library dir for " + path);
4107 mInstaller.linkNativeLibraryDirectory(dataPathString,
4108 pkg.applicationInfo.nativeLibraryDir);
Kenny Root831baa22010-10-05 12:29:25 -07004109 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004110 } catch (IOException ioe) {
4111 Log.e(TAG, "Unable to get canonical file " + ioe.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004112 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004113 }
4114 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004115
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004116 if ((scanMode&SCAN_NO_DEX) == 0) {
Dianne Hackborn661cd522011-08-22 00:26:20 -07004117 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0)
4118 == DEX_OPT_FAILED) {
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004119 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
4120 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 }
4122 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004124 if (mFactoryTest && pkg.requestedPermissions.contains(
4125 android.Manifest.permission.FACTORY_TEST)) {
4126 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
4127 }
4128
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004129 // Request the ActivityManager to kill the process(only for existing packages)
4130 // so that we do not end up in a confused state while the user is still using the older
4131 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004132 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004133 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004134 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004135 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004136
Kenny Root447106f2011-03-23 11:00:15 -07004137 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004138 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004139 // We don't expect installation to fail beyond this point,
4140 if ((scanMode&SCAN_MONITOR) != 0) {
4141 mAppDirs.put(pkg.mPath, pkg);
4142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143 // Add the new setting to mSettings
Kenny Root447106f2011-03-23 11:00:15 -07004144 mSettings.insertPackageSettingLPw(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07004146 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004147 // Make sure we don't accidentally delete its data.
Dianne Hackborn7767eac2012-08-23 18:25:40 -07004148 for (int i=0; i<mSettings.mPackagesToBeCleaned.size(); i++) {
4149 mSettings.mPackagesToBeCleaned.valueAt(i).remove(pkgName);
4150 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004151
Dianne Hackborn78d6883692010-10-07 01:12:46 -07004152 // Take care of first install / last update times.
4153 if (currentTime != 0) {
4154 if (pkgSetting.firstInstallTime == 0) {
4155 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
4156 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
4157 pkgSetting.lastUpdateTime = currentTime;
4158 }
4159 } else if (pkgSetting.firstInstallTime == 0) {
4160 // We need *something*. Take time time stamp of the file.
4161 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
4162 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
4163 if (scanFileTime != pkgSetting.timeStamp) {
4164 // A package on the system image has changed; consider this
4165 // to be an update.
4166 pkgSetting.lastUpdateTime = scanFileTime;
4167 }
4168 }
4169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004170 int N = pkg.providers.size();
4171 StringBuilder r = null;
4172 int i;
4173 for (i=0; i<N; i++) {
4174 PackageParser.Provider p = pkg.providers.get(i);
4175 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
4176 p.info.processName, pkg.applicationInfo.uid);
4177 mProvidersByComponent.put(new ComponentName(p.info.packageName,
4178 p.info.name), p);
4179 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08004180 if (p.info.authority != null) {
4181 String names[] = p.info.authority.split(";");
4182 p.info.authority = null;
4183 for (int j = 0; j < names.length; j++) {
4184 if (j == 1 && p.syncable) {
4185 // We only want the first authority for a provider to possibly be
4186 // syncable, so if we already added this provider using a different
4187 // authority clear the syncable flag. We copy the provider before
4188 // changing it because the mProviders object contains a reference
4189 // to a provider that we don't want to change.
4190 // Only do this for the second authority since the resulting provider
4191 // object can be the same for all future authorities for this provider.
4192 p = new PackageParser.Provider(p);
4193 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08004195 if (!mProviders.containsKey(names[j])) {
4196 mProviders.put(names[j], p);
4197 if (p.info.authority == null) {
4198 p.info.authority = names[j];
4199 } else {
4200 p.info.authority = p.info.authority + ";" + names[j];
4201 }
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004202 if (DEBUG_PACKAGE_SCANNING) {
4203 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4204 Log.d(TAG, "Registered content provider: " + names[j]
4205 + ", className = " + p.info.name + ", isSyncable = "
4206 + p.info.isSyncable);
4207 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08004208 } else {
4209 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004210 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08004211 " (in package " + pkg.applicationInfo.packageName +
4212 "): name already used by "
4213 + ((other != null && other.getComponentName() != null)
4214 ? other.getComponentName().getPackageName() : "?"));
4215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216 }
4217 }
4218 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4219 if (r == null) {
4220 r = new StringBuilder(256);
4221 } else {
4222 r.append(' ');
4223 }
4224 r.append(p.info.name);
4225 }
4226 }
4227 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004228 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004229 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004231 N = pkg.services.size();
4232 r = null;
4233 for (i=0; i<N; i++) {
4234 PackageParser.Service s = pkg.services.get(i);
4235 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
4236 s.info.processName, pkg.applicationInfo.uid);
4237 mServices.addService(s);
4238 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4239 if (r == null) {
4240 r = new StringBuilder(256);
4241 } else {
4242 r.append(' ');
4243 }
4244 r.append(s.info.name);
4245 }
4246 }
4247 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004248 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004249 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004251 N = pkg.receivers.size();
4252 r = null;
4253 for (i=0; i<N; i++) {
4254 PackageParser.Activity a = pkg.receivers.get(i);
4255 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
4256 a.info.processName, pkg.applicationInfo.uid);
4257 mReceivers.addActivity(a, "receiver");
4258 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4259 if (r == null) {
4260 r = new StringBuilder(256);
4261 } else {
4262 r.append(' ');
4263 }
4264 r.append(a.info.name);
4265 }
4266 }
4267 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004268 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004269 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271 N = pkg.activities.size();
4272 r = null;
4273 for (i=0; i<N; i++) {
4274 PackageParser.Activity a = pkg.activities.get(i);
4275 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
4276 a.info.processName, pkg.applicationInfo.uid);
4277 mActivities.addActivity(a, "activity");
4278 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4279 if (r == null) {
4280 r = new StringBuilder(256);
4281 } else {
4282 r.append(' ');
4283 }
4284 r.append(a.info.name);
4285 }
4286 }
4287 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004288 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 N = pkg.permissionGroups.size();
4292 r = null;
4293 for (i=0; i<N; i++) {
4294 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
4295 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
4296 if (cur == null) {
4297 mPermissionGroups.put(pg.info.name, pg);
4298 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4299 if (r == null) {
4300 r = new StringBuilder(256);
4301 } else {
4302 r.append(' ');
4303 }
4304 r.append(pg.info.name);
4305 }
4306 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004307 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 + pg.info.packageName + " ignored: original from "
4309 + cur.info.packageName);
4310 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4311 if (r == null) {
4312 r = new StringBuilder(256);
4313 } else {
4314 r.append(' ');
4315 }
4316 r.append("DUP:");
4317 r.append(pg.info.name);
4318 }
4319 }
4320 }
4321 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004322 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004323 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325 N = pkg.permissions.size();
4326 r = null;
4327 for (i=0; i<N; i++) {
4328 PackageParser.Permission p = pkg.permissions.get(i);
4329 HashMap<String, BasePermission> permissionMap =
4330 p.tree ? mSettings.mPermissionTrees
4331 : mSettings.mPermissions;
4332 p.group = mPermissionGroups.get(p.info.group);
4333 if (p.info.group == null || p.group != null) {
4334 BasePermission bp = permissionMap.get(p.info.name);
4335 if (bp == null) {
4336 bp = new BasePermission(p.info.name, p.info.packageName,
4337 BasePermission.TYPE_NORMAL);
4338 permissionMap.put(p.info.name, bp);
4339 }
4340 if (bp.perm == null) {
4341 if (bp.sourcePackage == null
4342 || bp.sourcePackage.equals(p.info.packageName)) {
4343 BasePermission tree = findPermissionTreeLP(p.info.name);
4344 if (tree == null
4345 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004346 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004347 bp.perm = p;
4348 bp.uid = pkg.applicationInfo.uid;
4349 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4350 if (r == null) {
4351 r = new StringBuilder(256);
4352 } else {
4353 r.append(' ');
4354 }
4355 r.append(p.info.name);
4356 }
4357 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004358 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004359 + p.info.packageName + " ignored: base tree "
4360 + tree.name + " is from package "
4361 + tree.sourcePackage);
4362 }
4363 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004364 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004365 + p.info.packageName + " ignored: original from "
4366 + bp.sourcePackage);
4367 }
4368 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4369 if (r == null) {
4370 r = new StringBuilder(256);
4371 } else {
4372 r.append(' ');
4373 }
4374 r.append("DUP:");
4375 r.append(p.info.name);
4376 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004377 if (bp.perm == p) {
4378 bp.protectionLevel = p.info.protectionLevel;
4379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004380 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004381 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004382 + p.info.packageName + " ignored: no group "
4383 + p.group);
4384 }
4385 }
4386 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004387 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004388 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004390 N = pkg.instrumentation.size();
4391 r = null;
4392 for (i=0; i<N; i++) {
4393 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
4394 a.info.packageName = pkg.applicationInfo.packageName;
4395 a.info.sourceDir = pkg.applicationInfo.sourceDir;
4396 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
4397 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07004398 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004399 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004400 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4401 if (r == null) {
4402 r = new StringBuilder(256);
4403 } else {
4404 r.append(' ');
4405 }
4406 r.append(a.info.name);
4407 }
4408 }
4409 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004410 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004411 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004412
Dianne Hackborn854060af2009-07-09 18:14:31 -07004413 if (pkg.protectedBroadcasts != null) {
4414 N = pkg.protectedBroadcasts.size();
4415 for (i=0; i<N; i++) {
4416 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
4417 }
4418 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004420 pkgSetting.setTimeStamp(scanFileTime);
4421 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004423 return pkg;
4424 }
4425
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004426 private void killApplication(String pkgName, int uid) {
4427 // Request the ActivityManager to kill the process(only for existing packages)
4428 // so that we do not end up in a confused state while the user is still using the older
4429 // version of the application while the new one gets installed.
4430 IActivityManager am = ActivityManagerNative.getDefault();
4431 if (am != null) {
4432 try {
4433 am.killApplicationWithUid(pkgName, uid);
4434 } catch (RemoteException e) {
4435 }
4436 }
4437 }
4438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004439 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004440 if (DEBUG_INSTALL) {
4441 if (chatty)
4442 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
4443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004444
Kenny Root447106f2011-03-23 11:00:15 -07004445 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004446 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004447 mPackages.remove(pkg.applicationInfo.packageName);
4448 if (pkg.mPath != null) {
4449 mAppDirs.remove(pkg.mPath);
4450 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004452 int N = pkg.providers.size();
4453 StringBuilder r = null;
4454 int i;
4455 for (i=0; i<N; i++) {
4456 PackageParser.Provider p = pkg.providers.get(i);
4457 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
4458 p.info.name));
4459 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004461 /* The is another ContentProvider with this authority when
4462 * this app was installed so this authority is null,
4463 * Ignore it as we don't have to unregister the provider.
4464 */
4465 continue;
4466 }
4467 String names[] = p.info.authority.split(";");
4468 for (int j = 0; j < names.length; j++) {
4469 if (mProviders.get(names[j]) == p) {
4470 mProviders.remove(names[j]);
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004471 if (DEBUG_REMOVE) {
4472 if (chatty)
4473 Log.d(TAG, "Unregistered content provider: " + names[j]
4474 + ", className = " + p.info.name + ", isSyncable = "
4475 + p.info.isSyncable);
4476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004477 }
4478 }
4479 if (chatty) {
4480 if (r == null) {
4481 r = new StringBuilder(256);
4482 } else {
4483 r.append(' ');
4484 }
4485 r.append(p.info.name);
4486 }
4487 }
4488 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004489 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004490 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004492 N = pkg.services.size();
4493 r = null;
4494 for (i=0; i<N; i++) {
4495 PackageParser.Service s = pkg.services.get(i);
4496 mServices.removeService(s);
4497 if (chatty) {
4498 if (r == null) {
4499 r = new StringBuilder(256);
4500 } else {
4501 r.append(' ');
4502 }
4503 r.append(s.info.name);
4504 }
4505 }
4506 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004507 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004508 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004510 N = pkg.receivers.size();
4511 r = null;
4512 for (i=0; i<N; i++) {
4513 PackageParser.Activity a = pkg.receivers.get(i);
4514 mReceivers.removeActivity(a, "receiver");
4515 if (chatty) {
4516 if (r == null) {
4517 r = new StringBuilder(256);
4518 } else {
4519 r.append(' ');
4520 }
4521 r.append(a.info.name);
4522 }
4523 }
4524 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004525 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004526 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004528 N = pkg.activities.size();
4529 r = null;
4530 for (i=0; i<N; i++) {
4531 PackageParser.Activity a = pkg.activities.get(i);
4532 mActivities.removeActivity(a, "activity");
4533 if (chatty) {
4534 if (r == null) {
4535 r = new StringBuilder(256);
4536 } else {
4537 r.append(' ');
4538 }
4539 r.append(a.info.name);
4540 }
4541 }
4542 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004543 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004544 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004546 N = pkg.permissions.size();
4547 r = null;
4548 for (i=0; i<N; i++) {
4549 PackageParser.Permission p = pkg.permissions.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004550 BasePermission bp = mSettings.mPermissions.get(p.info.name);
4551 if (bp == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004552 bp = mSettings.mPermissionTrees.get(p.info.name);
4553 }
4554 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004555 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004556 if (chatty) {
4557 if (r == null) {
4558 r = new StringBuilder(256);
4559 } else {
4560 r.append(' ');
4561 }
4562 r.append(p.info.name);
4563 }
4564 }
4565 }
4566 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004567 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004568 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004570 N = pkg.instrumentation.size();
4571 r = null;
4572 for (i=0; i<N; i++) {
4573 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004574 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004575 if (chatty) {
4576 if (r == null) {
4577 r = new StringBuilder(256);
4578 } else {
4579 r.append(' ');
4580 }
4581 r.append(a.info.name);
4582 }
4583 }
4584 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004585 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004586 }
4587 }
4588 }
4589
4590 private static final boolean isPackageFilename(String name) {
4591 return name != null && name.endsWith(".apk");
4592 }
4593
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004594 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
4595 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
4596 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
4597 return true;
4598 }
4599 }
4600 return false;
4601 }
Dianne Hackborne639da72012-02-21 15:11:13 -08004602
4603 static final int UPDATE_PERMISSIONS_ALL = 1<<0;
4604 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
4605 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
4606
Kenny Root447106f2011-03-23 11:00:15 -07004607 private void updatePermissionsLPw(String changingPkg,
Dianne Hackborne639da72012-02-21 15:11:13 -08004608 PackageParser.Package pkgInfo, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004609 // Make sure there are no dangling permission trees.
Kenny Root447106f2011-03-23 11:00:15 -07004610 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004611 while (it.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07004612 final BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004613 if (bp.packageSetting == null) {
4614 // We may not yet have parsed the package, so just see if
4615 // we still know about its settings.
4616 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4617 }
4618 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004619 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004620 + " from package " + bp.sourcePackage);
4621 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004622 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4623 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4624 Slog.i(TAG, "Removing old permission tree: " + bp.name
4625 + " from package " + bp.sourcePackage);
Dianne Hackborne639da72012-02-21 15:11:13 -08004626 flags |= UPDATE_PERMISSIONS_ALL;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004627 it.remove();
4628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004629 }
4630 }
4631
4632 // Make sure all dynamic permissions have been assigned to a package,
4633 // and make sure there are no dangling permissions.
4634 it = mSettings.mPermissions.values().iterator();
4635 while (it.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07004636 final BasePermission bp = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004637 if (bp.type == BasePermission.TYPE_DYNAMIC) {
4638 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
4639 + bp.name + " pkg=" + bp.sourcePackage
4640 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004641 if (bp.packageSetting == null && bp.pendingInfo != null) {
Kenny Root447106f2011-03-23 11:00:15 -07004642 final BasePermission tree = findPermissionTreeLP(bp.name);
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07004643 if (tree != null && tree.perm != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004644 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004645 bp.perm = new PackageParser.Permission(tree.perm.owner,
4646 new PermissionInfo(bp.pendingInfo));
4647 bp.perm.info.packageName = tree.perm.info.packageName;
4648 bp.perm.info.name = bp.name;
4649 bp.uid = tree.uid;
4650 }
4651 }
4652 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004653 if (bp.packageSetting == null) {
4654 // We may not yet have parsed the package, so just see if
4655 // we still know about its settings.
4656 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4657 }
4658 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004659 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004660 + " from package " + bp.sourcePackage);
4661 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004662 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4663 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4664 Slog.i(TAG, "Removing old permission: " + bp.name
4665 + " from package " + bp.sourcePackage);
Dianne Hackborne639da72012-02-21 15:11:13 -08004666 flags |= UPDATE_PERMISSIONS_ALL;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004667 it.remove();
4668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004669 }
4670 }
4671
4672 // Now update the permissions for all packages, in particular
4673 // replace the granted permissions of the system packages.
Dianne Hackborne639da72012-02-21 15:11:13 -08004674 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004675 for (PackageParser.Package pkg : mPackages.values()) {
4676 if (pkg != pkgInfo) {
Dianne Hackborne639da72012-02-21 15:11:13 -08004677 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004678 }
4679 }
4680 }
4681
4682 if (pkgInfo != null) {
Dianne Hackborne639da72012-02-21 15:11:13 -08004683 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004684 }
4685 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004686
Kenny Root447106f2011-03-23 11:00:15 -07004687 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
4688 final PackageSetting ps = (PackageSetting) pkg.mExtras;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004689 if (ps == null) {
4690 return;
4691 }
4692 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackborne639da72012-02-21 15:11:13 -08004693 HashSet<String> origPermissions = gp.grantedPermissions;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004694 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004696 if (replace) {
4697 ps.permissionsFixed = false;
4698 if (gp == ps) {
Dianne Hackborne639da72012-02-21 15:11:13 -08004699 origPermissions = new HashSet<String>(gp.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004700 gp.grantedPermissions.clear();
4701 gp.gids = mGlobalGids;
4702 }
4703 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004705 if (gp.gids == null) {
4706 gp.gids = mGlobalGids;
4707 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004709 final int N = pkg.requestedPermissions.size();
4710 for (int i=0; i<N; i++) {
Kenny Root447106f2011-03-23 11:00:15 -07004711 final String name = pkg.requestedPermissions.get(i);
Dianne Hackborne639da72012-02-21 15:11:13 -08004712 //final boolean required = pkg.requestedPermssionsRequired.get(i);
Kenny Root447106f2011-03-23 11:00:15 -07004713 final BasePermission bp = mSettings.mPermissions.get(name);
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004714 if (DEBUG_INSTALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004715 if (gp != ps) {
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004716 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004717 }
4718 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004719 if (bp != null && bp.packageSetting != null) {
4720 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004721 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004722 boolean allowedSig = false;
Dianne Hackborne639da72012-02-21 15:11:13 -08004723 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
4724 if (level == PermissionInfo.PROTECTION_NORMAL
4725 || level == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004726 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07004727 } else if (bp.packageSetting == null) {
4728 // This permission is invalid; skip it.
4729 allowed = false;
Dianne Hackborne639da72012-02-21 15:11:13 -08004730 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
Kenny Root447106f2011-03-23 11:00:15 -07004731 allowed = (compareSignatures(
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07004732 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004733 == PackageManager.SIGNATURE_MATCH)
Kenny Root447106f2011-03-23 11:00:15 -07004734 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004735 == PackageManager.SIGNATURE_MATCH);
Dianne Hackborne639da72012-02-21 15:11:13 -08004736 if (!allowed && (bp.protectionLevel
4737 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
Kenny Root85387d72010-08-26 10:13:11 -07004738 if (isSystemApp(pkg)) {
Dianne Hackborne639da72012-02-21 15:11:13 -08004739 // For updated system applications, a system permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004740 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07004741 if (isUpdatedSystemApp(pkg)) {
Kenny Root447106f2011-03-23 11:00:15 -07004742 final PackageSetting sysPs = mSettings
4743 .getDisabledSystemPkgLPr(pkg.packageName);
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07004744 final GrantedPermissions origGp = sysPs.sharedUser != null
4745 ? sysPs.sharedUser : sysPs;
4746 if (origGp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004747 allowed = true;
4748 } else {
4749 allowed = false;
4750 }
4751 } else {
4752 allowed = true;
4753 }
4754 }
4755 }
Dianne Hackborne639da72012-02-21 15:11:13 -08004756 if (!allowed && (bp.protectionLevel
4757 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
4758 // For development permissions, a development permission
4759 // is granted only if it was already granted.
4760 if (origPermissions.contains(perm)) {
4761 allowed = true;
4762 } else {
4763 allowed = false;
4764 }
4765 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004766 if (allowed) {
4767 allowedSig = true;
4768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004769 } else {
4770 allowed = false;
4771 }
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004772 if (DEBUG_INSTALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004773 if (gp != ps) {
4774 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4775 }
4776 }
4777 if (allowed) {
4778 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4779 && ps.permissionsFixed) {
4780 // If this is an existing, non-system package, then
4781 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004782 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004783 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004784 // Except... if this is a permission that was added
4785 // to the platform (note: need to only do this when
4786 // updating the platform).
4787 final int NP = PackageParser.NEW_PERMISSIONS.length;
4788 for (int ip=0; ip<NP; ip++) {
4789 final PackageParser.NewPermissionInfo npi
4790 = PackageParser.NEW_PERMISSIONS[ip];
4791 if (npi.name.equals(perm)
4792 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4793 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004794 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004795 + pkg.packageName);
4796 break;
4797 }
4798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004799 }
4800 }
4801 if (allowed) {
4802 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004803 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004804 gp.grantedPermissions.add(perm);
4805 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004806 } else if (!ps.haveGids) {
4807 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004808 }
4809 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004810 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004811 + " to package " + pkg.packageName
4812 + " because it was previously installed without");
4813 }
4814 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004815 if (gp.grantedPermissions.remove(perm)) {
4816 changedPermission = true;
4817 gp.gids = removeInts(gp.gids, bp.gids);
4818 Slog.i(TAG, "Un-granting permission " + perm
4819 + " from package " + pkg.packageName
4820 + " (protectionLevel=" + bp.protectionLevel
4821 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4822 + ")");
4823 } else {
4824 Slog.w(TAG, "Not granting permission " + perm
4825 + " to package " + pkg.packageName
4826 + " (protectionLevel=" + bp.protectionLevel
4827 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4828 + ")");
4829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004830 }
4831 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004832 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004833 + " in package " + pkg.packageName);
4834 }
4835 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004836
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004837 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004838 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4839 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004840 // This is the first that we have heard about this package, so the
4841 // permissions we have now selected are fixed until explicitly
4842 // changed.
4843 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004844 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004845 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004846 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004848 private final class ActivityIntentResolver
4849 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Kenny Root60f7ad82011-03-22 12:49:06 -07004850 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004851 boolean defaultOnly, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07004852 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004853 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Amith Yamasani483f3b02012-03-13 16:08:00 -07004854 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004855 }
4856
Amith Yamasani483f3b02012-03-13 16:08:00 -07004857 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
4858 int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07004859 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004860 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004861 return super.queryIntent(intent, resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004862 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004863 }
4864
Kenny Root60f7ad82011-03-22 12:49:06 -07004865 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004866 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07004867 if (!sUserManager.exists(userId)) return null;
Mihai Predaeae850c2009-05-13 10:13:48 +02004868 if (packageActivities == null) {
4869 return null;
4870 }
4871 mFlags = flags;
4872 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
Kenny Root62cc6902011-02-23 16:49:21 -08004873 final int N = packageActivities.size();
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07004874 ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
4875 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004876
4877 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004878 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004879 intentFilters = packageActivities.get(i).intents;
4880 if (intentFilters != null && intentFilters.size() > 0) {
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07004881 PackageParser.ActivityIntentInfo[] array =
4882 new PackageParser.ActivityIntentInfo[intentFilters.size()];
4883 intentFilters.toArray(array);
4884 listCut.add(array);
Mihai Predac3320db2009-05-18 20:15:32 +02004885 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004886 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07004887 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
Mihai Predaeae850c2009-05-13 10:13:48 +02004888 }
4889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004890 public final void addActivity(PackageParser.Activity a, String type) {
Kenny Root502e9a42011-01-10 13:48:15 -08004891 final boolean systemApp = isSystemApp(a.info.applicationInfo);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004892 mActivities.put(a.getComponentName(), a);
Kenny Root9718cf52011-02-23 16:45:26 -08004893 if (DEBUG_SHOW_INFO)
4894 Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004895 TAG, " " + type + " " +
4896 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
Kenny Root9718cf52011-02-23 16:45:26 -08004897 if (DEBUG_SHOW_INFO)
4898 Log.v(TAG, " Class=" + a.info.name);
Kenny Root62cc6902011-02-23 16:49:21 -08004899 final int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004900 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004901 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
Kenny Root502e9a42011-01-10 13:48:15 -08004902 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
4903 intent.setPriority(0);
4904 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
4905 + a.className + " with priority > 0, forcing to 0");
4906 }
Kenny Root9718cf52011-02-23 16:45:26 -08004907 if (DEBUG_SHOW_INFO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004908 Log.v(TAG, " IntentFilter:");
4909 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4910 }
4911 if (!intent.debugCheck()) {
4912 Log.w(TAG, "==> For Activity " + a.info.name);
4913 }
4914 addFilter(intent);
4915 }
4916 }
4917
4918 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004919 mActivities.remove(a.getComponentName());
Kenny Root9718cf52011-02-23 16:45:26 -08004920 if (DEBUG_SHOW_INFO) {
4921 Log.v(TAG, " " + type + " "
4922 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
4923 : a.info.name) + ":");
4924 Log.v(TAG, " Class=" + a.info.name);
4925 }
4926 final int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004927 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004928 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
Kenny Root9718cf52011-02-23 16:45:26 -08004929 if (DEBUG_SHOW_INFO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004930 Log.v(TAG, " IntentFilter:");
4931 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4932 }
4933 removeFilter(intent);
4934 }
4935 }
4936
4937 @Override
4938 protected boolean allowFilterResult(
4939 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4940 ActivityInfo filterAi = filter.activity.info;
4941 for (int i=dest.size()-1; i>=0; i--) {
4942 ActivityInfo destAi = dest.get(i).activityInfo;
4943 if (destAi.name == filterAi.name
4944 && destAi.packageName == filterAi.packageName) {
4945 return false;
4946 }
4947 }
4948 return true;
4949 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004951 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07004952 protected ActivityIntentInfo[] newArray(int size) {
4953 return new ActivityIntentInfo[size];
4954 }
4955
4956 @Override
Amith Yamasani483f3b02012-03-13 16:08:00 -07004957 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07004958 if (!sUserManager.exists(userId)) return true;
Dianne Hackborne7f97212011-02-24 14:40:20 -08004959 PackageParser.Package p = filter.activity.owner;
4960 if (p != null) {
4961 PackageSetting ps = (PackageSetting)p.mExtras;
4962 if (ps != null) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07004963 // System apps are never considered stopped for purposes of
4964 // filtering, because there may be no way for the user to
4965 // actually re-launch them.
Dianne Hackborn7767eac2012-08-23 18:25:40 -07004966 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4967 && ps.getStopped(userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08004968 }
4969 }
4970 return false;
4971 }
4972
4973 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004974 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4975 return info.activity.owner.packageName;
4976 }
4977
4978 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004979 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004980 int match, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07004981 if (!sUserManager.exists(userId)) return null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07004982 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004983 return null;
4984 }
4985 final PackageParser.Activity activity = info.activity;
4986 if (mSafeMode && (activity.info.applicationInfo.flags
4987 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4988 return null;
4989 }
Amith Yamasani13593602012-03-22 16:16:17 -07004990 PackageSetting ps = (PackageSetting) activity.owner.mExtras;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07004991 if (ps == null) {
4992 return null;
4993 }
4994 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
4995 ps.readUserState(userId), userId);
4996 if (ai == null) {
4997 return null;
4998 }
4999 final ResolveInfo res = new ResolveInfo();
5000 res.activityInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005001 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
5002 res.filter = info;
5003 }
5004 res.priority = info.getPriority();
5005 res.preferredOrder = activity.owner.mPreferredOrder;
5006 //System.out.println("Result: " + res.activityInfo.className +
5007 // " = " + res.priority);
5008 res.match = match;
5009 res.isDefault = info.hasDefault;
5010 res.labelRes = info.labelRes;
5011 res.nonLocalizedLabel = info.nonLocalizedLabel;
5012 res.icon = info.icon;
Dianne Hackbornd99b2932011-08-18 14:39:58 -07005013 res.system = isSystemApp(res.activityInfo.applicationInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005014 return res;
5015 }
5016
5017 @Override
5018 protected void sortResults(List<ResolveInfo> results) {
5019 Collections.sort(results, mResolvePrioritySorter);
5020 }
5021
5022 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005023 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005024 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005025 out.print(prefix); out.print(
5026 Integer.toHexString(System.identityHashCode(filter.activity)));
5027 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005028 out.print(filter.activity.getComponentShortName());
5029 out.print(" filter ");
5030 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005031 }
5032
5033// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
5034// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
5035// final List<ResolveInfo> retList = Lists.newArrayList();
5036// while (i.hasNext()) {
5037// final ResolveInfo resolveInfo = i.next();
5038// if (isEnabledLP(resolveInfo.activityInfo)) {
5039// retList.add(resolveInfo);
5040// }
5041// }
5042// return retList;
5043// }
5044
5045 // Keys are String (activity class name), values are Activity.
5046 private final HashMap<ComponentName, PackageParser.Activity> mActivities
5047 = new HashMap<ComponentName, PackageParser.Activity>();
5048 private int mFlags;
5049 }
5050
5051 private final class ServiceIntentResolver
5052 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Kenny Root60f7ad82011-03-22 12:49:06 -07005053 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005054 boolean defaultOnly, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005055 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005056 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005057 }
5058
Amith Yamasani483f3b02012-03-13 16:08:00 -07005059 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
5060 int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005061 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005062 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02005063 return super.queryIntent(intent, resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005064 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005065 }
5066
Kenny Root60f7ad82011-03-22 12:49:06 -07005067 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005068 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005069 if (!sUserManager.exists(userId)) return null;
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07005070 if (packageServices == null) {
5071 return null;
5072 }
5073 mFlags = flags;
5074 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
Kenny Root62cc6902011-02-23 16:49:21 -08005075 final int N = packageServices.size();
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07005076 ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
5077 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07005078
5079 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
5080 for (int i = 0; i < N; ++i) {
5081 intentFilters = packageServices.get(i).intents;
5082 if (intentFilters != null && intentFilters.size() > 0) {
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07005083 PackageParser.ServiceIntentInfo[] array =
5084 new PackageParser.ServiceIntentInfo[intentFilters.size()];
5085 intentFilters.toArray(array);
5086 listCut.add(array);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07005087 }
5088 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07005089 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07005090 }
5091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005092 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005093 mServices.put(s.getComponentName(), s);
Kenny Root9718cf52011-02-23 16:45:26 -08005094 if (DEBUG_SHOW_INFO) {
5095 Log.v(TAG, " "
5096 + (s.info.nonLocalizedLabel != null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005097 ? s.info.nonLocalizedLabel : s.info.name) + ":");
Kenny Root9718cf52011-02-23 16:45:26 -08005098 Log.v(TAG, " Class=" + s.info.name);
5099 }
5100 final int NI = s.intents.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005101 int j;
5102 for (j=0; j<NI; j++) {
5103 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
Kenny Root9718cf52011-02-23 16:45:26 -08005104 if (DEBUG_SHOW_INFO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005105 Log.v(TAG, " IntentFilter:");
5106 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
5107 }
5108 if (!intent.debugCheck()) {
5109 Log.w(TAG, "==> For Service " + s.info.name);
5110 }
5111 addFilter(intent);
5112 }
5113 }
5114
5115 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005116 mServices.remove(s.getComponentName());
Kenny Root9718cf52011-02-23 16:45:26 -08005117 if (DEBUG_SHOW_INFO) {
5118 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005119 ? s.info.nonLocalizedLabel : s.info.name) + ":");
Kenny Root9718cf52011-02-23 16:45:26 -08005120 Log.v(TAG, " Class=" + s.info.name);
5121 }
5122 final int NI = s.intents.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005123 int j;
5124 for (j=0; j<NI; j++) {
5125 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
Kenny Root9718cf52011-02-23 16:45:26 -08005126 if (DEBUG_SHOW_INFO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005127 Log.v(TAG, " IntentFilter:");
5128 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
5129 }
5130 removeFilter(intent);
5131 }
5132 }
5133
5134 @Override
5135 protected boolean allowFilterResult(
5136 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
5137 ServiceInfo filterSi = filter.service.info;
5138 for (int i=dest.size()-1; i>=0; i--) {
5139 ServiceInfo destAi = dest.get(i).serviceInfo;
5140 if (destAi.name == filterSi.name
5141 && destAi.packageName == filterSi.packageName) {
5142 return false;
5143 }
5144 }
5145 return true;
5146 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005148 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07005149 protected PackageParser.ServiceIntentInfo[] newArray(int size) {
5150 return new PackageParser.ServiceIntentInfo[size];
5151 }
5152
5153 @Override
Amith Yamasani483f3b02012-03-13 16:08:00 -07005154 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005155 if (!sUserManager.exists(userId)) return true;
Dianne Hackborne7f97212011-02-24 14:40:20 -08005156 PackageParser.Package p = filter.service.owner;
5157 if (p != null) {
5158 PackageSetting ps = (PackageSetting)p.mExtras;
5159 if (ps != null) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07005160 // System apps are never considered stopped for purposes of
5161 // filtering, because there may be no way for the user to
5162 // actually re-launch them.
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005163 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
5164 && ps.getStopped(userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08005165 }
5166 }
5167 return false;
5168 }
5169
5170 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005171 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
5172 return info.service.owner.packageName;
5173 }
5174
5175 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005176 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005177 int match, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005178 if (!sUserManager.exists(userId)) return null;
Jason parksa3cdaa52011-01-13 14:15:43 -06005179 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005180 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005181 return null;
5182 }
5183 final PackageParser.Service service = info.service;
5184 if (mSafeMode && (service.info.applicationInfo.flags
5185 &ApplicationInfo.FLAG_SYSTEM) == 0) {
5186 return null;
5187 }
Amith Yamasani13593602012-03-22 16:16:17 -07005188 PackageSetting ps = (PackageSetting) service.owner.mExtras;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005189 if (ps == null) {
5190 return null;
5191 }
5192 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
5193 ps.readUserState(userId), userId);
Dianne Hackborn4428e172012-08-24 17:43:05 -07005194 if (si == null) {
5195 return null;
5196 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005197 final ResolveInfo res = new ResolveInfo();
5198 res.serviceInfo = si;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005199 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
5200 res.filter = filter;
5201 }
5202 res.priority = info.getPriority();
5203 res.preferredOrder = service.owner.mPreferredOrder;
5204 //System.out.println("Result: " + res.activityInfo.className +
5205 // " = " + res.priority);
5206 res.match = match;
5207 res.isDefault = info.hasDefault;
5208 res.labelRes = info.labelRes;
5209 res.nonLocalizedLabel = info.nonLocalizedLabel;
5210 res.icon = info.icon;
Dianne Hackbornd99b2932011-08-18 14:39:58 -07005211 res.system = isSystemApp(res.serviceInfo.applicationInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005212 return res;
5213 }
5214
5215 @Override
5216 protected void sortResults(List<ResolveInfo> results) {
5217 Collections.sort(results, mResolvePrioritySorter);
5218 }
5219
5220 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005221 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005222 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005223 out.print(prefix); out.print(
5224 Integer.toHexString(System.identityHashCode(filter.service)));
5225 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005226 out.print(filter.service.getComponentShortName());
5227 out.print(" filter ");
5228 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005229 }
5230
5231// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
5232// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
5233// final List<ResolveInfo> retList = Lists.newArrayList();
5234// while (i.hasNext()) {
5235// final ResolveInfo resolveInfo = (ResolveInfo) i;
5236// if (isEnabledLP(resolveInfo.serviceInfo)) {
5237// retList.add(resolveInfo);
5238// }
5239// }
5240// return retList;
5241// }
5242
5243 // Keys are String (activity class name), values are Activity.
5244 private final HashMap<ComponentName, PackageParser.Service> mServices
5245 = new HashMap<ComponentName, PackageParser.Service>();
5246 private int mFlags;
5247 };
5248
5249 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
5250 new Comparator<ResolveInfo>() {
5251 public int compare(ResolveInfo r1, ResolveInfo r2) {
5252 int v1 = r1.priority;
5253 int v2 = r2.priority;
5254 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
5255 if (v1 != v2) {
5256 return (v1 > v2) ? -1 : 1;
5257 }
5258 v1 = r1.preferredOrder;
5259 v2 = r2.preferredOrder;
5260 if (v1 != v2) {
5261 return (v1 > v2) ? -1 : 1;
5262 }
5263 if (r1.isDefault != r2.isDefault) {
5264 return r1.isDefault ? -1 : 1;
5265 }
5266 v1 = r1.match;
5267 v2 = r2.match;
5268 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
Dianne Hackbornd99b2932011-08-18 14:39:58 -07005269 if (v1 != v2) {
5270 return (v1 > v2) ? -1 : 1;
5271 }
5272 if (r1.system != r2.system) {
5273 return r1.system ? -1 : 1;
5274 }
5275 return 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005276 }
5277 };
5278
5279 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
5280 new Comparator<ProviderInfo>() {
5281 public int compare(ProviderInfo p1, ProviderInfo p2) {
5282 final int v1 = p1.initOrder;
5283 final int v2 = p2.initOrder;
5284 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
5285 }
5286 };
5287
Kenny Root447106f2011-03-23 11:00:15 -07005288 static final void sendPackageBroadcast(String action, String pkg,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005289 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
5290 int[] userIds) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005291 IActivityManager am = ActivityManagerNative.getDefault();
5292 if (am != null) {
5293 try {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005294 if (userIds == null) {
5295 userIds = sUserManager.getUserIds();
5296 }
Amith Yamasani13593602012-03-22 16:16:17 -07005297 for (int id : userIds) {
5298 final Intent intent = new Intent(action,
5299 pkg != null ? Uri.fromParts("package", pkg, null) : null);
5300 if (extras != null) {
5301 intent.putExtras(extras);
5302 }
5303 if (targetPkg != null) {
5304 intent.setPackage(targetPkg);
5305 }
5306 // Modify the UID when posting to other users
5307 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005308 if (uid > 0 && UserHandle.getUserId(uid) != id) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005309 uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
Amith Yamasani13593602012-03-22 16:16:17 -07005310 intent.putExtra(Intent.EXTRA_UID, uid);
5311 }
5312 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005313 if (DEBUG_BROADCASTS) {
5314 RuntimeException here = new RuntimeException("here");
5315 here.fillInStackTrace();
5316 Slog.d(TAG, "Sending to user " + id + ": "
5317 + intent.toShortString(false, true, false, false)
5318 + " " + intent.getExtras(), here);
5319 }
Amith Yamasani13593602012-03-22 16:16:17 -07005320 am.broadcastIntent(null, intent, null, finishedReceiver,
5321 0, null, null, null, finishedReceiver != null, false, id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005323 } catch (RemoteException ex) {
5324 }
5325 }
5326 }
Kenny Root300c13a2011-01-18 13:04:40 -08005327
5328 /**
5329 * Check if the external storage media is available. This is true if there
5330 * is a mounted external storage medium or if the external storage is
5331 * emulated.
5332 */
5333 private boolean isExternalMediaAvailable() {
5334 return mMediaMounted || Environment.isExternalStorageEmulated();
5335 }
5336
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005337 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
Kenny Root447106f2011-03-23 11:00:15 -07005338 // writer
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005339 final int userId = UserHandle.getCallingUserId();
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005340 synchronized (mPackages) {
Kenny Root300c13a2011-01-18 13:04:40 -08005341 if (!isExternalMediaAvailable()) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005342 // If the external storage is no longer mounted at this point,
5343 // the caller may not have been able to delete all of this
5344 // packages files and can not delete any more. Bail.
5345 return null;
5346 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005347 ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned.get(userId);
5348 if (pkgs != null) {
5349 if (lastPackage != null) {
5350 pkgs.remove(lastPackage);
5351 }
5352 if (pkgs.size() > 0) {
5353 return pkgs.get(0);
5354 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005355 }
Dianne Hackborn377de7b2012-08-28 15:57:33 -07005356 mSettings.mPackagesToBeCleaned.remove(userId);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005357 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005358 // Move on to the next user to clean.
5359 long ident = Binder.clearCallingIdentity();
5360 try {
5361 startCleaningPackages(userId);
5362 } finally {
5363 Binder.restoreCallingIdentity(ident);
5364 }
5365 return null;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005367
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005368 void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
5369 if (false) {
5370 RuntimeException here = new RuntimeException("here");
5371 here.fillInStackTrace();
5372 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
5373 + " andCode=" + andCode, here);
5374 }
5375 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
5376 userId, andCode ? 1 : 0, packageName));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005377 }
5378
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005379 void startCleaningPackages(int lastUser) {
Kenny Root447106f2011-03-23 11:00:15 -07005380 // reader
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005381 int nextUser = -1;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005382 synchronized (mPackages) {
Kenny Root300c13a2011-01-18 13:04:40 -08005383 if (!isExternalMediaAvailable()) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005384 return;
5385 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005386 final int N = mSettings.mPackagesToBeCleaned.size();
5387 if (N <= 0) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005388 return;
5389 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005390 for (int i=0; i<N; i++) {
5391 int user = mSettings.mPackagesToBeCleaned.keyAt(i);
5392 if (user > lastUser) {
5393 nextUser = user;
5394 break;
5395 }
5396 }
5397 if (nextUser < 0) {
5398 nextUser = mSettings.mPackagesToBeCleaned.keyAt(0);
5399 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005400 }
5401 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
5402 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
5403 IActivityManager am = ActivityManagerNative.getDefault();
5404 if (am != null) {
5405 try {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005406 am.startService(null, intent, null, nextUser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005407 } catch (RemoteException e) {
5408 }
5409 }
5410 }
5411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005412 private final class AppDirObserver extends FileObserver {
5413 public AppDirObserver(String path, int mask, boolean isrom) {
5414 super(path, mask);
5415 mRootDir = path;
5416 mIsRom = isrom;
5417 }
5418
5419 public void onEvent(int event, String path) {
5420 String removedPackage = null;
5421 int removedUid = -1;
Dianne Hackborn786b4402012-08-27 15:14:02 -07005422 int[] removedUsers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005423 String addedPackage = null;
5424 int addedUid = -1;
Dianne Hackborn786b4402012-08-27 15:14:02 -07005425 int[] addedUsers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005426
Kenny Root447106f2011-03-23 11:00:15 -07005427 // TODO post a message to the handler to obtain serial ordering
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005428 synchronized (mInstallLock) {
5429 String fullPathStr = null;
5430 File fullPath = null;
5431 if (path != null) {
5432 fullPath = new File(mRootDir, path);
5433 fullPathStr = fullPath.getPath();
5434 }
5435
Kenny Root9718cf52011-02-23 16:45:26 -08005436 if (DEBUG_APP_DIR_OBSERVER)
5437 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005438
5439 if (!isPackageFilename(path)) {
Kenny Root9718cf52011-02-23 16:45:26 -08005440 if (DEBUG_APP_DIR_OBSERVER)
5441 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005442 return;
5443 }
5444
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005445 // Ignore packages that are being installed or
5446 // have just been installed.
5447 if (ignoreCodePath(fullPathStr)) {
5448 return;
5449 }
5450 PackageParser.Package p = null;
Kenny Root447106f2011-03-23 11:00:15 -07005451 // reader
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005452 synchronized (mPackages) {
5453 p = mAppDirs.get(fullPathStr);
Dianne Hackborn786b4402012-08-27 15:14:02 -07005454 if (p != null) {
5455 PackageSetting ps = mSettings.mPackages.get(p.applicationInfo.packageName);
5456 if (ps != null) {
5457 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
5458 } else {
5459 removedUsers = sUserManager.getUserIds();
5460 }
5461 }
5462 addedUsers = sUserManager.getUserIds();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005464 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005465 if (p != null) {
5466 removePackageLI(p, true);
5467 removedPackage = p.applicationInfo.packageName;
5468 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005469 }
5470 }
5471
5472 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005473 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005474 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07005475 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
5476 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005477 PackageParser.PARSE_CHATTY |
5478 PackageParser.PARSE_MUST_BE_APK,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005479 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
Dianne Hackborn786b4402012-08-27 15:14:02 -07005480 System.currentTimeMillis(), UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005481 if (p != null) {
Kenny Root447106f2011-03-23 11:00:15 -07005482 /*
5483 * TODO this seems dangerous as the package may have
5484 * changed since we last acquired the mPackages
5485 * lock.
5486 */
5487 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07005489 updatePermissionsLPw(p.packageName, p,
Dianne Hackborne639da72012-02-21 15:11:13 -08005490 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005491 }
5492 addedPackage = p.applicationInfo.packageName;
5493 addedUid = p.applicationInfo.uid;
5494 }
5495 }
5496 }
5497
Kenny Root447106f2011-03-23 11:00:15 -07005498 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005499 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07005500 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005501 }
5502 }
5503
5504 if (removedPackage != null) {
5505 Bundle extras = new Bundle(1);
5506 extras.putInt(Intent.EXTRA_UID, removedUid);
5507 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07005508 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
Dianne Hackborn786b4402012-08-27 15:14:02 -07005509 extras, null, null, removedUsers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005510 }
5511 if (addedPackage != null) {
5512 Bundle extras = new Bundle(1);
5513 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07005514 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
Dianne Hackborn786b4402012-08-27 15:14:02 -07005515 extras, null, null, addedUsers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005516 }
5517 }
5518
5519 private final String mRootDir;
5520 private final boolean mIsRom;
5521 }
Jacek Surazski65e13172009-04-28 15:26:38 +02005522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005523 /* Called when a downloaded package installation has been confirmed by the user */
5524 public void installPackage(
5525 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02005526 installPackage(packageURI, observer, flags, null);
5527 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005528
Jacek Surazski65e13172009-04-28 15:26:38 +02005529 /* Called when a downloaded package installation has been confirmed by the user */
5530 public void installPackage(
5531 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
5532 final String installerPackageName) {
Kenny Root5ab21572011-07-27 11:11:19 -07005533 installPackageWithVerification(packageURI, observer, flags, installerPackageName, null,
Rich Canningse1d7c712012-08-08 12:46:06 -07005534 null, null);
Kenny Root5ab21572011-07-27 11:11:19 -07005535 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005536
Kenny Root5ab21572011-07-27 11:11:19 -07005537 @Override
5538 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
5539 int flags, String installerPackageName, Uri verificationURI,
Rich Canningse1d7c712012-08-08 12:46:06 -07005540 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
rich cannings706e8ba2012-08-20 13:20:14 -07005541 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
5542 manifestDigest);
5543 installPackageWithVerificationAndEncryption(packageURI, observer, flags,
5544 installerPackageName, verificationParams, encryptionParams);
5545 }
5546
5547 public void installPackageWithVerificationAndEncryption(Uri packageURI,
5548 IPackageInstallObserver observer, int flags, String installerPackageName,
5549 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
5550 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
5551 null);
Kenny Root5ab21572011-07-27 11:11:19 -07005552
5553 final int uid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005554 UserHandle user;
5555 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
5556 user = UserHandle.ALL;
5557 } else {
Dianne Hackborn786b4402012-08-27 15:14:02 -07005558 user = new UserHandle(UserHandle.getUserId(uid));
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005559 }
Kenny Root5ab21572011-07-27 11:11:19 -07005560
5561 final int filteredFlags;
5562
5563 if (uid == Process.SHELL_UID || uid == 0) {
5564 if (DEBUG_INSTALL) {
5565 Slog.v(TAG, "Install from ADB");
5566 }
5567 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
5568 } else {
5569 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
5570 }
5571
5572 final Message msg = mHandler.obtainMessage(INIT_COPY);
5573 msg.obj = new InstallParams(packageURI, observer, filteredFlags, installerPackageName,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005574 verificationParams, encryptionParams, user);
Kenny Root5ab21572011-07-27 11:11:19 -07005575 mHandler.sendMessage(msg);
5576 }
5577
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005578 /**
5579 * @hide
5580 */
5581 @Override
5582 public int installExistingPackage(String packageName) {
5583 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
5584 null);
5585 PackageSetting pkgSetting;
5586 final int uid = Binder.getCallingUid();
5587 final int userId = UserHandle.getUserId(uid);
5588
5589 long callingId = Binder.clearCallingIdentity();
5590 try {
5591 boolean sendAdded = false;
5592 Bundle extras = new Bundle(1);
5593
5594 // writer
5595 synchronized (mPackages) {
5596 pkgSetting = mSettings.mPackages.get(packageName);
5597 if (pkgSetting == null) {
5598 return PackageManager.INSTALL_FAILED_INVALID_URI;
5599 }
5600 if (!pkgSetting.getInstalled(userId)) {
5601 pkgSetting.setInstalled(true, userId);
5602 mSettings.writePackageRestrictionsLPr(userId);
5603 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
5604 sendAdded = true;
5605 }
5606 }
5607
5608 if (sendAdded) {
5609 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
5610 packageName, extras, null, null, new int[] {userId});
5611 }
5612 } finally {
5613 Binder.restoreCallingIdentity(callingId);
5614 }
5615
5616 return PackageManager.INSTALL_SUCCEEDED;
5617 }
5618
Kenny Root5ab21572011-07-27 11:11:19 -07005619 @Override
Kenny Root05ca4c92011-09-15 10:36:25 -07005620 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
rich cannings7e671512012-08-27 14:44:16 -07005621 mContext.enforceCallingOrSelfPermission(
5622 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
5623 "Only package verification agents can verify applications");
5624
Kenny Root5ab21572011-07-27 11:11:19 -07005625 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
Kenny Root05ca4c92011-09-15 10:36:25 -07005626 final PackageVerificationResponse response = new PackageVerificationResponse(
5627 verificationCode, Binder.getCallingUid());
Kenny Root5ab21572011-07-27 11:11:19 -07005628 msg.arg1 = id;
Kenny Root05ca4c92011-09-15 10:36:25 -07005629 msg.obj = response;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005630 mHandler.sendMessage(msg);
5631 }
5632
rich canningsd9ef3e52012-08-22 14:28:05 -07005633 @Override
5634 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
5635 long millisecondsToDelay) {
rich cannings7e671512012-08-27 14:44:16 -07005636 mContext.enforceCallingOrSelfPermission(
5637 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
5638 "Only package verification agents can extend verification timeouts");
5639
rich canningsd9ef3e52012-08-22 14:28:05 -07005640 final PackageVerificationState state = mPendingVerification.get(id);
5641 final PackageVerificationResponse response = new PackageVerificationResponse(
5642 verificationCodeAtTimeout, Binder.getCallingUid());
5643
5644 if ((millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT)
5645 || (millisecondsToDelay < 0)) {
5646 throw new IllegalArgumentException("millisecondsToDelay is out of bounds.");
5647 }
5648 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
5649 || (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
5650 throw new IllegalArgumentException("verificationCodeAtTimeout is unknown.");
5651 }
5652
5653 if ((state != null) && !state.timeoutExtended()) {
5654 state.extendTimeout();
5655
5656 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
5657 msg.arg1 = id;
5658 msg.obj = response;
5659 mHandler.sendMessageDelayed(msg, millisecondsToDelay);
5660 }
5661 }
5662
Kenny Root05ca4c92011-09-15 10:36:25 -07005663 private ComponentName matchComponentForVerifier(String packageName,
5664 List<ResolveInfo> receivers) {
5665 ActivityInfo targetReceiver = null;
5666
5667 final int NR = receivers.size();
5668 for (int i = 0; i < NR; i++) {
5669 final ResolveInfo info = receivers.get(i);
5670 if (info.activityInfo == null) {
5671 continue;
5672 }
5673
5674 if (packageName.equals(info.activityInfo.packageName)) {
5675 targetReceiver = info.activityInfo;
5676 break;
5677 }
5678 }
5679
5680 if (targetReceiver == null) {
5681 return null;
5682 }
5683
5684 return new ComponentName(targetReceiver.packageName, targetReceiver.name);
5685 }
5686
5687 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
5688 List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
5689 if (pkgInfo.verifiers.length == 0) {
5690 return null;
5691 }
5692
5693 final int N = pkgInfo.verifiers.length;
5694 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
5695 for (int i = 0; i < N; i++) {
5696 final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
5697
5698 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
5699 receivers);
5700 if (comp == null) {
5701 continue;
5702 }
5703
5704 final int verifierUid = getUidForVerifier(verifierInfo);
5705 if (verifierUid == -1) {
5706 continue;
5707 }
5708
5709 if (DEBUG_VERIFY) {
5710 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
5711 + " with the correct signature");
5712 }
5713 sufficientVerifiers.add(comp);
5714 verificationState.addSufficientVerifier(verifierUid);
5715 }
5716
5717 return sufficientVerifiers;
5718 }
5719
5720 private int getUidForVerifier(VerifierInfo verifierInfo) {
5721 synchronized (mPackages) {
5722 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
5723 if (pkg == null) {
5724 return -1;
5725 } else if (pkg.mSignatures.length != 1) {
5726 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
5727 + " has more than one signature; ignoring");
5728 return -1;
5729 }
5730
5731 /*
5732 * If the public key of the package's signature does not match
5733 * our expected public key, then this is a different package and
5734 * we should skip.
5735 */
5736
5737 final byte[] expectedPublicKey;
5738 try {
5739 final Signature verifierSig = pkg.mSignatures[0];
5740 final PublicKey publicKey = verifierSig.getPublicKey();
5741 expectedPublicKey = publicKey.getEncoded();
5742 } catch (CertificateException e) {
5743 return -1;
5744 }
5745
5746 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
5747
5748 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
5749 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
5750 + " does not have the expected public key; ignoring");
5751 return -1;
5752 }
5753
5754 return pkg.applicationInfo.uid;
5755 }
5756 }
5757
Christopher Tate1bb69062010-02-19 17:02:12 -08005758 public void finishPackageInstall(int token) {
Kenny Root461ff1f2011-08-09 09:43:03 -07005759 enforceSystemOrRoot("Only the system is allowed to finish installs");
5760
5761 if (DEBUG_INSTALL) {
5762 Slog.v(TAG, "BM finishing package install for " + token);
5763 }
5764
5765 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
Christopher Tate1bb69062010-02-19 17:02:12 -08005766 mHandler.sendMessage(msg);
5767 }
5768
Kenny Root5ab21572011-07-27 11:11:19 -07005769 /**
5770 * Get the verification agent timeout.
5771 *
5772 * @return verification timeout in milliseconds
5773 */
5774 private long getVerificationTimeout() {
5775 return android.provider.Settings.Secure.getLong(mContext.getContentResolver(),
5776 android.provider.Settings.Secure.PACKAGE_VERIFIER_TIMEOUT,
5777 DEFAULT_VERIFICATION_TIMEOUT);
5778 }
5779
5780 /**
rich canningsa6cfe522012-05-21 15:50:56 -07005781 * Get the default verification agent response code.
5782 *
5783 * @return default verification response code
5784 */
5785 private int getDefaultVerificationResponse() {
5786 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
5787 android.provider.Settings.Secure.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
5788 DEFAULT_VERIFICATION_RESPONSE);
5789 }
5790
5791 /**
Kenny Root5ab21572011-07-27 11:11:19 -07005792 * Check whether or not package verification has been enabled.
5793 *
5794 * @return true if verification should be performed
5795 */
5796 private boolean isVerificationEnabled() {
5797 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
5798 android.provider.Settings.Secure.PACKAGE_VERIFIER_ENABLE,
5799 DEFAULT_VERIFY_ENABLE ? 1 : 0) == 1 ? true : false;
5800 }
5801
Matt Finifterf8a98ed2012-05-14 15:43:34 -07005802 /**
5803 * Get the "allow unknown sources" setting.
5804 *
5805 * @return the current "allow unknown sources" setting
5806 */
5807 private int getUnknownSourcesSettings() {
5808 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
5809 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
5810 -1);
5811 }
5812
Kenny Rootf03b45f2011-02-23 17:25:45 -08005813 public void setInstallerPackageName(String targetPackage, String installerPackageName) {
Dianne Hackborn880119b2010-11-18 22:26:40 -08005814 final int uid = Binder.getCallingUid();
Kenny Root447106f2011-03-23 11:00:15 -07005815 // writer
Dianne Hackborn880119b2010-11-18 22:26:40 -08005816 synchronized (mPackages) {
5817 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
5818 if (targetPackageSetting == null) {
5819 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
5820 }
5821
5822 PackageSetting installerPackageSetting;
5823 if (installerPackageName != null) {
5824 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
5825 if (installerPackageSetting == null) {
5826 throw new IllegalArgumentException("Unknown installer package: "
5827 + installerPackageName);
5828 }
5829 } else {
5830 installerPackageSetting = null;
5831 }
5832
5833 Signature[] callerSignature;
Kenny Root447106f2011-03-23 11:00:15 -07005834 Object obj = mSettings.getUserIdLPr(uid);
Dianne Hackborn880119b2010-11-18 22:26:40 -08005835 if (obj != null) {
5836 if (obj instanceof SharedUserSetting) {
5837 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
5838 } else if (obj instanceof PackageSetting) {
5839 callerSignature = ((PackageSetting)obj).signatures.mSignatures;
5840 } else {
5841 throw new SecurityException("Bad object " + obj + " for uid " + uid);
5842 }
5843 } else {
5844 throw new SecurityException("Unknown calling uid " + uid);
5845 }
5846
5847 // Verify: can't set installerPackageName to a package that is
5848 // not signed with the same cert as the caller.
5849 if (installerPackageSetting != null) {
Kenny Root447106f2011-03-23 11:00:15 -07005850 if (compareSignatures(callerSignature,
Dianne Hackborn880119b2010-11-18 22:26:40 -08005851 installerPackageSetting.signatures.mSignatures)
5852 != PackageManager.SIGNATURE_MATCH) {
5853 throw new SecurityException(
5854 "Caller does not have same cert as new installer package "
5855 + installerPackageName);
5856 }
5857 }
5858
5859 // Verify: if target already has an installer package, it must
5860 // be signed with the same cert as the caller.
5861 if (targetPackageSetting.installerPackageName != null) {
5862 PackageSetting setting = mSettings.mPackages.get(
5863 targetPackageSetting.installerPackageName);
5864 // If the currently set package isn't valid, then it's always
5865 // okay to change it.
5866 if (setting != null) {
Kenny Root447106f2011-03-23 11:00:15 -07005867 if (compareSignatures(callerSignature,
Dianne Hackborn880119b2010-11-18 22:26:40 -08005868 setting.signatures.mSignatures)
5869 != PackageManager.SIGNATURE_MATCH) {
5870 throw new SecurityException(
5871 "Caller does not have same cert as old installer package "
5872 + targetPackageSetting.installerPackageName);
5873 }
5874 }
5875 }
5876
5877 // Okay!
5878 targetPackageSetting.installerPackageName = installerPackageName;
5879 scheduleWriteSettingsLocked();
5880 }
5881 }
5882
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005883 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005884 // Queue up an async operation since the package installation may take a little while.
5885 mHandler.post(new Runnable() {
5886 public void run() {
5887 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005888 // Result object to be returned
5889 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005890 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005891 res.uid = -1;
5892 res.pkg = null;
5893 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005894 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07005895 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005896 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005897 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005898 }
Kenny Root6dceb882012-04-12 14:23:49 -07005899 args.doPostInstall(res.returnCode, res.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005900 }
Christopher Tate1bb69062010-02-19 17:02:12 -08005901
5902 // A restore should be performed at this point if (a) the install
5903 // succeeded, (b) the operation is not an update, and (c) the new
5904 // package has a backupAgent defined.
5905 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08005906 boolean doRestore = (!update
5907 && res.pkg != null
5908 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08005909
5910 // Set up the post-install work request bookkeeping. This will be used
5911 // and cleaned up by the post-install event handling regardless of whether
5912 // there's a restore pass performed. Token values are >= 1.
5913 int token;
5914 if (mNextInstallToken < 0) mNextInstallToken = 1;
5915 token = mNextInstallToken++;
5916
5917 PostInstallData data = new PostInstallData(args, res);
5918 mRunningInstalls.put(token, data);
5919 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
5920
5921 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
5922 // Pass responsibility to the Backup Manager. It will perform a
5923 // restore if appropriate, then pass responsibility back to the
5924 // Package Manager to run the post-install observer callbacks
5925 // and broadcasts.
5926 IBackupManager bm = IBackupManager.Stub.asInterface(
5927 ServiceManager.getService(Context.BACKUP_SERVICE));
5928 if (bm != null) {
5929 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
5930 + " to BM for possible restore");
5931 try {
5932 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
5933 } catch (RemoteException e) {
5934 // can't happen; the backup manager is local
5935 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005936 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08005937 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005938 }
Christopher Tate1bb69062010-02-19 17:02:12 -08005939 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005940 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08005941 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005943 }
Christopher Tate1bb69062010-02-19 17:02:12 -08005944
5945 if (!doRestore) {
5946 // No restore possible, or the Backup Manager was mysteriously not
5947 // available -- just fire the post-install work request directly.
5948 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
5949 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
5950 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005952 }
5953 });
5954 }
5955
Kenny Root5ab21572011-07-27 11:11:19 -07005956 private abstract class HandlerParams {
5957 private static final int MAX_RETRIES = 4;
5958
5959 /**
5960 * Number of times startCopy() has been attempted and had a non-fatal
5961 * error.
5962 */
5963 private int mRetries = 0;
5964
Amith Yamasani6ec10122012-08-23 13:49:25 -07005965 /** User handle for the user requesting the information or installation. */
5966 private final UserHandle mUser;
5967
5968 HandlerParams(UserHandle user) {
5969 mUser = user;
5970 }
5971
5972 UserHandle getUser() {
5973 return mUser;
5974 }
5975
Dianne Hackborn7d608422011-08-07 16:24:18 -07005976 final boolean startCopy() {
5977 boolean res;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005978 try {
Kenny Root5ab21572011-07-27 11:11:19 -07005979 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy");
5980
5981 if (++mRetries > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005982 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005983 mHandler.sendEmptyMessage(MCS_GIVE_UP);
5984 handleServiceError();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005985 return false;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005986 } else {
5987 handleStartCopy();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005988 res = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005989 }
5990 } catch (RemoteException e) {
Kenny Root5ab21572011-07-27 11:11:19 -07005991 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005992 mHandler.sendEmptyMessage(MCS_RECONNECT);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005993 res = false;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005994 }
5995 handleReturnCode();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005996 return res;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005997 }
5998
5999 final void serviceError() {
Kenny Root5ab21572011-07-27 11:11:19 -07006000 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006001 handleServiceError();
6002 handleReturnCode();
6003 }
Kenny Root5ab21572011-07-27 11:11:19 -07006004
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006005 abstract void handleStartCopy() throws RemoteException;
6006 abstract void handleServiceError();
6007 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006008 }
6009
Kenny Root366949c2011-01-14 17:18:14 -08006010 class MeasureParams extends HandlerParams {
6011 private final PackageStats mStats;
6012 private boolean mSuccess;
6013
6014 private final IPackageStatsObserver mObserver;
6015
Kenny Roota69b7eb2012-05-14 14:47:06 -07006016 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
Amith Yamasani6ec10122012-08-23 13:49:25 -07006017 super(new UserHandle(stats.userHandle));
Kenny Root366949c2011-01-14 17:18:14 -08006018 mObserver = observer;
6019 mStats = stats;
Kenny Root366949c2011-01-14 17:18:14 -08006020 }
6021
6022 @Override
6023 void handleStartCopy() throws RemoteException {
Kenny Roota69b7eb2012-05-14 14:47:06 -07006024 synchronized (mInstallLock) {
Dianne Hackborn0c380492012-08-20 17:23:30 -07006025 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
Kenny Roota69b7eb2012-05-14 14:47:06 -07006026 }
Kenny Root366949c2011-01-14 17:18:14 -08006027
Kenny Roota69b7eb2012-05-14 14:47:06 -07006028 final boolean mounted;
Kenny Root366949c2011-01-14 17:18:14 -08006029 if (Environment.isExternalStorageEmulated()) {
6030 mounted = true;
6031 } else {
6032 final String status = Environment.getExternalStorageState();
6033
6034 mounted = status.equals(Environment.MEDIA_MOUNTED)
6035 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
6036 }
6037
6038 if (mounted) {
6039 final File externalCacheDir = Environment
6040 .getExternalStorageAppCacheDirectory(mStats.packageName);
6041 final long externalCacheSize = mContainerService
6042 .calculateDirectorySize(externalCacheDir.getPath());
6043 mStats.externalCacheSize = externalCacheSize;
6044
6045 final File externalDataDir = Environment
6046 .getExternalStorageAppDataDirectory(mStats.packageName);
6047 long externalDataSize = mContainerService.calculateDirectorySize(externalDataDir
6048 .getPath());
6049
6050 if (externalCacheDir.getParentFile().equals(externalDataDir)) {
6051 externalDataSize -= externalCacheSize;
6052 }
6053 mStats.externalDataSize = externalDataSize;
6054
6055 final File externalMediaDir = Environment
6056 .getExternalStorageAppMediaDirectory(mStats.packageName);
6057 mStats.externalMediaSize = mContainerService
Kenny Rootc7624d92011-02-23 16:25:25 -08006058 .calculateDirectorySize(externalMediaDir.getPath());
Kenny Rootbcd6c962011-01-17 11:21:49 -08006059
6060 final File externalObbDir = Environment
6061 .getExternalStorageAppObbDirectory(mStats.packageName);
6062 mStats.externalObbSize = mContainerService.calculateDirectorySize(externalObbDir
6063 .getPath());
Kenny Root366949c2011-01-14 17:18:14 -08006064 }
6065 }
6066
6067 @Override
6068 void handleReturnCode() {
6069 if (mObserver != null) {
6070 try {
6071 mObserver.onGetStatsCompleted(mStats, mSuccess);
6072 } catch (RemoteException e) {
6073 Slog.i(TAG, "Observer no longer exists.");
6074 }
6075 }
6076 }
6077
6078 @Override
6079 void handleServiceError() {
6080 Slog.e(TAG, "Could not measure application " + mStats.packageName
6081 + " external storage");
6082 }
6083 }
6084
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006085 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006086 final IPackageInstallObserver observer;
6087 int flags;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006088
6089 private final Uri mPackageURI;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006090 final String installerPackageName;
rich cannings706e8ba2012-08-20 13:20:14 -07006091 final VerificationParams verificationParams;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006092 private InstallArgs mArgs;
6093 private int mRet;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006094 private File mTempPackage;
6095 final ContainerEncryptionParams encryptionParams;
Kenny Root5ab21572011-07-27 11:11:19 -07006096
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006097 InstallParams(Uri packageURI,
6098 IPackageInstallObserver observer, int flags,
rich cannings706e8ba2012-08-20 13:20:14 -07006099 String installerPackageName, VerificationParams verificationParams,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006100 ContainerEncryptionParams encryptionParams, UserHandle user) {
Amith Yamasani6ec10122012-08-23 13:49:25 -07006101 super(user);
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006102 this.mPackageURI = packageURI;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006103 this.flags = flags;
6104 this.observer = observer;
6105 this.installerPackageName = installerPackageName;
rich cannings706e8ba2012-08-20 13:20:14 -07006106 this.verificationParams = verificationParams;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006107 this.encryptionParams = encryptionParams;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006108 }
6109
rich cannings706e8ba2012-08-20 13:20:14 -07006110 public ManifestDigest getManifestDigest() {
6111 if (verificationParams == null) {
6112 return null;
6113 }
6114 return verificationParams.getManifestDigest();
6115 }
6116
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006117 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
6118 String packageName = pkgLite.packageName;
6119 int installLocation = pkgLite.installLocation;
6120 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Kenny Root447106f2011-03-23 11:00:15 -07006121 // reader
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006122 synchronized (mPackages) {
6123 PackageParser.Package pkg = mPackages.get(packageName);
6124 if (pkg != null) {
6125 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006126 // Check for downgrading.
6127 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
6128 if (pkgLite.versionCode < pkg.mVersionCode) {
6129 Slog.w(TAG, "Can't install update of " + packageName
6130 + " update version " + pkgLite.versionCode
6131 + " is older than installed version "
6132 + pkg.mVersionCode);
6133 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
6134 }
6135 }
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006136 // Check for updated system application.
6137 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6138 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006139 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006140 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
6141 }
6142 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
6143 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006144 if (onSd) {
6145 // Install flag overrides everything.
6146 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
6147 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07006148 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006149 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
6150 // Application explicitly specified internal.
6151 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
6152 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
6153 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07006154 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006155 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07006156 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07006157 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
6158 }
6159 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006160 }
6161 }
6162 } else {
6163 // Invalid install. Return error code
6164 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
6165 }
6166 }
6167 }
6168 // All the special cases have been taken care of.
6169 // Return result based on recommended install location.
6170 if (onSd) {
6171 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
6172 }
6173 return pkgLite.recommendedInstallLocation;
6174 }
6175
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006176 /*
6177 * Invoke remote method to get package information and install
6178 * location values. Override install location based on default
6179 * policy if needed and then create install arguments based
6180 * on the install location.
6181 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006182 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08006183 int ret = PackageManager.INSTALL_SUCCEEDED;
Kenny Root05ca4c92011-09-15 10:36:25 -07006184 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
6185 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
6186 PackageInfoLite pkgLite = null;
6187
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07006188 if (onInt && onSd) {
6189 // Check if both bits are set.
6190 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
6191 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006192 } else {
Kenny Root62e1b4e2011-03-14 17:13:39 -07006193 final long lowThreshold;
6194
6195 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
6196 .getService(DeviceStorageMonitorService.SERVICE);
6197 if (dsm == null) {
6198 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
6199 lowThreshold = 0L;
6200 } else {
6201 lowThreshold = dsm.getMemoryLowThreshold();
6202 }
6203
Kenny Root11128572010-10-11 10:51:32 -07006204 try {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006205 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
Kenny Root11128572010-10-11 10:51:32 -07006206 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root11128572010-10-11 10:51:32 -07006207
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006208 final File packageFile;
6209 if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
6210 ParcelFileDescriptor out = null;
6211
6212 mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
6213 if (mTempPackage != null) {
6214 try {
6215 out = ParcelFileDescriptor.open(mTempPackage,
6216 ParcelFileDescriptor.MODE_READ_WRITE);
6217 } catch (FileNotFoundException e) {
6218 Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
6219 }
6220
6221 // Make a temporary file for decryption.
6222 ret = mContainerService
6223 .copyResource(mPackageURI, encryptionParams, out);
6224
6225 packageFile = mTempPackage;
6226
6227 FileUtils.setPermissions(packageFile.getAbsolutePath(),
6228 FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IROTH,
6229 -1, -1);
6230 } else {
6231 packageFile = null;
6232 }
6233 } else {
6234 packageFile = new File(mPackageURI.getPath());
6235 }
6236
6237 if (packageFile != null) {
6238 // Remote call to find out default install location
6239 pkgLite = mContainerService.getMinimalPackageInfo(
6240 packageFile.getAbsolutePath(), flags, lowThreshold);
6241 }
6242 } finally {
6243 mContext.revokeUriPermission(mPackageURI,
6244 Intent.FLAG_GRANT_READ_URI_PERMISSION);
6245 }
6246 }
6247
6248 if (ret == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006249 int loc = pkgLite.recommendedInstallLocation;
Kenny Root1ebd74a2011-08-03 15:09:44 -07006250 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006251 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Kenny Root1ebd74a2011-08-03 15:09:44 -07006252 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006253 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
Kenny Root1ebd74a2011-08-03 15:09:44 -07006254 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006255 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6256 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
6257 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Kenny Root1ebd74a2011-08-03 15:09:44 -07006258 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
6259 ret = PackageManager.INSTALL_FAILED_INVALID_URI;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006260 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
Kenny Root1ebd74a2011-08-03 15:09:44 -07006261 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006262 } else if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
6263 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006264 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006265 // Override with defaults if needed.
6266 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07006267 if (!onSd && !onInt) {
6268 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006269 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
6270 // Set the flag to install on external media.
6271 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07006272 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006273 } else {
6274 // Make sure the flag for installing on external
6275 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07006276 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006277 flags &= ~PackageManager.INSTALL_EXTERNAL;
6278 }
6279 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006280 }
6281 }
Kenny Root5ab21572011-07-27 11:11:19 -07006282
6283 final InstallArgs args = createInstallArgs(this);
Kenny Root05ca4c92011-09-15 10:36:25 -07006284 mArgs = args;
6285
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006286 if (ret == PackageManager.INSTALL_SUCCEEDED) {
Kenny Root5ab21572011-07-27 11:11:19 -07006287 /*
6288 * Determine if we have any installed package verifiers. If we
6289 * do, then we'll defer to them to verify the packages.
6290 */
Kenny Root05ca4c92011-09-15 10:36:25 -07006291 final int requiredUid = mRequiredVerifierPackage == null ? -1
Amith Yamasani483f3b02012-03-13 16:08:00 -07006292 : getPackageUid(mRequiredVerifierPackage, 0);
Kenny Root05ca4c92011-09-15 10:36:25 -07006293 if (requiredUid != -1 && isVerificationEnabled()) {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006294 final Intent verification = new Intent(
6295 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
6296 verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
Kenny Root05ca4c92011-09-15 10:36:25 -07006297 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root5ab21572011-07-27 11:11:19 -07006298
Andy Stadler250ce282012-08-24 16:09:03 -07006299 final List<ResolveInfo> receivers = queryIntentReceivers(verification,
6300 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
6301 0 /* TODO: Which userId? */);
Kenny Root05ca4c92011-09-15 10:36:25 -07006302
6303 if (DEBUG_VERIFY) {
Kenny Root5ab21572011-07-27 11:11:19 -07006304 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
Kenny Root05ca4c92011-09-15 10:36:25 -07006305 + verification.toString() + " with " + pkgLite.verifiers.length
6306 + " optional verifiers");
Kenny Root5ab21572011-07-27 11:11:19 -07006307 }
6308
6309 final int verificationId = mPendingVerificationToken++;
6310
6311 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
6312
6313 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
6314 installerPackageName);
6315
6316 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
6317
rich cannings706e8ba2012-08-20 13:20:14 -07006318 if (verificationParams != null) {
6319 if (verificationParams.getVerificationURI() != null) {
6320 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
6321 verificationParams.getVerificationURI());
6322 }
6323 if (verificationParams.getOriginatingURI() != null) {
6324 verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
6325 verificationParams.getOriginatingURI());
6326 }
6327 if (verificationParams.getReferrer() != null) {
6328 verification.putExtra(Intent.EXTRA_REFERRER,
6329 verificationParams.getReferrer());
6330 }
Kenny Root5ab21572011-07-27 11:11:19 -07006331 }
6332
Kenny Root05ca4c92011-09-15 10:36:25 -07006333 final PackageVerificationState verificationState = new PackageVerificationState(
6334 requiredUid, args);
6335
6336 mPendingVerification.append(verificationId, verificationState);
6337
6338 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
6339 receivers, verificationState);
Kenny Root5ab21572011-07-27 11:11:19 -07006340
6341 /*
Kenny Root05ca4c92011-09-15 10:36:25 -07006342 * If any sufficient verifiers were listed in the package
6343 * manifest, attempt to ask them.
Kenny Root5ab21572011-07-27 11:11:19 -07006344 */
Kenny Root05ca4c92011-09-15 10:36:25 -07006345 if (sufficientVerifiers != null) {
6346 final int N = sufficientVerifiers.size();
6347 if (N == 0) {
6348 Slog.i(TAG, "Additional verifiers required, but none installed.");
6349 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
6350 } else {
6351 for (int i = 0; i < N; i++) {
6352 final ComponentName verifierComponent = sufficientVerifiers.get(i);
6353
6354 final Intent sufficientIntent = new Intent(verification);
6355 sufficientIntent.setComponent(verifierComponent);
6356
6357 mContext.sendBroadcast(sufficientIntent);
6358 }
6359 }
6360 }
6361
6362 final ComponentName requiredVerifierComponent = matchComponentForVerifier(
6363 mRequiredVerifierPackage, receivers);
6364 if (ret == PackageManager.INSTALL_SUCCEEDED
6365 && mRequiredVerifierPackage != null) {
6366 /*
6367 * Send the intent to the required verification agent,
6368 * but only start the verification timeout after the
6369 * target BroadcastReceivers have run.
6370 */
6371 verification.setComponent(requiredVerifierComponent);
6372 mContext.sendOrderedBroadcast(verification,
6373 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
6374 new BroadcastReceiver() {
6375 @Override
6376 public void onReceive(Context context, Intent intent) {
6377 final Message msg = mHandler
6378 .obtainMessage(CHECK_PENDING_VERIFICATION);
6379 msg.arg1 = verificationId;
6380 mHandler.sendMessageDelayed(msg, getVerificationTimeout());
6381 }
6382 }, null, 0, null, null);
6383
6384 /*
6385 * We don't want the copy to proceed until verification
6386 * succeeds, so null out this field.
6387 */
6388 mArgs = null;
6389 }
Kenny Root5ab21572011-07-27 11:11:19 -07006390 } else {
Kenny Root05ca4c92011-09-15 10:36:25 -07006391 /*
6392 * No package verification is enabled, so immediately start
6393 * the remote call to initiate copy using temporary file.
6394 */
Kenny Root5ab21572011-07-27 11:11:19 -07006395 ret = args.copyApk(mContainerService, true);
6396 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006397 }
Kenny Root5ab21572011-07-27 11:11:19 -07006398
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006399 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006400 }
6401
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006402 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006403 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07006404 // If mArgs is null, then MCS couldn't be reached. When it
6405 // reconnects, it will try again to install. At that point, this
6406 // will succeed.
6407 if (mArgs != null) {
6408 processPendingInstall(mArgs, mRet);
6409 }
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006410
6411 if (mTempPackage != null) {
6412 if (!mTempPackage.delete()) {
6413 Slog.w(TAG, "Couldn't delete temporary file: "
6414 + mTempPackage.getAbsolutePath());
6415 }
6416 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006417 }
6418
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006419 @Override
6420 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006421 mArgs = createInstallArgs(this);
6422 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006423 }
Kenny Root6dceb882012-04-12 14:23:49 -07006424
6425 public boolean isForwardLocked() {
6426 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
6427 }
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006428
6429 public Uri getPackageUri() {
6430 if (mTempPackage != null) {
6431 return Uri.fromFile(mTempPackage);
6432 } else {
6433 return mPackageURI;
6434 }
6435 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006436 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006437
6438 /*
6439 * Utility class used in movePackage api.
6440 * srcArgs and targetArgs are not set for invalid flags and make
6441 * sure to do null checks when invoking methods on them.
6442 * We probably want to return ErrorPrams for both failed installs
6443 * and moves.
6444 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006445 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006446 final IPackageMoveObserver observer;
6447 final int flags;
6448 final String packageName;
6449 final InstallArgs srcArgs;
6450 final InstallArgs targetArgs;
Kenny Root6dceb882012-04-12 14:23:49 -07006451 int uid;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006452 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07006453
6454 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
Amith Yamasani6ec10122012-08-23 13:49:25 -07006455 String packageName, String dataDir, int uid, UserHandle user) {
6456 super(user);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006457 this.srcArgs = srcArgs;
6458 this.observer = observer;
6459 this.flags = flags;
6460 this.packageName = packageName;
Kenny Root6dceb882012-04-12 14:23:49 -07006461 this.uid = uid;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006462 if (srcArgs != null) {
6463 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07006464 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006465 } else {
6466 targetArgs = null;
6467 }
6468 }
6469
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006470 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006471 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6472 // Check for storage space on target medium
6473 if (!targetArgs.checkFreeStorage(mContainerService)) {
6474 Log.w(TAG, "Insufficient storage to install");
6475 return;
6476 }
Kenny Rootbf023582012-05-02 16:56:15 -07006477
6478 mRet = srcArgs.doPreCopy();
6479 if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6480 return;
6481 }
6482
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006483 mRet = targetArgs.copyApk(mContainerService, false);
Kenny Rootbf023582012-05-02 16:56:15 -07006484 if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6485 srcArgs.doPostCopy(uid);
6486 return;
6487 }
6488
6489 mRet = srcArgs.doPostCopy(uid);
6490 if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6491 return;
6492 }
6493
6494 mRet = targetArgs.doPreInstall(mRet);
6495 if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6496 return;
6497 }
6498
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006499 if (DEBUG_SD_INSTALL) {
6500 StringBuilder builder = new StringBuilder();
6501 if (srcArgs != null) {
6502 builder.append("src: ");
6503 builder.append(srcArgs.getCodePath());
6504 }
6505 if (targetArgs != null) {
6506 builder.append(" target : ");
6507 builder.append(targetArgs.getCodePath());
6508 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006509 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006510 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006511 }
6512
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006513 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006514 void handleReturnCode() {
Kenny Root6dceb882012-04-12 14:23:49 -07006515 targetArgs.doPostInstall(mRet, uid);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006516 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
6517 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
6518 currentStatus = PackageManager.MOVE_SUCCEEDED;
6519 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
6520 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
6521 }
6522 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006523 }
6524
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006525 @Override
6526 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006527 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006528 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006529 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006530
Kenny Root6dceb882012-04-12 14:23:49 -07006531 /**
6532 * Used during creation of InstallArgs
6533 *
6534 * @param flags package installation flags
6535 * @return true if should be installed on external storage
6536 */
6537 private static boolean installOnSd(int flags) {
6538 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
6539 return false;
6540 }
6541 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
6542 return true;
6543 }
6544 return false;
6545 }
6546
6547 /**
6548 * Used during creation of InstallArgs
6549 *
6550 * @param flags package installation flags
6551 * @return true if should be installed as forward locked
6552 */
6553 private static boolean installForwardLocked(int flags) {
6554 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
6555 }
6556
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006557 private InstallArgs createInstallArgs(InstallParams params) {
Kenny Root6dceb882012-04-12 14:23:49 -07006558 if (installOnSd(params.flags) || params.isForwardLocked()) {
6559 return new AsecInstallArgs(params);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006560 } else {
6561 return new FileInstallArgs(params);
6562 }
6563 }
6564
Kenny Root85387d72010-08-26 10:13:11 -07006565 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
6566 String nativeLibraryPath) {
Kenny Root84e35ea2012-06-06 16:05:05 -07006567 final boolean isInAsec;
6568 if (installOnSd(flags)) {
6569 /* Apps on SD card are always in ASEC containers. */
6570 isInAsec = true;
6571 } else if (installForwardLocked(flags)
6572 && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
6573 /*
6574 * Forward-locked apps are only in ASEC containers if they're the
6575 * new style
6576 */
6577 isInAsec = true;
6578 } else {
6579 isInAsec = false;
6580 }
6581
6582 if (isInAsec) {
Kenny Root6dceb882012-04-12 14:23:49 -07006583 return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
Kenny Rootbf023582012-05-02 16:56:15 -07006584 installOnSd(flags), installForwardLocked(flags));
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006585 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006586 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006587 }
6588 }
6589
Kenny Root85387d72010-08-26 10:13:11 -07006590 // Used by package mover
6591 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Kenny Root6dceb882012-04-12 14:23:49 -07006592 if (installOnSd(flags) || installForwardLocked(flags)) {
Kenny Rootbf023582012-05-02 16:56:15 -07006593 String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
6594 + AsecInstallArgs.RES_FILE_NAME);
6595 return new AsecInstallArgs(packageURI, cid, installOnSd(flags),
6596 installForwardLocked(flags));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006597 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006598 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006599 }
6600 }
6601
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006602 static abstract class InstallArgs {
6603 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006604 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006605 final int flags;
6606 final Uri packageURI;
6607 final String installerPackageName;
Kenny Root5ab21572011-07-27 11:11:19 -07006608 final ManifestDigest manifestDigest;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006609 final UserHandle user;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006610
Kenny Root5ab21572011-07-27 11:11:19 -07006611 InstallArgs(Uri packageURI, IPackageInstallObserver observer, int flags,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006612 String installerPackageName, ManifestDigest manifestDigest,
6613 UserHandle user) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006614 this.packageURI = packageURI;
6615 this.flags = flags;
6616 this.observer = observer;
6617 this.installerPackageName = installerPackageName;
Kenny Root5ab21572011-07-27 11:11:19 -07006618 this.manifestDigest = manifestDigest;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006619 this.user = user;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006620 }
6621
6622 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006623 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006624 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006625 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Kenny Root6dceb882012-04-12 14:23:49 -07006626
6627 abstract int doPostInstall(int status, int uid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006628 abstract String getCodePath();
6629 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07006630 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006631 // Need installer lock especially for dex file removal.
6632 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006633 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006634 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Kenny Root6dceb882012-04-12 14:23:49 -07006635
Kenny Rootbf023582012-05-02 16:56:15 -07006636 /**
6637 * Called before the source arguments are copied. This is used mostly
6638 * for MoveParams when it needs to read the source file to put it in the
6639 * destination.
6640 */
6641 int doPreCopy() {
6642 return PackageManager.INSTALL_SUCCEEDED;
6643 }
6644
6645 /**
6646 * Called after the source arguments are copied. This is used mostly for
6647 * MoveParams when it needs to read the source file to put it in the
6648 * destination.
6649 *
6650 * @return
6651 */
6652 int doPostCopy(int uid) {
6653 return PackageManager.INSTALL_SUCCEEDED;
6654 }
6655
Kenny Root6dceb882012-04-12 14:23:49 -07006656 protected boolean isFwdLocked() {
6657 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
6658 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006659 }
6660
6661 class FileInstallArgs extends InstallArgs {
6662 File installDir;
6663 String codeFileName;
6664 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07006665 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006666 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006667
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006668 FileInstallArgs(InstallParams params) {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006669 super(params.getPackageUri(), params.observer, params.flags,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006670 params.installerPackageName, params.getManifestDigest(),
6671 params.getUser());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006672 }
6673
Kenny Root85387d72010-08-26 10:13:11 -07006674 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006675 super(null, null, 0, null, null, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006676 File codeFile = new File(fullCodePath);
6677 installDir = codeFile.getParentFile();
6678 codeFileName = fullCodePath;
6679 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07006680 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006681 }
6682
Kenny Root85387d72010-08-26 10:13:11 -07006683 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006684 super(packageURI, null, 0, null, null, null);
Kenny Root85387d72010-08-26 10:13:11 -07006685 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006686 String apkName = getNextCodePath(null, pkgName, ".apk");
6687 codeFileName = new File(installDir, apkName + ".apk").getPath();
6688 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07006689 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006690 }
6691
Kenny Root11128572010-10-11 10:51:32 -07006692 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
Kenny Root62e1b4e2011-03-14 17:13:39 -07006693 final long lowThreshold;
6694
6695 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
6696 .getService(DeviceStorageMonitorService.SERVICE);
6697 if (dsm == null) {
6698 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
6699 lowThreshold = 0L;
6700 } else {
6701 if (dsm.isMemoryLow()) {
6702 Log.w(TAG, "Memory is reported as being too low; aborting package install");
6703 return false;
6704 }
6705
6706 lowThreshold = dsm.getMemoryLowThreshold();
6707 }
6708
Kenny Root11128572010-10-11 10:51:32 -07006709 try {
6710 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
6711 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root6dceb882012-04-12 14:23:49 -07006712 return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
Kenny Root11128572010-10-11 10:51:32 -07006713 } finally {
6714 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
6715 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006716 }
6717
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006718 String getCodePath() {
6719 return codeFileName;
6720 }
6721
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006722 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07006723 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006724 codeFileName = createTempPackageFile(installDir).getPath();
6725 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006726 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006727 }
6728
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006729 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006730 if (temp) {
6731 // Generate temp file name
6732 createCopyFile();
6733 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006734 // Get a ParcelFileDescriptor to write to the output file
6735 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006736 if (!created) {
6737 try {
6738 codeFile.createNewFile();
6739 // Set permissions
6740 if (!setPermissions()) {
6741 // Failed setting permissions.
6742 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6743 }
6744 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006745 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006746 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6747 }
6748 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006749 ParcelFileDescriptor out = null;
6750 try {
Kenny Root85387d72010-08-26 10:13:11 -07006751 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006752 } catch (FileNotFoundException e) {
Kenny Rootf5121a92011-08-10 16:23:32 -07006753 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006754 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6755 }
6756 // Copy the resource now
6757 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6758 try {
Kenny Root11128572010-10-11 10:51:32 -07006759 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
6760 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006761 ret = imcs.copyResource(packageURI, null, out);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006762 } finally {
Kenny Root2782a472012-04-14 21:48:21 -07006763 IoUtils.closeQuietly(out);
Kenny Root11128572010-10-11 10:51:32 -07006764 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006765 }
Kenny Root85387d72010-08-26 10:13:11 -07006766
Kenny Root2782a472012-04-14 21:48:21 -07006767 if (isFwdLocked()) {
6768 final File destResourceFile = new File(getResourcePath());
6769
6770 // Copy the public files
6771 try {
6772 PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
6773 } catch (IOException e) {
6774 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
6775 + " forward-locked app.");
6776 destResourceFile.delete();
6777 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6778 }
6779 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006780 return ret;
6781 }
6782
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006783 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006784 if (status != PackageManager.INSTALL_SUCCEEDED) {
6785 cleanUp();
6786 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006787 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006788 }
6789
6790 boolean doRename(int status, final String pkgName, String oldCodePath) {
6791 if (status != PackageManager.INSTALL_SUCCEEDED) {
6792 cleanUp();
6793 return false;
6794 } else {
Kenny Root2782a472012-04-14 21:48:21 -07006795 final File oldCodeFile = new File(getCodePath());
6796 final File oldResourceFile = new File(getResourcePath());
6797
6798 // Rename APK file based on packageName
6799 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
6800 final File newCodeFile = new File(installDir, apkName + ".apk");
6801 if (!oldCodeFile.renameTo(newCodeFile)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006802 return false;
6803 }
Kenny Root2782a472012-04-14 21:48:21 -07006804 codeFileName = newCodeFile.getPath();
6805
6806 // Rename public resource file if it's forward-locked.
6807 final File newResFile = new File(getResourcePathFromCodePath());
6808 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
6809 return false;
6810 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006811 resourceFileName = getResourcePathFromCodePath();
Kenny Root2782a472012-04-14 21:48:21 -07006812
6813 // Attempt to set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006814 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006815 return false;
6816 }
Kenny Root2782a472012-04-14 21:48:21 -07006817
rpcraig554cb0c2012-07-05 06:41:43 -04006818 if (!SELinux.restorecon(newCodeFile)) {
6819 return false;
6820 }
6821
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006822 return true;
6823 }
6824 }
6825
Kenny Root6dceb882012-04-12 14:23:49 -07006826 int doPostInstall(int status, int uid) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006827 if (status != PackageManager.INSTALL_SUCCEEDED) {
6828 cleanUp();
6829 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006830 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006831 }
6832
6833 String getResourcePath() {
6834 return resourceFileName;
6835 }
6836
Kenny Root2782a472012-04-14 21:48:21 -07006837 private String getResourcePathFromCodePath() {
6838 final String codePath = getCodePath();
6839 if (isFwdLocked()) {
6840 final StringBuilder sb = new StringBuilder();
6841
6842 sb.append(mAppInstallDir.getPath());
6843 sb.append('/');
6844 sb.append(getApkName(codePath));
6845 sb.append(".zip");
6846
6847 /*
6848 * If our APK is a temporary file, mark the resource as a
6849 * temporary file as well so it can be cleaned up after
6850 * catastrophic failure.
6851 */
6852 if (codePath.endsWith(".tmp")) {
6853 sb.append(".tmp");
6854 }
6855
6856 return sb.toString();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006857 } else {
6858 return codePath;
6859 }
6860 }
6861
Kenny Root85387d72010-08-26 10:13:11 -07006862 @Override
6863 String getNativeLibraryPath() {
6864 return libraryPath;
6865 }
6866
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006867 private boolean cleanUp() {
6868 boolean ret = true;
6869 String sourceDir = getCodePath();
6870 String publicSourceDir = getResourcePath();
6871 if (sourceDir != null) {
6872 File sourceFile = new File(sourceDir);
6873 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006874 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006875 ret = false;
6876 }
6877 // Delete application's code and resources
6878 sourceFile.delete();
6879 }
6880 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
6881 final File publicSourceFile = new File(publicSourceDir);
6882 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006883 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006884 }
6885 if (publicSourceFile.exists()) {
6886 publicSourceFile.delete();
6887 }
6888 }
6889 return ret;
6890 }
6891
6892 void cleanUpResourcesLI() {
6893 String sourceDir = getCodePath();
Jeff Brown5d6d90f2011-07-11 13:04:53 -07006894 if (cleanUp()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006895 int retCode = mInstaller.rmdex(sourceDir);
6896 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006897 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006898 + " at location "
6899 + sourceDir + ", retcode=" + retCode);
6900 // we don't consider this to be a failure of the core package deletion
6901 }
6902 }
6903 }
6904
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006905 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006906 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07006907 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006908 final int filePermissions =
6909 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
6910 |FileUtils.S_IROTH;
6911 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
6912 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006913 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006914 getCodePath()
6915 + ". The return code was: " + retCode);
6916 // TODO Define new internal error
6917 return false;
6918 }
6919 return true;
6920 }
6921 return true;
6922 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006923
6924 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07006925 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006926 cleanUpResourcesLI();
6927 return true;
6928 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006929 }
6930
Kenny Root51a573c2012-05-17 13:30:28 -07006931 private boolean isAsecExternal(String cid) {
6932 final String asecPath = PackageHelper.getSdFilesystem(cid);
6933 return !asecPath.startsWith(mAsecInternalPath);
6934 }
6935
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07006936 /**
6937 * Extract the MountService "container ID" from the full code path of an
6938 * .apk.
6939 */
6940 static String cidFromCodePath(String fullCodePath) {
6941 int eidx = fullCodePath.lastIndexOf("/");
6942 String subStr1 = fullCodePath.substring(0, eidx);
6943 int sidx = subStr1.lastIndexOf("/");
6944 return subStr1.substring(sidx+1, eidx);
6945 }
6946
Kenny Root6dceb882012-04-12 14:23:49 -07006947 class AsecInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006948 static final String RES_FILE_NAME = "pkg.apk";
Kenny Root6dceb882012-04-12 14:23:49 -07006949 static final String PUBLIC_RES_FILE_NAME = "res.zip";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006950
Kenny Root85387d72010-08-26 10:13:11 -07006951 String cid;
6952 String packagePath;
Kenny Root6dceb882012-04-12 14:23:49 -07006953 String resourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07006954 String libraryPath;
6955
Kenny Root6dceb882012-04-12 14:23:49 -07006956 AsecInstallArgs(InstallParams params) {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006957 super(params.getPackageUri(), params.observer, params.flags,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006958 params.installerPackageName, params.getManifestDigest(),
6959 params.getUser());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006960 }
6961
Kenny Root6dceb882012-04-12 14:23:49 -07006962 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
Kenny Rootbf023582012-05-02 16:56:15 -07006963 boolean isExternal, boolean isForwardLocked) {
6964 super(null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006965 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
6966 null, null, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006967 // Extract cid from fullCodePath
6968 int eidx = fullCodePath.lastIndexOf("/");
6969 String subStr1 = fullCodePath.substring(0, eidx);
6970 int sidx = subStr1.lastIndexOf("/");
6971 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07006972 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006973 }
6974
Kenny Rootc7a89992012-06-05 15:13:17 -07006975 AsecInstallArgs(String cid, boolean isForwardLocked) {
6976 super(null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006977 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
6978 null, null, null);
Dianne Hackbornaa77de12010-05-14 22:33:54 -07006979 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07006980 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006981 }
6982
Kenny Rootbf023582012-05-02 16:56:15 -07006983 AsecInstallArgs(Uri packageURI, String cid, boolean isExternal, boolean isForwardLocked) {
6984 super(packageURI, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006985 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
6986 null, null, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006987 this.cid = cid;
6988 }
6989
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006990 void createCopyFile() {
6991 cid = getTempContainerId();
6992 }
6993
Kenny Root11128572010-10-11 10:51:32 -07006994 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
6995 try {
6996 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
6997 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root6dceb882012-04-12 14:23:49 -07006998 return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
Kenny Root11128572010-10-11 10:51:32 -07006999 } finally {
7000 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
7001 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08007002 }
7003
Kenny Root6dceb882012-04-12 14:23:49 -07007004 private final boolean isExternal() {
7005 return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
7006 }
7007
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007008 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007009 if (temp) {
7010 createCopyFile();
Kenny Rootf5121a92011-08-10 16:23:32 -07007011 } else {
7012 /*
7013 * Pre-emptively destroy the container since it's destroyed if
7014 * copying fails due to it existing anyway.
7015 */
7016 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007017 }
Kenny Root11128572010-10-11 10:51:32 -07007018
7019 final String newCachePath;
7020 try {
7021 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
7022 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root6dceb882012-04-12 14:23:49 -07007023 newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
7024 RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
Kenny Root11128572010-10-11 10:51:32 -07007025 } finally {
7026 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
7027 }
7028
Kenny Root85387d72010-08-26 10:13:11 -07007029 if (newCachePath != null) {
7030 setCachePath(newCachePath);
7031 return PackageManager.INSTALL_SUCCEEDED;
7032 } else {
7033 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7034 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007035 }
7036
7037 @Override
7038 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07007039 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007040 }
7041
7042 @Override
7043 String getResourcePath() {
Kenny Root6dceb882012-04-12 14:23:49 -07007044 return resourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07007045 }
7046
7047 @Override
7048 String getNativeLibraryPath() {
7049 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007050 }
7051
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007052 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007053 if (status != PackageManager.INSTALL_SUCCEEDED) {
7054 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08007055 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007056 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08007057 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007058 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07007059 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
7060 Process.SYSTEM_UID);
7061 if (newCachePath != null) {
7062 setCachePath(newCachePath);
7063 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007064 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7065 }
7066 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007067 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007068 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007069 }
7070
7071 boolean doRename(int status, final String pkgName,
7072 String oldCodePath) {
7073 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007074 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007075 if (PackageHelper.isContainerMounted(cid)) {
7076 // Unmount the container
7077 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007078 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007079 return false;
7080 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007081 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007082 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07007083 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
7084 " which might be stale. Will try to clean up.");
7085 // Clean up the stale container and proceed to recreate.
7086 if (!PackageHelper.destroySdDir(newCacheId)) {
7087 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
7088 return false;
7089 }
7090 // Successfully cleaned up stale container. Try to rename again.
7091 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
7092 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
7093 + " inspite of cleaning it up.");
7094 return false;
7095 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007096 }
7097 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007098 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007099 newCachePath = PackageHelper.mountSdDir(newCacheId,
7100 getEncryptKey(), Process.SYSTEM_UID);
7101 } else {
7102 newCachePath = PackageHelper.getSdDir(newCacheId);
7103 }
7104 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007105 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007106 return false;
7107 }
7108 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07007109 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007110 " at new path: " + newCachePath);
7111 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07007112 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007113 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007114 }
7115
Kenny Root85387d72010-08-26 10:13:11 -07007116 private void setCachePath(String newCachePath) {
7117 File cachePath = new File(newCachePath);
7118 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
7119 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
Kenny Root6dceb882012-04-12 14:23:49 -07007120
7121 if (isFwdLocked()) {
7122 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
7123 } else {
7124 resourcePath = packagePath;
7125 }
Kenny Root85387d72010-08-26 10:13:11 -07007126 }
7127
Kenny Root6dceb882012-04-12 14:23:49 -07007128 int doPostInstall(int status, int uid) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007129 if (status != PackageManager.INSTALL_SUCCEEDED) {
7130 cleanUp();
7131 } else {
Kenny Rootbf023582012-05-02 16:56:15 -07007132 final int groupOwner;
7133 final String protectedFile;
7134 if (isFwdLocked()) {
7135 groupOwner = uid;
7136 protectedFile = RES_FILE_NAME;
7137 } else {
7138 groupOwner = -1;
7139 protectedFile = null;
7140 }
7141
Kenny Root6dceb882012-04-12 14:23:49 -07007142 if (uid < Process.FIRST_APPLICATION_UID
Kenny Rootbf023582012-05-02 16:56:15 -07007143 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
Kenny Root6dceb882012-04-12 14:23:49 -07007144 Slog.e(TAG, "Failed to finalize " + cid);
7145 PackageHelper.destroySdDir(cid);
7146 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7147 }
7148
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08007149 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007150 if (!mounted) {
Kenny Root6dceb882012-04-12 14:23:49 -07007151 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007152 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007153 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007154 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007155 }
7156
7157 private void cleanUp() {
Kenny Root6dceb882012-04-12 14:23:49 -07007158 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
7159
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007160 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08007161 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007162 }
7163
7164 void cleanUpResourcesLI() {
7165 String sourceFile = getCodePath();
7166 // Remove dex file
Jeff Brown5d6d90f2011-07-11 13:04:53 -07007167 int retCode = mInstaller.rmdex(sourceFile);
7168 if (retCode < 0) {
7169 Slog.w(TAG, "Couldn't remove dex file for package: "
7170 + " at location "
7171 + sourceFile.toString() + ", retcode=" + retCode);
7172 // we don't consider this to be a failure of the core package deletion
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007173 }
7174 cleanUp();
7175 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007176
7177 boolean matchContainer(String app) {
7178 if (cid.startsWith(app)) {
7179 return true;
7180 }
7181 return false;
7182 }
7183
7184 String getPackageName() {
Kenny Rootc7a89992012-06-05 15:13:17 -07007185 return getAsecPackageName(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007186 }
7187
7188 boolean doPostDeleteLI(boolean delete) {
7189 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08007190 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007191 if (mounted) {
7192 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08007193 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007194 }
7195 if (ret && delete) {
7196 cleanUpResourcesLI();
7197 }
7198 return ret;
7199 }
Kenny Rootbf023582012-05-02 16:56:15 -07007200
7201 @Override
7202 int doPreCopy() {
7203 if (isFwdLocked()) {
7204 if (!PackageHelper.fixSdPermissions(cid,
7205 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
7206 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7207 }
7208 }
7209
7210 return PackageManager.INSTALL_SUCCEEDED;
7211 }
7212
7213 @Override
7214 int doPostCopy(int uid) {
7215 if (isFwdLocked()) {
Kenny Rootbf023582012-05-02 16:56:15 -07007216 if (uid < Process.FIRST_APPLICATION_UID
7217 || !PackageHelper.fixSdPermissions(cid, uid, RES_FILE_NAME)) {
7218 Slog.e(TAG, "Failed to finalize " + cid);
7219 PackageHelper.destroySdDir(cid);
7220 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7221 }
7222 }
7223
7224 return PackageManager.INSTALL_SUCCEEDED;
7225 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007226 };
7227
Kenny Rootc7a89992012-06-05 15:13:17 -07007228 static String getAsecPackageName(String packageCid) {
7229 int idx = packageCid.lastIndexOf("-");
7230 if (idx == -1) {
7231 return packageCid;
7232 }
7233 return packageCid.substring(0, idx);
7234 }
7235
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007236 // Utility method used to create code paths based on package name and available index.
7237 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
7238 String idxStr = "";
7239 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007240 // Fall back to default value of idx=1 if prefix is not
7241 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007242 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00007243 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007244 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00007245 if (subStr.endsWith(suffix)) {
7246 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007247 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007248 // If oldCodePath already contains prefix find out the
7249 // ending index to either increment or decrement.
7250 int sidx = subStr.lastIndexOf(prefix);
7251 if (sidx != -1) {
7252 subStr = subStr.substring(sidx + prefix.length());
7253 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007254 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
7255 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007256 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007257 try {
7258 idx = Integer.parseInt(subStr);
7259 if (idx <= 1) {
7260 idx++;
7261 } else {
7262 idx--;
7263 }
7264 } catch(NumberFormatException e) {
7265 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007266 }
7267 }
7268 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007269 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007270 return prefix + idxStr;
7271 }
7272
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007273 // Utility method used to ignore ADD/REMOVE events
7274 // by directory observer.
7275 private static boolean ignoreCodePath(String fullPathStr) {
7276 String apkName = getApkName(fullPathStr);
7277 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
7278 if (idx != -1 && ((idx+1) < apkName.length())) {
7279 // Make sure the package ends with a numeral
7280 String version = apkName.substring(idx+1);
7281 try {
7282 Integer.parseInt(version);
7283 return true;
7284 } catch (NumberFormatException e) {}
7285 }
7286 return false;
7287 }
7288
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007289 // Utility method that returns the relative package path with respect
7290 // to the installation directory. Like say for /data/data/com.test-1.apk
7291 // string com.test-1 is returned.
7292 static String getApkName(String codePath) {
7293 if (codePath == null) {
7294 return null;
7295 }
7296 int sidx = codePath.lastIndexOf("/");
7297 int eidx = codePath.lastIndexOf(".");
7298 if (eidx == -1) {
7299 eidx = codePath.length();
7300 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007301 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007302 return null;
7303 }
7304 return codePath.substring(sidx+1, eidx);
7305 }
7306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007307 class PackageInstalledInfo {
7308 String name;
7309 int uid;
Dianne Hackborn786b4402012-08-27 15:14:02 -07007310 // The set of users that originally had this package installed.
7311 int[] origUsers;
7312 // The set of users that now have this package installed.
7313 int[] newUsers;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007314 PackageParser.Package pkg;
7315 int returnCode;
7316 PackageRemovedInfo removedInfo;
7317 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007319 /*
7320 * Install a non-existing package.
7321 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007322 private void installNewPackageLI(PackageParser.Package pkg,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007323 int parseFlags, int scanMode, UserHandle user,
Jacek Surazski65e13172009-04-28 15:26:38 +02007324 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007325 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007326 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08007327
Amith Yamasani0b285492011-04-14 17:35:23 -07007328 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007329 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07007330 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
7331 // A package with the same name is already installed, though
7332 // it has been renamed to an older name. The package we
7333 // are trying to install should be installed as an update to
7334 // the existing one, but that has not been requested, so bail.
7335 Slog.w(TAG, "Attempt to re-install " + pkgName
7336 + " without first uninstalling package running as "
7337 + mSettings.mRenamedPackages.get(pkgName));
7338 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
7339 return;
7340 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007341 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007342 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007343 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007344 + " without first uninstalling.");
7345 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
7346 return;
7347 }
7348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007349 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007350 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007351 System.currentTimeMillis(), user);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007352 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007353 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007354 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
7355 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
7356 }
7357 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007358 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02007359 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007360 res);
7361 // delete the partially installed application. the data directory will have to be
7362 // restored if it was already existing
7363 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
7364 // remove package from internal structures. Note that we want deletePackageX to
7365 // delete the package data and cache directories that it created in
7366 // scanPackageLocked, unless those directories existed before we even tried to
7367 // install.
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007368 deletePackageLI(pkgName, UserHandle.ALL, false,
7369 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007370 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007371 }
7372 }
7373 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007374
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007375 private void replacePackageLI(PackageParser.Package pkg,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007376 int parseFlags, int scanMode, UserHandle user,
Jacek Surazski65e13172009-04-28 15:26:38 +02007377 String installerPackageName, PackageInstalledInfo res) {
7378
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007379 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007380 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007381 // First find the old package info and check signatures
7382 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007383 oldPackage = mPackages.get(pkgName);
Kenny Root447106f2011-03-23 11:00:15 -07007384 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07007385 != PackageManager.SIGNATURE_MATCH) {
Kenny Root8c11f1d2012-04-14 12:10:38 -07007386 Slog.w(TAG, "New package has a different signature: " + pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007387 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
7388 return;
7389 }
7390 }
Kenny Root85387d72010-08-26 10:13:11 -07007391 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007392 if (sysPkg) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007393 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
7394 user, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007395 } else {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007396 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
7397 user, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007398 }
7399 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007401 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007402 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
Jacek Surazski65e13172009-04-28 15:26:38 +02007403 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007404 PackageParser.Package newPackage = null;
7405 String pkgName = deletedPackage.packageName;
7406 boolean deletedPkg = true;
7407 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007408
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007409 long origUpdateTime;
7410 if (pkg.mExtras != null) {
7411 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
7412 } else {
7413 origUpdateTime = 0;
7414 }
7415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007416 // First delete the existing package while retaining the data directory
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007417 if (!deletePackageLI(pkgName, null, true, PackageManager.DELETE_KEEP_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007418 res.removedInfo, true)) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007419 // If the existing package wasn't successfully deleted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007420 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
7421 deletedPkg = false;
7422 } else {
7423 // Successfully deleted the old package. Now proceed with re-installation
7424 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007425 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007426 System.currentTimeMillis(), user);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007427 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007428 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007429 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
7430 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08007431 }
7432 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007433 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02007434 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007435 res);
7436 updatedSettings = true;
7437 }
7438 }
7439
Suchi Amalapurapuae181712010-03-30 14:01:02 -07007440 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007441 // remove package from internal structures. Note that we want deletePackageX to
7442 // delete the package data and cache directories that it created in
7443 // scanPackageLocked, unless those directories existed before we even tried to
7444 // install.
7445 if(updatedSettings) {
7446 deletePackageLI(
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007447 pkgName, null, true,
7448 PackageManager.DELETE_KEEP_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007449 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007450 }
7451 // Since we failed to install the new package we need to restore the old
7452 // package that we deleted.
7453 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07007454 File restoreFile = new File(deletedPackage.mPath);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007455 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07007456 boolean oldOnSd = isExternal(deletedPackage);
7457 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
7458 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
7459 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007460 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
7461 | SCAN_UPDATE_TIME;
7462 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
Dianne Hackborn786b4402012-08-27 15:14:02 -07007463 origUpdateTime, null) == null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07007464 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
7465 return;
7466 }
7467 // Restore of old package succeeded. Update permissions.
Kenny Root447106f2011-03-23 11:00:15 -07007468 // writer
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007469 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07007470 updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
Dianne Hackborne639da72012-02-21 15:11:13 -08007471 UPDATE_PERMISSIONS_ALL);
Kenny Root447106f2011-03-23 11:00:15 -07007472 // can downgrade to reader
7473 mSettings.writeLPr();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007474 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07007475 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007476 }
7477 }
7478 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007480 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007481 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
Jacek Surazski65e13172009-04-28 15:26:38 +02007482 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007483 PackageParser.Package newPackage = null;
7484 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007485 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007486 PackageParser.PARSE_IS_SYSTEM;
7487 String packageName = deletedPackage.packageName;
7488 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
7489 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007490 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007491 return;
7492 }
7493 PackageParser.Package oldPkg;
7494 PackageSetting oldPkgSetting;
Kenny Root447106f2011-03-23 11:00:15 -07007495 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007496 synchronized (mPackages) {
7497 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007498 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007499 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
7500 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007501 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007502 return;
7503 }
7504 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007505
7506 killApplication(packageName, oldPkg.applicationInfo.uid);
7507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007508 res.removedInfo.uid = oldPkg.applicationInfo.uid;
7509 res.removedInfo.removedPackage = packageName;
7510 // Remove existing system package
7511 removePackageLI(oldPkg, true);
Kenny Root447106f2011-03-23 11:00:15 -07007512 // writer
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08007513 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07007514 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007515 // We didn't need to disable the .apk as a current system package,
7516 // which means we are replacing another update that is already
7517 // installed. We need to make sure to delete the older one's .apk.
Kenny Root6dceb882012-04-12 14:23:49 -07007518 res.removedInfo.args = createInstallArgs(0,
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007519 deletedPackage.applicationInfo.sourceDir,
7520 deletedPackage.applicationInfo.publicSourceDir,
7521 deletedPackage.applicationInfo.nativeLibraryDir);
7522 } else {
7523 res.removedInfo.args = null;
7524 }
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08007525 }
7526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007527 // Successfully disabled the old package. Now proceed with re-installation
7528 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
7529 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007530 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007531 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007532 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007533 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
7534 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
7535 }
7536 } else {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007537 if (newPackage.mExtras != null) {
7538 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
7539 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
7540 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
7541 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007542 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007543 updatedSettings = true;
7544 }
7545
Suchi Amalapurapuae181712010-03-30 14:01:02 -07007546 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007547 // Re installation failed. Restore old information
7548 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07007549 if (newPackage != null) {
7550 removePackageLI(newPackage, true);
7551 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007552 // Add back the old system package
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007553 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007554 // Restore the old system information in Settings
7555 synchronized(mPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007556 if (updatedSettings) {
Kenny Root447106f2011-03-23 11:00:15 -07007557 mSettings.enableSystemPackageLPw(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02007558 mSettings.setInstallerPackageName(packageName,
7559 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007560 }
Kenny Root447106f2011-03-23 11:00:15 -07007561 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007562 }
7563 }
7564 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007565
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007566 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07007567 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007568 int retCode;
7569 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
7570 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
7571 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07007572 if (mNoDexOpt) {
7573 /*
7574 * If we're in an engineering build, programs are lazily run
7575 * through dexopt. If the .dex file doesn't exist yet, it
7576 * will be created when the program is run next.
7577 */
7578 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
7579 } else {
7580 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
7581 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7582 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007583 }
7584 }
7585 return PackageManager.INSTALL_SUCCEEDED;
7586 }
7587
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007588 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02007589 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007590 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007591 synchronized (mPackages) {
7592 //write settings. the installStatus will be incomplete at this stage.
7593 //note that the new package setting would have already been
7594 //added to mPackages. It hasn't been persisted yet.
Kenny Rootcf0b38c2011-03-22 14:17:59 -07007595 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
Kenny Root447106f2011-03-23 11:00:15 -07007596 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007597 }
7598
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07007599 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007600 != PackageManager.INSTALL_SUCCEEDED) {
7601 // Discontinue if moving dex files failed.
7602 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007603 }
Kenny Root6dceb882012-04-12 14:23:49 -07007604
7605 Log.d(TAG, "New package installed in " + newPackage.mPath);
7606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007607 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07007608 updatePermissionsLPw(newPackage.packageName, newPackage,
Dianne Hackborne639da72012-02-21 15:11:13 -08007609 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
7610 ? UPDATE_PERMISSIONS_ALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007611 res.name = pkgName;
7612 res.uid = newPackage.applicationInfo.uid;
7613 res.pkg = newPackage;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07007614 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02007615 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007616 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
7617 //to update install status
Kenny Root447106f2011-03-23 11:00:15 -07007618 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007619 }
7620 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007621
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007622 private void installPackageLI(InstallArgs args,
7623 boolean newInstall, PackageInstalledInfo res) {
7624 int pFlags = args.flags;
7625 String installerPackageName = args.installerPackageName;
7626 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007627 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08007628 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007629 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07007630 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007631 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07007632 // Result object to be returned
7633 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
7634
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007635 // Retrieve PackageSettings and parse package
Kenny Root6dceb882012-04-12 14:23:49 -07007636 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
7637 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
7638 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007639 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
7640 pp.setSeparateProcesses(mSeparateProcesses);
7641 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
7642 null, mMetrics, parseFlags);
7643 if (pkg == null) {
7644 res.returnCode = pp.getParseError();
7645 return;
7646 }
7647 String pkgName = res.name = pkg.packageName;
7648 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
7649 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
7650 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
7651 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007652 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007653 }
7654 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
7655 res.returnCode = pp.getParseError();
7656 return;
7657 }
Kenny Root5ab21572011-07-27 11:11:19 -07007658
7659 /* If the installer passed in a manifest digest, compare it now. */
7660 if (args.manifestDigest != null) {
7661 if (DEBUG_INSTALL) {
7662 final String parsedManifest = pkg.manifestDigest == null ? "null"
7663 : pkg.manifestDigest.toString();
7664 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
7665 + parsedManifest);
7666 }
7667
7668 if (!args.manifestDigest.equals(pkg.manifestDigest)) {
7669 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
7670 return;
7671 }
7672 } else if (DEBUG_INSTALL) {
7673 final String parsedManifest = pkg.manifestDigest == null
7674 ? "null" : pkg.manifestDigest.toString();
7675 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
7676 }
7677
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007678 // Get rid of all references to package scan path via parser.
7679 pp = null;
7680 String oldCodePath = null;
7681 boolean systemApp = false;
7682 synchronized (mPackages) {
7683 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007684 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
7685 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08007686 if (pkg.mOriginalPackages != null
7687 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007688 && mPackages.containsKey(oldName)) {
7689 // This package is derived from an original package,
7690 // and this device has been updating from that original
7691 // name. We must continue using the original name, so
7692 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08007693 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007694 pkgName = pkg.packageName;
7695 replace = true;
7696 } else if (mPackages.containsKey(pkgName)) {
7697 // This package, under its official name, already exists
7698 // on the device; we should replace it.
7699 replace = true;
7700 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007701 }
7702 PackageSetting ps = mSettings.mPackages.get(pkgName);
7703 if (ps != null) {
7704 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
7705 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7706 systemApp = (ps.pkg.applicationInfo.flags &
7707 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07007708 }
Dianne Hackborn786b4402012-08-27 15:14:02 -07007709 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
Dianne Hackbornade3eca2009-05-11 18:54:45 -07007710 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007711 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007712
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007713 if (systemApp && onSd) {
7714 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007715 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007716 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
7717 return;
7718 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08007719
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007720 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
7721 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7722 return;
7723 }
7724 // Set application objects path explicitly after the rename
7725 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07007726 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007727 if (replace) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007728 replacePackageLI(pkg, parseFlags, scanMode, args.user,
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08007729 installerPackageName, res);
7730 } else {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007731 installNewPackageLI(pkg, parseFlags, scanMode, args.user,
Dianne Hackborn786b4402012-08-27 15:14:02 -07007732 installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007733 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007734 synchronized (mPackages) {
Dianne Hackborn786b4402012-08-27 15:14:02 -07007735 final PackageSetting ps = mSettings.mPackages.get(pkgName);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007736 if (ps != null) {
Dianne Hackborn786b4402012-08-27 15:14:02 -07007737 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007738 }
7739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007741
Kenny Root85387d72010-08-26 10:13:11 -07007742 private static boolean isForwardLocked(PackageParser.Package pkg) {
7743 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007744 }
7745
Kenny Root88670d82012-05-09 15:47:35 -07007746
7747 private boolean isForwardLocked(PackageSetting ps) {
7748 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
7749 }
7750
Kenny Root85387d72010-08-26 10:13:11 -07007751 private static boolean isExternal(PackageParser.Package pkg) {
7752 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
7753 }
7754
Kenny Root6dceb882012-04-12 14:23:49 -07007755 private static boolean isExternal(PackageSetting ps) {
7756 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
7757 }
7758
Kenny Root85387d72010-08-26 10:13:11 -07007759 private static boolean isSystemApp(PackageParser.Package pkg) {
7760 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7761 }
7762
Kenny Root502e9a42011-01-10 13:48:15 -08007763 private static boolean isSystemApp(ApplicationInfo info) {
7764 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7765 }
7766
Kenny Root208d3412012-05-07 19:42:35 -07007767 private static boolean isSystemApp(PackageSetting ps) {
7768 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
7769 }
7770
Kenny Root85387d72010-08-26 10:13:11 -07007771 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
7772 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07007773 }
7774
Kenny Root88670d82012-05-09 15:47:35 -07007775 private int packageFlagsToInstallFlags(PackageSetting ps) {
7776 int installFlags = 0;
7777 if (isExternal(ps)) {
7778 installFlags |= PackageManager.INSTALL_EXTERNAL;
7779 }
7780 if (isForwardLocked(ps)) {
7781 installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
7782 }
7783 return installFlags;
7784 }
7785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007786 private void deleteTempPackageFiles() {
7787 FilenameFilter filter = new FilenameFilter() {
7788 public boolean accept(File dir, String name) {
7789 return name.startsWith("vmdl") && name.endsWith(".tmp");
7790 }
7791 };
7792 String tmpFilesList[] = mAppInstallDir.list(filter);
7793 if(tmpFilesList == null) {
7794 return;
7795 }
7796 for(int i = 0; i < tmpFilesList.length; i++) {
7797 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
7798 tmpFile.delete();
7799 }
7800 }
7801
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007802 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007803 File tmpPackageFile;
7804 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007805 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007806 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007807 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007808 return null;
7809 }
7810 try {
7811 FileUtils.setPermissions(
7812 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
7813 -1, -1);
rpcraig554cb0c2012-07-05 06:41:43 -04007814 if (!SELinux.restorecon(tmpPackageFile)) {
7815 return null;
7816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007817 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007818 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007819 return null;
7820 }
7821 return tmpPackageFile;
7822 }
7823
7824 public void deletePackage(final String packageName,
7825 final IPackageDeleteObserver observer,
7826 final int flags) {
7827 mContext.enforceCallingOrSelfPermission(
7828 android.Manifest.permission.DELETE_PACKAGES, null);
7829 // Queue up an async operation since the package deletion may take a little while.
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007830 final int uid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007831 mHandler.post(new Runnable() {
7832 public void run() {
7833 mHandler.removeCallbacks(this);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007834 final int returnCode = deletePackageX(packageName, uid, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007835 if (observer != null) {
7836 try {
Kenny Rootc39bb4a2011-02-28 13:27:19 -08007837 observer.packageDeleted(packageName, returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007838 } catch (RemoteException e) {
7839 Log.i(TAG, "Observer no longer exists.");
7840 } //end catch
7841 } //end if
7842 } //end run
7843 });
7844 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007846 /**
7847 * This method is an internal method that could be get invoked either
7848 * to delete an installed package or to clean up a failed installation.
7849 * After deleting an installed package, a broadcast is sent to notify any
7850 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007851 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007852 * installation wouldn't have sent the initial broadcast either
7853 * The key steps in deleting a package are
7854 * deleting the package information in internal structures like mPackages,
7855 * deleting the packages base directories through installd
7856 * updating mSettings to reflect current status
7857 * persisting settings for later use
7858 * sending a broadcast if necessary
7859 */
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007860 private int deletePackageX(String packageName, int uid, int flags) {
Kenny Rootc39bb4a2011-02-28 13:27:19 -08007861 final PackageRemovedInfo info = new PackageRemovedInfo();
7862 final boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007863
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007864 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
7865 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
7866 try {
7867 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007868 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Kenny Rootc39bb4a2011-02-28 13:27:19 -08007869 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007870 }
7871 } catch (RemoteException e) {
7872 }
7873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007874 synchronized (mInstallLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007875 res = deletePackageLI(packageName,
7876 (flags & PackageManager.DELETE_ALL_USERS) != 0
7877 ? UserHandle.ALL : new UserHandle(UserHandle.getUserId(uid)),
7878 true, flags | REMOVE_CHATTY, info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007879 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007880
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007881 if (res) {
Romain Guy96f43572009-03-24 20:27:49 -07007882 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007883 info.sendBroadcast(true, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07007884
7885 // If the removed package was a system update, the old system packaged
7886 // was re-enabled; we need to broadcast this information
7887 if (systemUpdate) {
7888 Bundle extras = new Bundle(1);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007889 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
7890 ? info.removedAppId : info.uid);
Romain Guy96f43572009-03-24 20:27:49 -07007891 extras.putBoolean(Intent.EXTRA_REPLACING, true);
7892
Dianne Hackborne7f97212011-02-24 14:40:20 -08007893 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007894 extras, null, null, null);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007895 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007896 extras, null, null, null);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007897 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007898 null, packageName, null, null);
Romain Guy96f43572009-03-24 20:27:49 -07007899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007900 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07007901 // Force a gc here.
7902 Runtime.getRuntime().gc();
7903 // Delete the resources here after sending the broadcast to let
7904 // other processes clean up before deleting resources.
7905 if (info.args != null) {
7906 synchronized (mInstallLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007907 info.args.doPostDeleteLI(true);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07007908 }
7909 }
Kenny Rootc39bb4a2011-02-28 13:27:19 -08007910
7911 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007912 }
7913
7914 static class PackageRemovedInfo {
7915 String removedPackage;
7916 int uid = -1;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007917 int removedAppId = -1;
7918 int[] removedUsers = null;
Romain Guy96f43572009-03-24 20:27:49 -07007919 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007920 // Clean up resources deleted packages.
7921 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07007922
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07007923 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007924 Bundle extras = new Bundle(1);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007925 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007926 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
7927 if (replacing) {
7928 extras.putBoolean(Intent.EXTRA_REPLACING, true);
7929 }
7930 if (removedPackage != null) {
Dianne Hackborne7f97212011-02-24 14:40:20 -08007931 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007932 extras, null, null, removedUsers);
Dianne Hackbornf9abb402011-08-10 15:00:59 -07007933 if (fullRemove && !replacing) {
7934 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007935 extras, null, null, removedUsers);
Dianne Hackbornf9abb402011-08-10 15:00:59 -07007936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007937 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007938 if (removedAppId >= 0) {
Amith Yamasani13593602012-03-22 16:16:17 -07007939 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007940 removedUsers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007941 }
7942 }
7943 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007945 /*
7946 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
7947 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007948 * 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 -08007949 * delete a partially installed application.
7950 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007951 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007952 int flags, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007953 String packageName = p.packageName;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07007954 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007955 // Retrieve object to delete permissions for shared user later on
Kenny Root447106f2011-03-23 11:00:15 -07007956 final PackageSetting deletedPs;
7957 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007958 synchronized (mPackages) {
7959 deletedPs = mSettings.mPackages.get(packageName);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007960 if (outInfo != null) {
7961 outInfo.removedPackage = packageName;
7962 outInfo.removedUsers = deletedPs != null
Dianne Hackborn786b4402012-08-27 15:14:02 -07007963 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
7964 : null;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007966 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007967 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07007968 removeDataDirsLI(packageName);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007969 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007970 }
Kenny Root447106f2011-03-23 11:00:15 -07007971 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007972 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007973 if (deletedPs != null) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007974 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007975 if (outInfo != null) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007976 outInfo.removedAppId = mSettings.removePackageLPw(packageName);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007977 }
7978 if (deletedPs != null) {
Dianne Hackborne639da72012-02-21 15:11:13 -08007979 updatePermissionsLPw(deletedPs.name, null, 0);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007980 if (deletedPs.sharedUser != null) {
7981 // remove permissions associated with package
Kenny Root447106f2011-03-23 11:00:15 -07007982 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007983 }
7984 }
Amith Yamasania3f133a2012-08-09 17:11:28 -07007985 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007986 }
7987 }
Kenny Root447106f2011-03-23 11:00:15 -07007988 // can downgrade to reader
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007989 if (writeSettings) {
7990 // Save settings now
Kenny Root447106f2011-03-23 11:00:15 -07007991 mSettings.writeLPr();
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007993 }
7994 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007996 /*
7997 * Tries to delete system package.
7998 */
7999 private boolean deleteSystemPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008000 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008001 ApplicationInfo applicationInfo = p.applicationInfo;
8002 //applicable for non-partially installed applications only
8003 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008004 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008005 return false;
8006 }
8007 PackageSetting ps = null;
8008 // Confirm if the system package has been updated
8009 // An updated system app can be deleted. This will also have to restore
8010 // the system pkg from system partition
Kenny Root447106f2011-03-23 11:00:15 -07008011 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008012 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07008013 ps = mSettings.getDisabledSystemPkgLPr(p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008014 }
8015 if (ps == null) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008016 Slog.w(TAG, "Attempt to delete unknown system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008017 return false;
8018 } else {
8019 Log.i(TAG, "Deleting system pkg from data partition");
8020 }
8021 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07008022 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07008023 if (ps.versionCode < p.mVersionCode) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008024 // Delete data for downgrades
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008025 flags &= ~PackageManager.DELETE_KEEP_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008026 } else {
8027 // Preserve data by setting flag
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008028 flags |= PackageManager.DELETE_KEEP_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008029 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008030 boolean ret = deleteInstalledPackageLI(p, true, flags, outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008031 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008032 if (!ret) {
8033 return false;
8034 }
Kenny Root447106f2011-03-23 11:00:15 -07008035 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008036 synchronized (mPackages) {
8037 // Reinstate the old system package
Kenny Root447106f2011-03-23 11:00:15 -07008038 mSettings.enableSystemPackageLPw(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07008039 // Remove any native libraries from the upgraded package.
8040 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008041 }
8042 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008043 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008044 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008045 SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008047 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008048 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008049 return false;
8050 }
Kenny Root447106f2011-03-23 11:00:15 -07008051 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008052 synchronized (mPackages) {
Dianne Hackborne639da72012-02-21 15:11:13 -08008053 updatePermissionsLPw(newPkg.packageName, newPkg,
8054 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
Kenny Root447106f2011-03-23 11:00:15 -07008055 // can downgrade to reader here
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008056 if (writeSettings) {
Kenny Root447106f2011-03-23 11:00:15 -07008057 mSettings.writeLPr();
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008059 }
8060 return true;
8061 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008063 private boolean deleteInstalledPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008064 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
8065 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008066 ApplicationInfo applicationInfo = p.applicationInfo;
8067 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008068 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008069 return false;
8070 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008071 if (outInfo != null) {
8072 outInfo.uid = applicationInfo.uid;
8073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008074
8075 // Delete package data from internal structures and also remove data if flag is set
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008076 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008077
8078 // Delete application code and resources
8079 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008080 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07008081 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
8082 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
8083 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
8084 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008085 }
8086 return true;
8087 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008089 /*
8090 * This method handles package deletion in general
8091 */
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008092 private boolean deletePackageLI(String packageName, UserHandle user,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008093 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
8094 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008095 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008096 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008097 return false;
8098 }
8099 PackageParser.Package p;
8100 boolean dataOnly = false;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008101 int removeUser = -1;
8102 int appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008103 synchronized (mPackages) {
8104 p = mPackages.get(packageName);
8105 if (p == null) {
8106 //this retrieves partially installed apps
8107 dataOnly = true;
8108 PackageSetting ps = mSettings.mPackages.get(packageName);
8109 if (ps == null) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008110 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008111 return false;
8112 }
8113 p = ps.pkg;
8114 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008115 if (p == null) {
8116 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
8117 return false;
8118 }
8119 final PackageSetting ps = (PackageSetting)p.mExtras;
8120 if (!isSystemApp(p) && ps != null && user != null
8121 && user.getIdentifier() != UserHandle.USER_ALL) {
8122 // The caller is asking that the package only be deleted for a single
8123 // user. To do this, we just mark its uninstalled state and delete
8124 // its data.
8125 ps.setUserState(user.getIdentifier(),
8126 COMPONENT_ENABLED_STATE_DEFAULT,
8127 false, //installed
8128 true, //stopped
8129 true, //notLaunched
8130 null, null);
8131 if (ps.isAnyInstalled(sUserManager.getUserIds())) {
8132 // Other user still have this package installed, so all
8133 // we need to do is clear this user's data and save that
8134 // it is uninstalled.
8135 removeUser = user.getIdentifier();
8136 appId = ps.appId;
8137 mSettings.writePackageRestrictionsLPr(removeUser);
8138 } else {
8139 // We need to set it back to 'installed' so the uninstall
8140 // broadcasts will be sent correctly.
8141 ps.setInstalled(true, user.getIdentifier());
8142 }
8143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008144 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008145
8146 if (removeUser >= 0) {
8147 // From above, we determined that we are deleting this only
8148 // for a single user. Continue the work here.
8149 if (outInfo != null) {
8150 outInfo.removedPackage = packageName;
8151 outInfo.removedAppId = appId;
8152 outInfo.removedUsers = new int[] {removeUser};
8153 }
8154 mInstaller.clearUserData(packageName, removeUser);
8155 schedulePackageCleaning(packageName, removeUser, false);
8156 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008157 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008159 if (dataOnly) {
8160 // Delete application data first
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008161 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008162 return true;
8163 }
8164 // At this point the package should have ApplicationInfo associated with it
8165 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008166 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008167 return false;
8168 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008169 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07008170 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008171 Log.i(TAG, "Removing system package:"+p.packageName);
8172 // When an updated system application is deleted we delete the existing resources as well and
8173 // fall back to existing code in system partition
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008174 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008175 } else {
8176 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008177 // Kill application pre-emptively especially for apps on sd.
8178 killApplication(packageName, p.applicationInfo.uid);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008179 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
8180 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008181 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008182 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008183 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008184
Dianne Hackborn183ce022012-06-29 15:00:21 -07008185 private final class ClearStorageConnection implements ServiceConnection {
8186 IMediaContainerService mContainerService;
8187
8188 @Override
8189 public void onServiceConnected(ComponentName name, IBinder service) {
8190 synchronized (this) {
8191 mContainerService = IMediaContainerService.Stub.asInterface(service);
8192 notifyAll();
8193 }
8194 }
8195
8196 @Override
8197 public void onServiceDisconnected(ComponentName name) {
8198 }
8199 }
8200
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008201 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
Dianne Hackborn183ce022012-06-29 15:00:21 -07008202 final boolean mounted;
8203 if (Environment.isExternalStorageEmulated()) {
8204 mounted = true;
8205 } else {
8206 final String status = Environment.getExternalStorageState();
8207
8208 mounted = status.equals(Environment.MEDIA_MOUNTED)
8209 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
8210 }
8211
8212 if (!mounted) {
8213 return;
8214 }
8215
8216 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008217 int[] users;
8218 if (userId == UserHandle.USER_ALL) {
8219 users = sUserManager.getUserIds();
8220 } else {
8221 users = new int[] { userId };
8222 }
8223 for (int curUser : users) {
8224 ClearStorageConnection conn = new ClearStorageConnection();
8225 if (mContext.bindService(containerIntent, conn, Context.BIND_AUTO_CREATE, curUser)) {
8226 try {
8227 long timeout = SystemClock.uptimeMillis() + 5000;
8228 synchronized (conn) {
8229 long now = SystemClock.uptimeMillis();
8230 while (conn.mContainerService == null && now < timeout) {
8231 try {
8232 conn.wait(timeout - now);
8233 } catch (InterruptedException e) {
8234 }
Dianne Hackborn183ce022012-06-29 15:00:21 -07008235 }
8236 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008237 if (conn.mContainerService == null) {
8238 return;
8239 }
8240 final File externalCacheDir = Environment
8241 .getExternalStorageAppCacheDirectory(packageName);
Dianne Hackborn183ce022012-06-29 15:00:21 -07008242 try {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008243 conn.mContainerService.clearDirectory(externalCacheDir.toString());
Dianne Hackborn183ce022012-06-29 15:00:21 -07008244 } catch (RemoteException e) {
8245 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008246 if (allData) {
8247 final File externalDataDir = Environment
8248 .getExternalStorageAppDataDirectory(packageName);
8249 try {
8250 conn.mContainerService.clearDirectory(externalDataDir.toString());
8251 } catch (RemoteException e) {
8252 }
8253 final File externalMediaDir = Environment
8254 .getExternalStorageAppMediaDirectory(packageName);
8255 try {
8256 conn.mContainerService.clearDirectory(externalMediaDir.toString());
8257 } catch (RemoteException e) {
8258 }
Dianne Hackborn183ce022012-06-29 15:00:21 -07008259 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008260 } finally {
8261 mContext.unbindService(conn);
Dianne Hackborn183ce022012-06-29 15:00:21 -07008262 }
Dianne Hackborn183ce022012-06-29 15:00:21 -07008263 }
8264 }
8265 }
8266
Amith Yamasani483f3b02012-03-13 16:08:00 -07008267 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008268 public void clearApplicationUserData(final String packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07008269 final IPackageDataObserver observer, final int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008270 mContext.enforceCallingOrSelfPermission(
8271 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
Amith Yamasanif203aee2012-08-29 18:41:53 -07008272 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008273 // Queue up an async operation since the package deletion may take a little while.
8274 mHandler.post(new Runnable() {
8275 public void run() {
8276 mHandler.removeCallbacks(this);
8277 final boolean succeeded;
8278 synchronized (mInstallLock) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008279 succeeded = clearApplicationUserDataLI(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008280 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008281 clearExternalStorageDataSync(packageName, userId, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008282 if (succeeded) {
8283 // invoke DeviceStorageMonitor's update method to clear any notifications
8284 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
8285 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
8286 if (dsm != null) {
8287 dsm.updateMemory();
8288 }
8289 }
8290 if(observer != null) {
8291 try {
8292 observer.onRemoveCompleted(packageName, succeeded);
8293 } catch (RemoteException e) {
8294 Log.i(TAG, "Observer no longer exists.");
8295 }
8296 } //end if observer
8297 } //end run
8298 });
8299 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008300
Amith Yamasani483f3b02012-03-13 16:08:00 -07008301 private boolean clearApplicationUserDataLI(String packageName, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008302 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008303 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008304 return false;
8305 }
8306 PackageParser.Package p;
8307 boolean dataOnly = false;
8308 synchronized (mPackages) {
8309 p = mPackages.get(packageName);
8310 if(p == null) {
8311 dataOnly = true;
8312 PackageSetting ps = mSettings.mPackages.get(packageName);
8313 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008314 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008315 return false;
8316 }
8317 p = ps.pkg;
8318 }
8319 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08008320
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08008321 if (!dataOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008322 //need to check this only for fully installed applications
8323 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008324 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008325 return false;
8326 }
8327 final ApplicationInfo applicationInfo = p.applicationInfo;
8328 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008329 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008330 return false;
8331 }
8332 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07008333 int retCode = mInstaller.clearUserData(packageName, userId);
Jeff Brown5d6d90f2011-07-11 13:04:53 -07008334 if (retCode < 0) {
8335 Slog.w(TAG, "Couldn't remove cache files for package: "
8336 + packageName);
8337 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008338 }
8339 return true;
8340 }
8341
8342 public void deleteApplicationCacheFiles(final String packageName,
8343 final IPackageDataObserver observer) {
8344 mContext.enforceCallingOrSelfPermission(
8345 android.Manifest.permission.DELETE_CACHE_FILES, null);
8346 // Queue up an async operation since the package deletion may take a little while.
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008347 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008348 mHandler.post(new Runnable() {
8349 public void run() {
8350 mHandler.removeCallbacks(this);
8351 final boolean succeded;
8352 synchronized (mInstallLock) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008353 succeded = deleteApplicationCacheFilesLI(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008354 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008355 clearExternalStorageDataSync(packageName, userId, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008356 if(observer != null) {
8357 try {
8358 observer.onRemoveCompleted(packageName, succeded);
8359 } catch (RemoteException e) {
8360 Log.i(TAG, "Observer no longer exists.");
8361 }
8362 } //end if observer
8363 } //end run
8364 });
8365 }
8366
Amith Yamasani483f3b02012-03-13 16:08:00 -07008367 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008368 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008369 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008370 return false;
8371 }
8372 PackageParser.Package p;
8373 synchronized (mPackages) {
8374 p = mPackages.get(packageName);
8375 }
8376 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008377 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008378 return false;
8379 }
8380 final ApplicationInfo applicationInfo = p.applicationInfo;
8381 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008382 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008383 return false;
8384 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07008385 // TODO: Pass userId to deleteCacheFiles
Jeff Brown5d6d90f2011-07-11 13:04:53 -07008386 int retCode = mInstaller.deleteCacheFiles(packageName);
8387 if (retCode < 0) {
8388 Slog.w(TAG, "Couldn't remove cache files for package: "
8389 + packageName);
8390 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008391 }
8392 return true;
8393 }
8394
Dianne Hackborn0c380492012-08-20 17:23:30 -07008395 public void getPackageSizeInfo(final String packageName, int userHandle,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008396 final IPackageStatsObserver observer) {
8397 mContext.enforceCallingOrSelfPermission(
8398 android.Manifest.permission.GET_PACKAGE_SIZE, null);
Kenny Root366949c2011-01-14 17:18:14 -08008399
Dianne Hackborn0c380492012-08-20 17:23:30 -07008400 PackageStats stats = new PackageStats(packageName, userHandle);
Kenny Root366949c2011-01-14 17:18:14 -08008401
Kenny Roota69b7eb2012-05-14 14:47:06 -07008402 /*
8403 * Queue up an async operation since the package measurement may take a
8404 * little while.
8405 */
8406 Message msg = mHandler.obtainMessage(INIT_COPY);
8407 msg.obj = new MeasureParams(stats, observer);
8408 mHandler.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008409 }
8410
Dianne Hackborn0c380492012-08-20 17:23:30 -07008411 private boolean getPackageSizeInfoLI(String packageName, int userHandle,
8412 PackageStats pStats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008413 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008414 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008415 return false;
8416 }
8417 PackageParser.Package p;
8418 boolean dataOnly = false;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07008419 String asecPath = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008420 synchronized (mPackages) {
8421 p = mPackages.get(packageName);
8422 if(p == null) {
8423 dataOnly = true;
8424 PackageSetting ps = mSettings.mPackages.get(packageName);
8425 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008426 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008427 return false;
8428 }
8429 p = ps.pkg;
8430 }
Kenny Root2afded12012-06-04 16:39:47 -07008431 if (p != null && (isExternal(p) || isForwardLocked(p))) {
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07008432 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
8433 if (secureContainerId != null) {
8434 asecPath = PackageHelper.getSdFilesystem(secureContainerId);
8435 }
8436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008437 }
8438 String publicSrcDir = null;
8439 if(!dataOnly) {
8440 final ApplicationInfo applicationInfo = p.applicationInfo;
8441 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008442 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008443 return false;
8444 }
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07008445 if (isForwardLocked(p)) {
8446 publicSrcDir = applicationInfo.publicSourceDir;
8447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008448 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008449 int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, publicSrcDir,
Jeff Brown5d6d90f2011-07-11 13:04:53 -07008450 asecPath, pStats);
8451 if (res < 0) {
8452 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008453 }
Kenny Root2afded12012-06-04 16:39:47 -07008454
8455 // Fix-up for forward-locked applications in ASEC containers.
8456 if (!isExternal(p)) {
8457 pStats.codeSize += pStats.externalCodeSize;
8458 pStats.externalCodeSize = 0L;
8459 }
8460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008461 return true;
8462 }
8463
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008465 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07008466 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008467 }
8468
8469 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07008470 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008471 }
8472
8473 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008474 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008475 }
8476
Kenny Root447106f2011-03-23 11:00:15 -07008477 private int getUidTargetSdkVersionLockedLPr(int uid) {
8478 Object obj = mSettings.getUserIdLPr(uid);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008479 if (obj instanceof SharedUserSetting) {
Kenny Root60f7ad82011-03-22 12:49:06 -07008480 final SharedUserSetting sus = (SharedUserSetting) obj;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008481 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
Kenny Root60f7ad82011-03-22 12:49:06 -07008482 final Iterator<PackageSetting> it = sus.packages.iterator();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008483 while (it.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07008484 final PackageSetting ps = it.next();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008485 if (ps.pkg != null) {
8486 int v = ps.pkg.applicationInfo.targetSdkVersion;
8487 if (v < vers) vers = v;
8488 }
8489 }
8490 return vers;
8491 } else if (obj instanceof PackageSetting) {
Kenny Root60f7ad82011-03-22 12:49:06 -07008492 final PackageSetting ps = (PackageSetting) obj;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008493 if (ps.pkg != null) {
8494 return ps.pkg.applicationInfo.targetSdkVersion;
8495 }
8496 }
8497 return Build.VERSION_CODES.CUR_DEVELOPMENT;
8498 }
8499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008500 public void addPreferredActivity(IntentFilter filter, int match,
Amith Yamasania3f133a2012-08-09 17:11:28 -07008501 ComponentName[] set, ComponentName activity, int userId) {
Kenny Root447106f2011-03-23 11:00:15 -07008502 // writer
Amith Yamasania3f133a2012-08-09 17:11:28 -07008503 int callingUid = Binder.getCallingUid();
Amith Yamasanif203aee2012-08-29 18:41:53 -07008504 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008505 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008506 if (mContext.checkCallingOrSelfPermission(
8507 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
8508 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasania3f133a2012-08-09 17:11:28 -07008509 if (getUidTargetSdkVersionLockedLPr(callingUid)
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008510 < Build.VERSION_CODES.FROYO) {
8511 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
Amith Yamasania3f133a2012-08-09 17:11:28 -07008512 + callingUid);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008513 return;
8514 }
8515 mContext.enforceCallingOrSelfPermission(
8516 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
8517 }
Amith Yamasania3f133a2012-08-09 17:11:28 -07008518
8519 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008520 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
8521 mSettings.mPreferredActivities.addFilter(
Amith Yamasania3f133a2012-08-09 17:11:28 -07008522 new PreferredActivity(filter, match, set, activity, userId));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07008523 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008524 }
8525 }
8526
Satish Sampath8dbe6122009-06-02 23:35:54 +01008527 public void replacePreferredActivity(IntentFilter filter, int match,
8528 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01008529 if (filter.countActions() != 1) {
8530 throw new IllegalArgumentException(
8531 "replacePreferredActivity expects filter to have only 1 action.");
8532 }
8533 if (filter.countCategories() != 1) {
8534 throw new IllegalArgumentException(
8535 "replacePreferredActivity expects filter to have only 1 category.");
8536 }
8537 if (filter.countDataAuthorities() != 0
8538 || filter.countDataPaths() != 0
8539 || filter.countDataSchemes() != 0
8540 || filter.countDataTypes() != 0) {
8541 throw new IllegalArgumentException(
8542 "replacePreferredActivity expects filter to have no data authorities, " +
8543 "paths, schemes or types.");
8544 }
8545 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008546 if (mContext.checkCallingOrSelfPermission(
8547 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
8548 != PackageManager.PERMISSION_GRANTED) {
Kenny Root447106f2011-03-23 11:00:15 -07008549 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008550 < Build.VERSION_CODES.FROYO) {
8551 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
8552 + Binder.getCallingUid());
8553 return;
8554 }
8555 mContext.enforceCallingOrSelfPermission(
8556 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
8557 }
Amith Yamasania3f133a2012-08-09 17:11:28 -07008558
8559 final int callingUserId = UserHandle.getCallingUserId();
Dianne Hackborn04505102012-02-29 12:34:04 -08008560 ArrayList<PreferredActivity> removed = null;
Satish Sampath8dbe6122009-06-02 23:35:54 +01008561 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
8562 String action = filter.getAction(0);
8563 String category = filter.getCategory(0);
8564 while (it.hasNext()) {
8565 PreferredActivity pa = it.next();
Amith Yamasania3f133a2012-08-09 17:11:28 -07008566 if (pa.mUserId != callingUserId) continue;
Satish Sampath8dbe6122009-06-02 23:35:54 +01008567 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
Dianne Hackborn04505102012-02-29 12:34:04 -08008568 if (removed == null) {
8569 removed = new ArrayList<PreferredActivity>();
8570 }
8571 removed.add(pa);
8572 Log.i(TAG, "Removing preferred activity " + pa.mPref.mComponent + ":");
Satish Sampath8dbe6122009-06-02 23:35:54 +01008573 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
8574 }
8575 }
Dianne Hackborn04505102012-02-29 12:34:04 -08008576 if (removed != null) {
8577 for (int i=0; i<removed.size(); i++) {
8578 PreferredActivity pa = removed.get(i);
8579 mSettings.mPreferredActivities.removeFilter(pa);
8580 }
8581 }
Amith Yamasania3f133a2012-08-09 17:11:28 -07008582 addPreferredActivity(filter, match, set, activity, callingUserId);
Satish Sampath8dbe6122009-06-02 23:35:54 +01008583 }
8584 }
8585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008586 public void clearPackagePreferredActivities(String packageName) {
Kenny Root447106f2011-03-23 11:00:15 -07008587 final int uid = Binder.getCallingUid();
8588 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008589 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08008590 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008591 if (pkg == null || pkg.applicationInfo.uid != uid) {
8592 if (mContext.checkCallingOrSelfPermission(
8593 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
8594 != PackageManager.PERMISSION_GRANTED) {
Kenny Root447106f2011-03-23 11:00:15 -07008595 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008596 < Build.VERSION_CODES.FROYO) {
8597 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
8598 + Binder.getCallingUid());
8599 return;
8600 }
8601 mContext.enforceCallingOrSelfPermission(
8602 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
8603 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08008604 }
8605
Amith Yamasania3f133a2012-08-09 17:11:28 -07008606 if (clearPackagePreferredActivitiesLPw(packageName, UserHandle.getCallingUserId())) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07008607 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008608 }
8609 }
8610 }
8611
Amith Yamasania3f133a2012-08-09 17:11:28 -07008612 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
8613 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
Dianne Hackborn04505102012-02-29 12:34:04 -08008614 ArrayList<PreferredActivity> removed = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008615 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
8616 while (it.hasNext()) {
8617 PreferredActivity pa = it.next();
Amith Yamasania3f133a2012-08-09 17:11:28 -07008618 if (userId != UserHandle.USER_ALL && pa.mUserId != userId) {
8619 continue;
8620 }
Dianne Hackbornf8b8a3f2011-03-04 00:05:31 -08008621 if (pa.mPref.mComponent.getPackageName().equals(packageName)) {
Dianne Hackborn04505102012-02-29 12:34:04 -08008622 if (removed == null) {
8623 removed = new ArrayList<PreferredActivity>();
8624 }
8625 removed.add(pa);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008626 }
8627 }
Dianne Hackborn04505102012-02-29 12:34:04 -08008628 if (removed != null) {
8629 for (int i=0; i<removed.size(); i++) {
8630 PreferredActivity pa = removed.get(i);
8631 mSettings.mPreferredActivities.removeFilter(pa);
8632 }
8633 return true;
8634 }
8635 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008636 }
8637
8638 public int getPreferredActivities(List<IntentFilter> outFilters,
8639 List<ComponentName> outActivities, String packageName) {
8640
8641 int num = 0;
Amith Yamasania3f133a2012-08-09 17:11:28 -07008642 final int userId = UserHandle.getCallingUserId();
Kenny Root447106f2011-03-23 11:00:15 -07008643 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008644 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07008645 final Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008646 while (it.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07008647 final PreferredActivity pa = it.next();
Amith Yamasania3f133a2012-08-09 17:11:28 -07008648 if (pa.mUserId != userId) {
8649 continue;
8650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008651 if (packageName == null
Dianne Hackbornf8b8a3f2011-03-04 00:05:31 -08008652 || pa.mPref.mComponent.getPackageName().equals(packageName)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008653 if (outFilters != null) {
8654 outFilters.add(new IntentFilter(pa));
8655 }
8656 if (outActivities != null) {
Dianne Hackbornf8b8a3f2011-03-04 00:05:31 -08008657 outActivities.add(pa.mPref.mComponent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008658 }
8659 }
8660 }
8661 }
8662
8663 return num;
8664 }
8665
Amith Yamasani483f3b02012-03-13 16:08:00 -07008666 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008667 public void setApplicationEnabledSetting(String appPackageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07008668 int newState, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07008669 if (!sUserManager.exists(userId)) return;
Amith Yamasani483f3b02012-03-13 16:08:00 -07008670 setEnabledSetting(appPackageName, null, newState, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008671 }
8672
Amith Yamasani483f3b02012-03-13 16:08:00 -07008673 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008674 public void setComponentEnabledSetting(ComponentName componentName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07008675 int newState, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07008676 if (!sUserManager.exists(userId)) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008677 setEnabledSetting(componentName.getPackageName(),
Amith Yamasani483f3b02012-03-13 16:08:00 -07008678 componentName.getClassName(), newState, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008679 }
8680
8681 private void setEnabledSetting(
Amith Yamasani483f3b02012-03-13 16:08:00 -07008682 final String packageName, String className, int newState, final int flags, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008683 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
8684 || newState == COMPONENT_ENABLED_STATE_ENABLED
Dianne Hackborn0ac30312011-06-17 14:49:23 -07008685 || newState == COMPONENT_ENABLED_STATE_DISABLED
8686 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008687 throw new IllegalArgumentException("Invalid new component state: "
8688 + newState);
8689 }
8690 PackageSetting pkgSetting;
8691 final int uid = Binder.getCallingUid();
8692 final int permission = mContext.checkCallingPermission(
8693 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
Amith Yamasanif203aee2012-08-29 18:41:53 -07008694 enforceCrossUserPermission(uid, userId, false, "set enabled");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008695 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008696 boolean sendNow = false;
8697 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08008698 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008699 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08008700 ArrayList<String> components;
Kenny Root447106f2011-03-23 11:00:15 -07008701
8702 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008703 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008704 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008705 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008706 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008707 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008708 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008709 }
8710 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008711 "Unknown component: " + packageName
8712 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008713 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07008714 // Allow root and verify that userId is not being specified by a different user
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008715 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008716 throw new SecurityException(
8717 "Permission Denial: attempt to change component state from pid="
8718 + Binder.getCallingPid()
Amith Yamasani13593602012-03-22 16:16:17 -07008719 + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008720 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008721 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008722 // We're dealing with an application/package level state change
Amith Yamasani483f3b02012-03-13 16:08:00 -07008723 if (pkgSetting.getEnabled(userId) == newState) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07008724 // Nothing to do
8725 return;
8726 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07008727 pkgSetting.setEnabled(newState, userId);
Amith Yamasani13593602012-03-22 16:16:17 -07008728 // pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008729 } else {
8730 // We're dealing with a component level state change
Dianne Hackborn65696252012-03-05 18:49:21 -08008731 // First, verify that this is a valid class name.
8732 PackageParser.Package pkg = pkgSetting.pkg;
8733 if (pkg == null || !pkg.hasComponentClassName(className)) {
8734 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
8735 throw new IllegalArgumentException("Component class " + className
8736 + " does not exist in " + packageName);
8737 } else {
8738 Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
8739 + className + " does not exist in " + packageName);
8740 }
8741 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008742 switch (newState) {
8743 case COMPONENT_ENABLED_STATE_ENABLED:
Amith Yamasani483f3b02012-03-13 16:08:00 -07008744 if (!pkgSetting.enableComponentLPw(className, userId)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07008745 return;
8746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008747 break;
8748 case COMPONENT_ENABLED_STATE_DISABLED:
Amith Yamasani483f3b02012-03-13 16:08:00 -07008749 if (!pkgSetting.disableComponentLPw(className, userId)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07008750 return;
8751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008752 break;
8753 case COMPONENT_ENABLED_STATE_DEFAULT:
Amith Yamasani483f3b02012-03-13 16:08:00 -07008754 if (!pkgSetting.restoreComponentLPw(className, userId)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07008755 return;
8756 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008757 break;
8758 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008759 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008760 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008761 }
8762 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07008763 mSettings.writePackageRestrictionsLPr(userId);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008764 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08008765 components = mPendingBroadcasts.get(packageName);
Kenny Root447106f2011-03-23 11:00:15 -07008766 final boolean newPackage = components == null;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08008767 if (newPackage) {
8768 components = new ArrayList<String>();
8769 }
8770 if (!components.contains(componentName)) {
8771 components.add(componentName);
8772 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008773 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
8774 sendNow = true;
8775 // Purge entry from pending broadcast list if another one exists already
8776 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08008777 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008778 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08008779 if (newPackage) {
8780 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008781 }
8782 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
8783 // Schedule a message
8784 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
8785 }
8786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008787 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008789 long callingId = Binder.clearCallingIdentity();
8790 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008791 if (sendNow) {
8792 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08008793 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008795 } finally {
8796 Binder.restoreCallingIdentity(callingId);
8797 }
8798 }
8799
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008800 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08008801 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
Kenny Root4dfe6ff2011-02-23 17:00:43 -08008802 if (DEBUG_INSTALL)
8803 Log.v(TAG, "Sending package changed: package=" + packageName + " components="
8804 + componentNames);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08008805 Bundle extras = new Bundle(4);
8806 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
8807 String nameList[] = new String[componentNames.size()];
8808 componentNames.toArray(nameList);
8809 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008810 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
8811 extras.putInt(Intent.EXTRA_UID, packageUid);
Amith Yamasani13593602012-03-22 16:16:17 -07008812 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008813 new int[] {UserHandle.getUserId(packageUid)});
Dianne Hackborne7f97212011-02-24 14:40:20 -08008814 }
8815
Amith Yamasani483f3b02012-03-13 16:08:00 -07008816 public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07008817 if (!sUserManager.exists(userId)) return;
Dianne Hackborne7f97212011-02-24 14:40:20 -08008818 final int uid = Binder.getCallingUid();
8819 final int permission = mContext.checkCallingOrSelfPermission(
8820 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
8821 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Amith Yamasanif203aee2012-08-29 18:41:53 -07008822 enforceCrossUserPermission(uid, userId, true, "stop package");
Kenny Root447106f2011-03-23 11:00:15 -07008823 // writer
Dianne Hackborne7f97212011-02-24 14:40:20 -08008824 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07008825 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
Amith Yamasani483f3b02012-03-13 16:08:00 -07008826 uid, userId)) {
8827 scheduleWritePackageRestrictionsLocked(userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08008828 }
8829 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07008830 }
8831
Jacek Surazski65e13172009-04-28 15:26:38 +02008832 public String getInstallerPackageName(String packageName) {
Kenny Root447106f2011-03-23 11:00:15 -07008833 // reader
Jacek Surazski65e13172009-04-28 15:26:38 +02008834 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07008835 return mSettings.getInstallerPackageNameLPr(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02008836 }
8837 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008838
Amith Yamasani483f3b02012-03-13 16:08:00 -07008839 @Override
8840 public int getApplicationEnabledSetting(String packageName, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07008841 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
Amith Yamasani483f3b02012-03-13 16:08:00 -07008842 int uid = Binder.getCallingUid();
Amith Yamasanif203aee2012-08-29 18:41:53 -07008843 enforceCrossUserPermission(uid, userId, false, "get enabled");
Kenny Root447106f2011-03-23 11:00:15 -07008844 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008845 synchronized (mPackages) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008846 return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008847 }
8848 }
8849
Amith Yamasani483f3b02012-03-13 16:08:00 -07008850 @Override
8851 public int getComponentEnabledSetting(ComponentName componentName, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07008852 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
Amith Yamasani483f3b02012-03-13 16:08:00 -07008853 int uid = Binder.getCallingUid();
Amith Yamasanif203aee2012-08-29 18:41:53 -07008854 enforceCrossUserPermission(uid, userId, false, "get component enabled");
Kenny Root447106f2011-03-23 11:00:15 -07008855 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008856 synchronized (mPackages) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008857 return mSettings.getComponentEnabledSettingLPr(componentName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008858 }
8859 }
8860
8861 public void enterSafeMode() {
Kenny Root461ff1f2011-08-09 09:43:03 -07008862 enforceSystemOrRoot("Only the system can request entering safe mode");
8863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008864 if (!mSystemReady) {
8865 mSafeMode = true;
8866 }
8867 }
8868
8869 public void systemReady() {
8870 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07008871
8872 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07008873 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07008874 mContext.getContentResolver(),
8875 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07008876 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07008877 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07008878 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07008879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008880 }
8881
8882 public boolean isSafeMode() {
8883 return mSafeMode;
8884 }
8885
8886 public boolean hasSystemUidErrors() {
8887 return mHasSystemUidErrors;
8888 }
8889
8890 static String arrayToString(int[] array) {
8891 StringBuffer buf = new StringBuffer(128);
8892 buf.append('[');
8893 if (array != null) {
8894 for (int i=0; i<array.length; i++) {
8895 if (i > 0) buf.append(", ");
8896 buf.append(array[i]);
8897 }
8898 }
8899 buf.append(']');
8900 return buf.toString();
8901 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008902
Kenny Root447106f2011-03-23 11:00:15 -07008903 static class DumpState {
8904 public static final int DUMP_LIBS = 1 << 0;
8905
8906 public static final int DUMP_FEATURES = 1 << 1;
8907
8908 public static final int DUMP_RESOLVERS = 1 << 2;
8909
8910 public static final int DUMP_PERMISSIONS = 1 << 3;
8911
8912 public static final int DUMP_PACKAGES = 1 << 4;
8913
8914 public static final int DUMP_SHARED_USERS = 1 << 5;
8915
8916 public static final int DUMP_MESSAGES = 1 << 6;
8917
8918 public static final int DUMP_PROVIDERS = 1 << 7;
8919
Kenny Root05ca4c92011-09-15 10:36:25 -07008920 public static final int DUMP_VERIFIERS = 1 << 8;
8921
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07008922 public static final int DUMP_PREFERRED = 1 << 9;
8923
8924 public static final int DUMP_PREFERRED_XML = 1 << 10;
8925
Kenny Root447106f2011-03-23 11:00:15 -07008926 public static final int OPTION_SHOW_FILTERS = 1 << 0;
8927
8928 private int mTypes;
8929
8930 private int mOptions;
8931
8932 private boolean mTitlePrinted;
8933
8934 private SharedUserSetting mSharedUser;
8935
8936 public boolean isDumping(int type) {
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07008937 if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
Kenny Root447106f2011-03-23 11:00:15 -07008938 return true;
8939 }
8940
8941 return (mTypes & type) != 0;
8942 }
8943
8944 public void setDump(int type) {
8945 mTypes |= type;
8946 }
8947
8948 public boolean isOptionEnabled(int option) {
8949 return (mOptions & option) != 0;
8950 }
8951
8952 public void setOptionEnabled(int option) {
8953 mOptions |= option;
8954 }
8955
8956 public boolean onTitlePrinted() {
8957 final boolean printed = mTitlePrinted;
8958 mTitlePrinted = true;
8959 return printed;
8960 }
8961
8962 public boolean getTitlePrinted() {
8963 return mTitlePrinted;
8964 }
8965
8966 public void setTitlePrinted(boolean enabled) {
8967 mTitlePrinted = enabled;
8968 }
8969
8970 public SharedUserSetting getSharedUser() {
8971 return mSharedUser;
8972 }
8973
8974 public void setSharedUser(SharedUserSetting user) {
8975 mSharedUser = user;
8976 }
8977 }
8978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008979 @Override
8980 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
8981 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
8982 != PackageManager.PERMISSION_GRANTED) {
8983 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8984 + Binder.getCallingPid()
8985 + ", uid=" + Binder.getCallingUid()
8986 + " without permission "
8987 + android.Manifest.permission.DUMP);
8988 return;
8989 }
8990
Kenny Root447106f2011-03-23 11:00:15 -07008991 DumpState dumpState = new DumpState();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008992
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008993 String packageName = null;
8994
8995 int opti = 0;
8996 while (opti < args.length) {
8997 String opt = args[opti];
8998 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8999 break;
9000 }
9001 opti++;
9002 if ("-a".equals(opt)) {
9003 // Right now we only know how to print all.
9004 } else if ("-h".equals(opt)) {
9005 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009006 pw.println(" [-h] [-f] [cmd] ...");
9007 pw.println(" -f: print details of intent filters");
9008 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009009 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009010 pw.println(" l[ibraries]: list known shared libraries");
9011 pw.println(" f[ibraries]: list device features");
9012 pw.println(" r[esolvers]: dump intent resolvers");
9013 pw.println(" perm[issions]: dump permissions");
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07009014 pw.println(" pref[erred]: print preferred package settings");
9015 pw.println(" preferred-xml: print preferred package settings as xml");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009016 pw.println(" prov[iders]: dump content providers");
9017 pw.println(" p[ackages]: dump installed packages");
9018 pw.println(" s[hared-users]: dump shared user IDs");
9019 pw.println(" m[essages]: print collected runtime messages");
Kenny Root05ca4c92011-09-15 10:36:25 -07009020 pw.println(" v[erifiers]: print package verifier info");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009021 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009022 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009023 } else if ("-f".equals(opt)) {
Kenny Root447106f2011-03-23 11:00:15 -07009024 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009025 } else {
9026 pw.println("Unknown argument: " + opt + "; use -h for help");
9027 }
9028 }
9029
9030 // Is the caller requesting to dump a particular piece of data?
9031 if (opti < args.length) {
9032 String cmd = args[opti];
9033 opti++;
9034 // Is this a package name?
9035 if ("android".equals(cmd) || cmd.contains(".")) {
9036 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009037 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07009038 dumpState.setDump(DumpState.DUMP_LIBS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009039 } else if ("f".equals(cmd) || "features".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07009040 dumpState.setDump(DumpState.DUMP_FEATURES);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009041 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07009042 dumpState.setDump(DumpState.DUMP_RESOLVERS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009043 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07009044 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07009045 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
9046 dumpState.setDump(DumpState.DUMP_PREFERRED);
9047 } else if ("preferred-xml".equals(cmd)) {
9048 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009049 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07009050 dumpState.setDump(DumpState.DUMP_PACKAGES);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009051 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07009052 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009053 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07009054 dumpState.setDump(DumpState.DUMP_PROVIDERS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009055 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07009056 dumpState.setDump(DumpState.DUMP_MESSAGES);
Kenny Root05ca4c92011-09-15 10:36:25 -07009057 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
9058 dumpState.setDump(DumpState.DUMP_VERIFIERS);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009059 }
9060 }
Kenny Root447106f2011-03-23 11:00:15 -07009061
9062 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009063 synchronized (mPackages) {
Kenny Root05ca4c92011-09-15 10:36:25 -07009064 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
9065 if (dumpState.onTitlePrinted())
9066 pw.println(" ");
9067 pw.println("Verifiers:");
9068 pw.print(" Required: ");
9069 pw.print(mRequiredVerifierPackage);
9070 pw.print(" (uid=");
Amith Yamasani483f3b02012-03-13 16:08:00 -07009071 pw.print(getPackageUid(mRequiredVerifierPackage, 0));
Kenny Root05ca4c92011-09-15 10:36:25 -07009072 pw.println(")");
9073 }
9074
Kenny Root447106f2011-03-23 11:00:15 -07009075 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
9076 if (dumpState.onTitlePrinted())
9077 pw.println(" ");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009078 pw.println("Libraries:");
Kenny Root447106f2011-03-23 11:00:15 -07009079 final Iterator<String> it = mSharedLibraries.keySet().iterator();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009080 while (it.hasNext()) {
9081 String name = it.next();
9082 pw.print(" ");
9083 pw.print(name);
9084 pw.print(" -> ");
9085 pw.println(mSharedLibraries.get(name));
9086 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009087 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009088
Kenny Root447106f2011-03-23 11:00:15 -07009089 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
9090 if (dumpState.onTitlePrinted())
9091 pw.println(" ");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009092 pw.println("Features:");
9093 Iterator<String> it = mAvailableFeatures.keySet().iterator();
9094 while (it.hasNext()) {
9095 String name = it.next();
9096 pw.print(" ");
9097 pw.println(name);
9098 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009099 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009100
Kenny Root447106f2011-03-23 11:00:15 -07009101 if (dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
9102 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
9103 : "Activity Resolver Table:", " ", packageName,
9104 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
9105 dumpState.setTitlePrinted(true);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009106 }
Kenny Root447106f2011-03-23 11:00:15 -07009107 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
9108 : "Receiver Resolver Table:", " ", packageName,
9109 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
9110 dumpState.setTitlePrinted(true);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009111 }
Kenny Root447106f2011-03-23 11:00:15 -07009112 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
9113 : "Service Resolver Table:", " ", packageName,
9114 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
9115 dumpState.setTitlePrinted(true);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009116 }
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07009117 }
9118
9119 if (dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
Kenny Root447106f2011-03-23 11:00:15 -07009120 if (mSettings.mPreferredActivities.dump(pw,
9121 dumpState.getTitlePrinted() ? "\nPreferred Activities:"
9122 : "Preferred Activities:", " ",
9123 packageName, dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
9124 dumpState.setTitlePrinted(true);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009125 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009126 }
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07009127
9128 if (dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
9129 pw.flush();
9130 FileOutputStream fout = new FileOutputStream(fd);
9131 BufferedOutputStream str = new BufferedOutputStream(fout);
9132 XmlSerializer serializer = new FastXmlSerializer();
9133 try {
9134 serializer.setOutput(str, "utf-8");
9135 serializer.startDocument(null, true);
9136 serializer.setFeature(
9137 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
9138 mSettings.writePreferredActivitiesLPr(serializer);
9139 serializer.endDocument();
9140 serializer.flush();
9141 } catch (IllegalArgumentException e) {
9142 pw.println("Failed writing: " + e);
9143 } catch (IllegalStateException e) {
9144 pw.println("Failed writing: " + e);
9145 } catch (IOException e) {
9146 pw.println("Failed writing: " + e);
9147 }
9148 }
9149
Kenny Root447106f2011-03-23 11:00:15 -07009150 if (dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
9151 mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009152 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009153
Kenny Root447106f2011-03-23 11:00:15 -07009154 if (dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
9155 boolean printedSomething = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009156 for (PackageParser.Provider p : mProvidersByComponent.values()) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009157 if (packageName != null && !packageName.equals(p.info.packageName)) {
9158 continue;
9159 }
9160 if (!printedSomething) {
Kenny Root447106f2011-03-23 11:00:15 -07009161 if (dumpState.onTitlePrinted())
9162 pw.println(" ");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009163 pw.println("Registered ContentProviders:");
9164 printedSomething = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009165 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009166 pw.print(" "); pw.print(p.getComponentShortName()); pw.println(":");
9167 pw.print(" "); pw.println(p.toString());
9168 }
9169 printedSomething = false;
9170 for (Map.Entry<String, PackageParser.Provider> entry : mProviders.entrySet()) {
9171 PackageParser.Provider p = entry.getValue();
9172 if (packageName != null && !packageName.equals(p.info.packageName)) {
9173 continue;
9174 }
9175 if (!printedSomething) {
9176 if (dumpState.onTitlePrinted())
9177 pw.println(" ");
9178 pw.println("ContentProvider Authorities:");
9179 printedSomething = true;
9180 }
9181 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:");
9182 pw.print(" "); pw.println(p.toString());
Kenny Rooteca64b32012-06-25 16:37:32 -07009183 if (p.info != null && p.info.applicationInfo != null) {
9184 final String appInfo = p.info.applicationInfo.toString();
9185 pw.print(" applicationInfo="); pw.println(appInfo);
9186 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009187 }
9188 }
9189
Kenny Root447106f2011-03-23 11:00:15 -07009190 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
9191 mSettings.dumpPackagesLPr(pw, packageName, dumpState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009192 }
Kenny Root447106f2011-03-23 11:00:15 -07009193
9194 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
9195 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009196 }
Kenny Root447106f2011-03-23 11:00:15 -07009197
9198 if (dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
9199 if (dumpState.onTitlePrinted())
9200 pw.println(" ");
9201 mSettings.dumpReadMessagesLPr(pw, dumpState);
9202
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009203 pw.println(" ");
9204 pw.println("Package warning messages:");
Kenny Root447106f2011-03-23 11:00:15 -07009205 final File fname = getSettingsProblemFile();
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -08009206 FileInputStream in = null;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009207 try {
9208 in = new FileInputStream(fname);
Kenny Root447106f2011-03-23 11:00:15 -07009209 final int avail = in.available();
9210 final byte[] data = new byte[avail];
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009211 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009212 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009213 } catch (FileNotFoundException e) {
9214 } catch (IOException e) {
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -08009215 } finally {
9216 if (in != null) {
9217 try {
9218 in.close();
Kenny Root447106f2011-03-23 11:00:15 -07009219 } catch (IOException e) {
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -08009220 }
9221 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009222 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009224 }
9225 }
9226
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009227 // ------- apps on sdcard specific code -------
9228 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root447106f2011-03-23 11:00:15 -07009229
Kenny Root305bcbf2010-09-03 07:56:38 -07009230 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
Kenny Root447106f2011-03-23 11:00:15 -07009231
Kenny Root305bcbf2010-09-03 07:56:38 -07009232 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
Kenny Root447106f2011-03-23 11:00:15 -07009233
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009234 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009235
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009236 private String getEncryptKey() {
9237 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009238 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9239 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009240 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009241 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9242 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009243 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009244 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009245 return null;
9246 }
9247 }
9248 return sdEncKey;
9249 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009250 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009251 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009252 } catch (IOException ioe) {
Kenny Root447106f2011-03-23 11:00:15 -07009253 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
Rich Cannings8d578832010-09-09 15:12:40 -07009254 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009255 }
Rich Cannings8d578832010-09-09 15:12:40 -07009256
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009257 }
9258
Kenny Root447106f2011-03-23 11:00:15 -07009259 /* package */static String getTempContainerId() {
Kenny Rootc78a8072010-07-27 15:18:38 -07009260 int tmpIdx = 1;
9261 String list[] = PackageHelper.getSecureContainerList();
9262 if (list != null) {
9263 for (final String name : list) {
9264 // Ignore null and non-temporary container entries
9265 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9266 continue;
9267 }
9268
9269 String subStr = name.substring(mTempContainerPrefix.length());
9270 try {
9271 int cid = Integer.parseInt(subStr);
9272 if (cid >= tmpIdx) {
9273 tmpIdx = cid + 1;
9274 }
9275 } catch (NumberFormatException e) {
9276 }
9277 }
9278 }
9279 return mTempContainerPrefix + tmpIdx;
9280 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009281
Kenny Root447106f2011-03-23 11:00:15 -07009282 /*
9283 * Update media status on PackageManager.
9284 */
9285 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9286 int callingUid = Binder.getCallingUid();
9287 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
9288 throw new SecurityException("Media status can only be updated by the system");
9289 }
9290 // reader; this apparently protects mMediaMounted, but should probably
9291 // be a different lock in that case.
9292 synchronized (mPackages) {
9293 Log.i(TAG, "Updating external media status from "
9294 + (mMediaMounted ? "mounted" : "unmounted") + " to "
9295 + (mediaStatus ? "mounted" : "unmounted"));
9296 if (DEBUG_SD_INSTALL)
9297 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
9298 + ", mMediaMounted=" + mMediaMounted);
9299 if (mediaStatus == mMediaMounted) {
9300 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
9301 : 0, -1);
9302 mHandler.sendMessage(msg);
9303 return;
9304 }
9305 mMediaMounted = mediaStatus;
9306 }
9307 // Queue up an async operation since the package installation may take a
9308 // little while.
9309 mHandler.post(new Runnable() {
9310 public void run() {
Kenny Root438a0ef2012-08-09 13:36:16 -07009311 updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
Kenny Root447106f2011-03-23 11:00:15 -07009312 }
9313 });
9314 }
9315
Kenny Root51a573c2012-05-17 13:30:28 -07009316 /**
9317 * Called by MountService when the initial ASECs to scan are available.
9318 * Should block until all the ASEC containers are finished being scanned.
9319 */
9320 public void scanAvailableAsecs() {
Kenny Root438a0ef2012-08-09 13:36:16 -07009321 updateExternalMediaStatusInner(true, false, false);
Kenny Root51a573c2012-05-17 13:30:28 -07009322 }
9323
Kenny Root447106f2011-03-23 11:00:15 -07009324 /*
9325 * Collect information of applications on external media, map them against
9326 * existing containers and update information based on current mount status.
9327 * Please note that we always have to report status if reportStatus has been
9328 * set to true especially when unloading packages.
9329 */
Kenny Root438a0ef2012-08-09 13:36:16 -07009330 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
9331 boolean externalStorage) {
Kenny Root447106f2011-03-23 11:00:15 -07009332 // Collection of uids
9333 int uidArr[] = null;
9334 // Collection of stale containers
9335 HashSet<String> removeCids = new HashSet<String>();
9336 // Collection of packages on external media with valid containers.
Kenny Root6dceb882012-04-12 14:23:49 -07009337 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
Kenny Root447106f2011-03-23 11:00:15 -07009338 // Get list of secure containers.
9339 final String list[] = PackageHelper.getSecureContainerList();
9340 if (list == null || list.length == 0) {
9341 Log.i(TAG, "No secure containers on sdcard");
9342 } else {
9343 // Process list of secure containers and categorize them
9344 // as active or stale based on their package internal state.
9345 int uidList[] = new int[list.length];
9346 int num = 0;
9347 // reader
9348 synchronized (mPackages) {
9349 for (String cid : list) {
Kenny Root447106f2011-03-23 11:00:15 -07009350 if (DEBUG_SD_INSTALL)
9351 Log.i(TAG, "Processing container " + cid);
Kenny Rootc7a89992012-06-05 15:13:17 -07009352 String pkgName = getAsecPackageName(cid);
Kenny Root447106f2011-03-23 11:00:15 -07009353 if (pkgName == null) {
9354 if (DEBUG_SD_INSTALL)
9355 Log.i(TAG, "Container : " + cid + " stale");
9356 removeCids.add(cid);
9357 continue;
9358 }
9359 if (DEBUG_SD_INSTALL)
9360 Log.i(TAG, "Looking for pkg : " + pkgName);
Kenny Rootc7a89992012-06-05 15:13:17 -07009361
9362 final PackageSetting ps = mSettings.mPackages.get(pkgName);
9363 if (ps == null) {
9364 Log.i(TAG, "Deleting container with no matching settings " + cid);
9365 removeCids.add(cid);
9366 continue;
9367 }
9368
Kenny Root438a0ef2012-08-09 13:36:16 -07009369 /*
9370 * Skip packages that are not external if we're unmounting
9371 * external storage.
9372 */
9373 if (externalStorage && !isMounted && !isExternal(ps)) {
9374 continue;
9375 }
9376
Kenny Rootc7a89992012-06-05 15:13:17 -07009377 final AsecInstallArgs args = new AsecInstallArgs(cid, isForwardLocked(ps));
Kenny Root447106f2011-03-23 11:00:15 -07009378 // The package status is changed only if the code path
9379 // matches between settings and the container id.
Kenny Rootc7a89992012-06-05 15:13:17 -07009380 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
9381 if (DEBUG_SD_INSTALL) {
Kenny Root447106f2011-03-23 11:00:15 -07009382 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
9383 + " at code path: " + ps.codePathString);
Kenny Rootc7a89992012-06-05 15:13:17 -07009384 }
9385
Kenny Root447106f2011-03-23 11:00:15 -07009386 // We do have a valid package installed on sdcard
9387 processCids.put(args, ps.codePathString);
Kenny Rootc7a89992012-06-05 15:13:17 -07009388 final int uid = ps.appId;
Kenny Root447106f2011-03-23 11:00:15 -07009389 if (uid != -1) {
9390 uidList[num++] = uid;
9391 }
9392 } else {
Kenny Rootc7a89992012-06-05 15:13:17 -07009393 Log.i(TAG, "Deleting stale container for " + cid);
Kenny Root447106f2011-03-23 11:00:15 -07009394 removeCids.add(cid);
9395 }
9396 }
9397 }
9398
9399 if (num > 0) {
9400 // Sort uid list
9401 Arrays.sort(uidList, 0, num);
9402 // Throw away duplicates
9403 uidArr = new int[num];
9404 uidArr[0] = uidList[0];
9405 int di = 0;
9406 for (int i = 1; i < num; i++) {
9407 if (uidList[i - 1] != uidList[i]) {
9408 uidArr[di++] = uidList[i];
9409 }
9410 }
9411 }
9412 }
9413 // Process packages with valid entries.
Kenny Root6dceb882012-04-12 14:23:49 -07009414 if (isMounted) {
Kenny Root447106f2011-03-23 11:00:15 -07009415 if (DEBUG_SD_INSTALL)
9416 Log.i(TAG, "Loading packages");
9417 loadMediaPackages(processCids, uidArr, removeCids);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009418 startCleaningPackages(-1);
Kenny Root447106f2011-03-23 11:00:15 -07009419 } else {
9420 if (DEBUG_SD_INSTALL)
9421 Log.i(TAG, "Unloading packages");
9422 unloadMediaPackages(processCids, uidArr, reportStatus);
9423 }
9424 }
9425
9426 private void sendResourcesChangedBroadcast(boolean mediaStatus, ArrayList<String> pkgList,
9427 int uidArr[], IIntentReceiver finishedReceiver) {
9428 int size = pkgList.size();
9429 if (size > 0) {
9430 // Send broadcasts here
9431 Bundle extras = new Bundle();
9432 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
9433 .toArray(new String[size]));
9434 if (uidArr != null) {
9435 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9436 }
9437 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9438 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009439 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
Kenny Root447106f2011-03-23 11:00:15 -07009440 }
9441 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009442
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009443 /*
Kenny Root447106f2011-03-23 11:00:15 -07009444 * Look at potentially valid container ids from processCids If package
9445 * information doesn't match the one on record or package scanning fails,
9446 * the cid is added to list of removeCids. We currently don't delete stale
9447 * containers.
9448 */
Kenny Root6dceb882012-04-12 14:23:49 -07009449 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
Kenny Root447106f2011-03-23 11:00:15 -07009450 HashSet<String> removeCids) {
9451 ArrayList<String> pkgList = new ArrayList<String>();
Kenny Root6dceb882012-04-12 14:23:49 -07009452 Set<AsecInstallArgs> keys = processCids.keySet();
Kenny Root447106f2011-03-23 11:00:15 -07009453 boolean doGc = false;
Kenny Root6dceb882012-04-12 14:23:49 -07009454 for (AsecInstallArgs args : keys) {
Kenny Root447106f2011-03-23 11:00:15 -07009455 String codePath = processCids.get(args);
9456 if (DEBUG_SD_INSTALL)
9457 Log.i(TAG, "Loading container : " + args.cid);
9458 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9459 try {
9460 // Make sure there are no container errors first.
9461 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
9462 Slog.e(TAG, "Failed to mount cid : " + args.cid
9463 + " when installing from sdcard");
9464 continue;
9465 }
9466 // Check code path here.
9467 if (codePath == null || !codePath.equals(args.getCodePath())) {
9468 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
9469 + " does not match one in settings " + codePath);
9470 continue;
9471 }
9472 // Parse package
Kenny Root51a573c2012-05-17 13:30:28 -07009473 int parseFlags = mDefParseFlags;
9474 if (args.isExternal()) {
9475 parseFlags |= PackageParser.PARSE_ON_SDCARD;
9476 }
Kenny Rootc7a89992012-06-05 15:13:17 -07009477 if (args.isFwdLocked()) {
9478 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
9479 }
Kenny Root51a573c2012-05-17 13:30:28 -07009480
Kenny Root447106f2011-03-23 11:00:15 -07009481 doGc = true;
9482 synchronized (mInstallLock) {
9483 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009484 0, 0, null);
Kenny Root447106f2011-03-23 11:00:15 -07009485 // Scan the package
9486 if (pkg != null) {
9487 /*
9488 * TODO why is the lock being held? doPostInstall is
9489 * called in other places without the lock. This needs
9490 * to be straightened out.
9491 */
9492 // writer
9493 synchronized (mPackages) {
9494 retCode = PackageManager.INSTALL_SUCCEEDED;
9495 pkgList.add(pkg.packageName);
9496 // Post process args
Kenny Root6dceb882012-04-12 14:23:49 -07009497 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
9498 pkg.applicationInfo.uid);
Kenny Root447106f2011-03-23 11:00:15 -07009499 }
9500 } else {
9501 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard");
9502 }
9503 }
9504
9505 } finally {
9506 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9507 // Don't destroy container here. Wait till gc clears things
9508 // up.
9509 removeCids.add(args.cid);
9510 }
9511 }
9512 }
9513 // writer
9514 synchronized (mPackages) {
9515 // If the platform SDK has changed since the last time we booted,
9516 // we need to re-grant app permission to catch any new ones that
9517 // appear. This is really a hack, and means that apps can in some
9518 // cases get permissions that the user didn't initially explicitly
9519 // allow... it would be nice to have some better way to handle
9520 // this situation.
9521 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
9522 if (regrantPermissions)
9523 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
9524 + mSdkVersion + "; regranting permissions for external storage");
9525 mSettings.mExternalSdkPlatform = mSdkVersion;
9526
9527 // Make sure group IDs have been assigned, and any permission
9528 // changes in other apps are accounted for
Dianne Hackborne639da72012-02-21 15:11:13 -08009529 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
9530 | (regrantPermissions
9531 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
9532 : 0));
Kenny Root447106f2011-03-23 11:00:15 -07009533 // can downgrade to reader
9534 // Persist settings
9535 mSettings.writeLPr();
9536 }
9537 // Send a broadcast to let everyone know we are done processing
9538 if (pkgList.size() > 0) {
9539 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
9540 }
9541 // Force gc to avoid any stale parser references that we might have.
9542 if (doGc) {
9543 Runtime.getRuntime().gc();
9544 }
9545 // List stale containers and destroy stale temporary containers.
9546 if (removeCids != null) {
9547 for (String cid : removeCids) {
9548 if (cid.startsWith(mTempContainerPrefix)) {
9549 Log.i(TAG, "Destroying stale temporary container " + cid);
9550 PackageHelper.destroySdDir(cid);
9551 } else {
9552 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009553 }
9554 }
Kenny Root447106f2011-03-23 11:00:15 -07009555 }
9556 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009557
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009558 /*
Kenny Root447106f2011-03-23 11:00:15 -07009559 * Utility method to unload a list of specified containers
9560 */
Kenny Root6dceb882012-04-12 14:23:49 -07009561 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
Kenny Root447106f2011-03-23 11:00:15 -07009562 // Just unmount all valid containers.
Kenny Root6dceb882012-04-12 14:23:49 -07009563 for (AsecInstallArgs arg : cidArgs) {
Kenny Root447106f2011-03-23 11:00:15 -07009564 synchronized (mInstallLock) {
9565 arg.doPostDeleteLI(false);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009566 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009567 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009568 }
9569
Kenny Root447106f2011-03-23 11:00:15 -07009570 /*
9571 * Unload packages mounted on external media. This involves deleting package
9572 * data from internal structures, sending broadcasts about diabled packages,
9573 * gc'ing to free up references, unmounting all secure containers
9574 * corresponding to packages on external media, and posting a
9575 * UPDATED_MEDIA_STATUS message if status has been requested. Please note
9576 * that we always have to post this message if status has been requested no
9577 * matter what.
9578 */
Kenny Root6dceb882012-04-12 14:23:49 -07009579 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
Kenny Root447106f2011-03-23 11:00:15 -07009580 final boolean reportStatus) {
9581 if (DEBUG_SD_INSTALL)
9582 Log.i(TAG, "unloading media packages");
9583 ArrayList<String> pkgList = new ArrayList<String>();
Kenny Root6dceb882012-04-12 14:23:49 -07009584 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
9585 final Set<AsecInstallArgs> keys = processCids.keySet();
9586 for (AsecInstallArgs args : keys) {
Kenny Root447106f2011-03-23 11:00:15 -07009587 String pkgName = args.getPackageName();
9588 if (DEBUG_SD_INSTALL)
9589 Log.i(TAG, "Trying to unload pkg : " + pkgName);
9590 // Delete package internally
9591 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9592 synchronized (mInstallLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009593 boolean res = deletePackageLI(pkgName, null, false,
9594 PackageManager.DELETE_KEEP_DATA, outInfo, false);
Kenny Root447106f2011-03-23 11:00:15 -07009595 if (res) {
9596 pkgList.add(pkgName);
9597 } else {
9598 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
9599 failedList.add(args);
9600 }
9601 }
9602 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009603
Kenny Root447106f2011-03-23 11:00:15 -07009604 // reader
9605 synchronized (mPackages) {
9606 // We didn't update the settings after removing each package;
9607 // write them now for all packages.
9608 mSettings.writeLPr();
9609 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009610
Kenny Root447106f2011-03-23 11:00:15 -07009611 // We have to absolutely send UPDATED_MEDIA_STATUS only
9612 // after confirming that all the receivers processed the ordered
9613 // broadcast when packages get disabled, force a gc to clean things up.
9614 // and unload all the containers.
9615 if (pkgList.size() > 0) {
9616 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9617 public void performReceive(Intent intent, int resultCode, String data,
9618 Bundle extras, boolean ordered, boolean sticky) throws RemoteException {
9619 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9620 reportStatus ? 1 : 0, 1, keys);
9621 mHandler.sendMessage(msg);
9622 }
9623 });
9624 } else {
9625 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
9626 keys);
9627 mHandler.sendMessage(msg);
9628 }
9629 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009630
Amith Yamasani6ec10122012-08-23 13:49:25 -07009631 /** Binder call */
9632 @Override
Kenny Root447106f2011-03-23 11:00:15 -07009633 public void movePackage(final String packageName, final IPackageMoveObserver observer,
9634 final int flags) {
9635 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
Amith Yamasani6ec10122012-08-23 13:49:25 -07009636 UserHandle user = new UserHandle(UserHandle.getCallingUserId());
Kenny Root447106f2011-03-23 11:00:15 -07009637 int returnCode = PackageManager.MOVE_SUCCEEDED;
9638 int currFlags = 0;
9639 int newFlags = 0;
9640 // reader
9641 synchronized (mPackages) {
9642 PackageParser.Package pkg = mPackages.get(packageName);
9643 if (pkg == null) {
9644 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9645 } else {
9646 // Disable moving fwd locked apps and system packages
9647 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
9648 Slog.w(TAG, "Cannot move system application");
9649 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root447106f2011-03-23 11:00:15 -07009650 } else if (pkg.mOperationPending) {
9651 Slog.w(TAG, "Attempt to move package which has pending operations");
9652 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
9653 } else {
9654 // Find install location first
9655 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
9656 && (flags & PackageManager.MOVE_INTERNAL) != 0) {
9657 Slog.w(TAG, "Ambigous flags specified for move location.");
9658 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9659 } else {
9660 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
9661 : PackageManager.INSTALL_INTERNAL;
9662 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9663 : PackageManager.INSTALL_INTERNAL;
Kenny Rootbf023582012-05-02 16:56:15 -07009664
Kenny Root447106f2011-03-23 11:00:15 -07009665 if (newFlags == currFlags) {
9666 Slog.w(TAG, "No move required. Trying to move to same location");
9667 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Kenny Rootbf023582012-05-02 16:56:15 -07009668 } else {
9669 if (isForwardLocked(pkg)) {
9670 currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9671 newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9672 }
Kenny Root447106f2011-03-23 11:00:15 -07009673 }
9674 }
9675 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9676 pkg.mOperationPending = true;
9677 }
9678 }
9679 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009680
Kenny Root447106f2011-03-23 11:00:15 -07009681 /*
9682 * TODO this next block probably shouldn't be inside the lock. We
9683 * can't guarantee these won't change after this is fired off
9684 * anyway.
9685 */
9686 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Amith Yamasani6ec10122012-08-23 13:49:25 -07009687 processPendingMove(new MoveParams(null, observer, 0, packageName,
9688 null, -1, user),
Kenny Root6dceb882012-04-12 14:23:49 -07009689 returnCode);
Kenny Root447106f2011-03-23 11:00:15 -07009690 } else {
9691 Message msg = mHandler.obtainMessage(INIT_COPY);
9692 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -07009693 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
Kenny Root447106f2011-03-23 11:00:15 -07009694 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
Amith Yamasani6ec10122012-08-23 13:49:25 -07009695 pkg.applicationInfo.dataDir, pkg.applicationInfo.uid, user);
Kenny Root447106f2011-03-23 11:00:15 -07009696 msg.obj = mp;
9697 mHandler.sendMessage(msg);
9698 }
9699 }
9700 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009701
Kenny Root447106f2011-03-23 11:00:15 -07009702 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9703 // Queue up an async operation since the package deletion may take a
9704 // little while.
9705 mHandler.post(new Runnable() {
9706 public void run() {
9707 // TODO fix this; this does nothing.
9708 mHandler.removeCallbacks(this);
9709 int returnCode = currentStatus;
9710 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9711 int uidArr[] = null;
9712 ArrayList<String> pkgList = null;
9713 synchronized (mPackages) {
9714 PackageParser.Package pkg = mPackages.get(mp.packageName);
9715 if (pkg == null) {
9716 Slog.w(TAG, " Package " + mp.packageName
9717 + " doesn't exist. Aborting move");
9718 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9719 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9720 Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
9721 + mp.srcArgs.getCodePath() + " to "
9722 + pkg.applicationInfo.sourceDir
9723 + " Aborting move and returning error");
9724 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9725 } else {
9726 uidArr = new int[] {
9727 pkg.applicationInfo.uid
9728 };
9729 pkgList = new ArrayList<String>();
9730 pkgList.add(mp.packageName);
9731 }
9732 }
9733 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9734 // Send resources unavailable broadcast
9735 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
9736 // Update package code and resource paths
9737 synchronized (mInstallLock) {
9738 synchronized (mPackages) {
9739 PackageParser.Package pkg = mPackages.get(mp.packageName);
9740 // Recheck for package again.
Kenny Root6a6b0072010-10-07 16:46:10 -07009741 if (pkg == null) {
9742 Slog.w(TAG, " Package " + mp.packageName
9743 + " doesn't exist. Aborting move");
9744 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Kenny Root447106f2011-03-23 11:00:15 -07009745 } else if (!mp.srcArgs.getCodePath().equals(
9746 pkg.applicationInfo.sourceDir)) {
9747 Slog.w(TAG, "Package " + mp.packageName
9748 + " code path changed from " + mp.srcArgs.getCodePath()
9749 + " to " + pkg.applicationInfo.sourceDir
9750 + " Aborting move and returning error");
9751 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9752 } else {
9753 final String oldCodePath = pkg.mPath;
9754 final String newCodePath = mp.targetArgs.getCodePath();
9755 final String newResPath = mp.targetArgs.getResourcePath();
9756 final String newNativePath = mp.targetArgs
9757 .getNativeLibraryPath();
Kenny Root6a6b0072010-10-07 16:46:10 -07009758
Kenny Rootbf023582012-05-02 16:56:15 -07009759 try {
9760 final File newNativeDir = new File(newNativePath);
9761
9762 final String libParentDir = newNativeDir.getParentFile()
9763 .getCanonicalPath();
9764 if (newNativeDir.getParentFile().getCanonicalPath()
9765 .equals(pkg.applicationInfo.dataDir)) {
9766 if (mInstaller
9767 .unlinkNativeLibraryDirectory(pkg.applicationInfo.dataDir) < 0) {
9768 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9769 } else {
9770 NativeLibraryHelper.copyNativeBinariesIfNeededLI(
9771 new File(newCodePath), newNativeDir);
9772 }
Kenny Root6a6b0072010-10-07 16:46:10 -07009773 } else {
Kenny Rootbf023582012-05-02 16:56:15 -07009774 if (mInstaller.linkNativeLibraryDirectory(
9775 pkg.applicationInfo.dataDir, newNativePath) < 0) {
9776 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9777 }
Kenny Root6a6b0072010-10-07 16:46:10 -07009778 }
Kenny Rootbf023582012-05-02 16:56:15 -07009779 } catch (IOException e) {
9780 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Kenny Root6a6b0072010-10-07 16:46:10 -07009781 }
9782
Kenny Rootbf023582012-05-02 16:56:15 -07009783
Kenny Root6a6b0072010-10-07 16:46:10 -07009784 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9785 pkg.mPath = newCodePath;
9786 // Move dex files around
9787 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
9788 // Moving of dex files failed. Set
9789 // error code and abort move.
9790 pkg.mPath = pkg.mScanPath;
9791 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9792 }
9793 }
9794
9795 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
Kenny Root447106f2011-03-23 11:00:15 -07009796 pkg.mScanPath = newCodePath;
9797 pkg.applicationInfo.sourceDir = newCodePath;
9798 pkg.applicationInfo.publicSourceDir = newResPath;
9799 pkg.applicationInfo.nativeLibraryDir = newNativePath;
9800 PackageSetting ps = (PackageSetting) pkg.mExtras;
9801 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9802 ps.codePathString = ps.codePath.getPath();
9803 ps.resourcePath = new File(
9804 pkg.applicationInfo.publicSourceDir);
9805 ps.resourcePathString = ps.resourcePath.getPath();
9806 ps.nativeLibraryPathString = newNativePath;
9807 // Set the application info flag
9808 // correctly.
9809 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9810 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9811 } else {
9812 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9813 }
9814 ps.setFlags(pkg.applicationInfo.flags);
9815 mAppDirs.remove(oldCodePath);
9816 mAppDirs.put(newCodePath, pkg);
9817 // Persist settings
9818 mSettings.writeLPr();
9819 }
9820 }
9821 }
9822 }
9823 // Send resources available broadcast
9824 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
9825 }
9826 }
9827 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9828 // Clean up failed installation
9829 if (mp.targetArgs != null) {
Kenny Root6dceb882012-04-12 14:23:49 -07009830 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
9831 -1);
Kenny Root447106f2011-03-23 11:00:15 -07009832 }
9833 } else {
9834 // Force a gc to clear things up.
9835 Runtime.getRuntime().gc();
9836 // Delete older code
9837 synchronized (mInstallLock) {
9838 mp.srcArgs.doPostDeleteLI(true);
9839 }
9840 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009841
Kenny Root447106f2011-03-23 11:00:15 -07009842 // Allow more operations on this file if we didn't fail because
9843 // an operation was already pending for this package.
9844 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
9845 synchronized (mPackages) {
9846 PackageParser.Package pkg = mPackages.get(mp.packageName);
9847 if (pkg != null) {
9848 pkg.mOperationPending = false;
Kenny Rootdeb11262010-08-02 11:36:21 -07009849 }
9850 }
Kenny Root447106f2011-03-23 11:00:15 -07009851 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009852
Kenny Root447106f2011-03-23 11:00:15 -07009853 IPackageMoveObserver observer = mp.observer;
9854 if (observer != null) {
9855 try {
9856 observer.packageMoved(mp.packageName, returnCode);
9857 } catch (RemoteException e) {
9858 Log.i(TAG, "Observer no longer exists.");
9859 }
9860 }
9861 }
9862 });
9863 }
9864
9865 public boolean setInstallLocation(int loc) {
9866 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
9867 null);
9868 if (getInstallLocation() == loc) {
9869 return true;
9870 }
9871 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
9872 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9873 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9874 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9875 return true;
9876 }
9877 return false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009878 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009879
Kenny Root447106f2011-03-23 11:00:15 -07009880 public int getInstallLocation() {
9881 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9882 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION,
9883 PackageHelper.APP_INSTALL_AUTO);
9884 }
Amith Yamasani0b285492011-04-14 17:35:23 -07009885
Amith Yamasani258848d2012-08-10 17:06:33 -07009886 /** Called by UserManagerService */
Dianne Hackborn4428e172012-08-24 17:43:05 -07009887 void cleanUpUserLILPw(int userHandle) {
Amith Yamasani13593602012-03-22 16:16:17 -07009888 // Disable all the packages for the user first
Dianne Hackborn4428e172012-08-24 17:43:05 -07009889 Set<Entry<String, PackageSetting>> entries = mSettings.mPackages.entrySet();
9890 for (Entry<String, PackageSetting> entry : entries) {
9891 entry.getValue().removeUser(userHandle);
9892 }
9893 if (mDirtyUsers.remove(userHandle));
9894 mSettings.removeUserLPr(userHandle);
9895 if (mInstaller != null) {
9896 // Technically, we shouldn't be doing this with the package lock
9897 // held. However, this is very rare, and there is already so much
9898 // other disk I/O going on, that we'll let it slide for now.
9899 mInstaller.removeUserDataDirs(userHandle);
9900 }
9901 }
9902
9903 /** Called by UserManagerService */
9904 void createNewUserLILPw(int userHandle, File path) {
9905 if (mInstaller != null) {
9906 path.mkdir();
9907 FileUtils.setPermissions(path.toString(), FileUtils.S_IRWXU | FileUtils.S_IRWXG
9908 | FileUtils.S_IXOTH, -1, -1);
9909 for (PackageSetting ps : mSettings.mPackages.values()) {
9910 // Only system apps are initially installed.
9911 ps.setInstalled((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0, userHandle);
9912 // Need to create a data directory for all apps under this user.
9913 mInstaller.createUserData(ps.name,
9914 UserHandle.getUid(userHandle, ps.appId), userHandle);
Amith Yamasani13593602012-03-22 16:16:17 -07009915 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07009916 mSettings.writePackageRestrictionsLPr(userHandle);
Amith Yamasani13593602012-03-22 16:16:17 -07009917 }
9918 }
9919
Kenny Root0aaa0d92011-09-12 16:42:55 -07009920 @Override
9921 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
9922 mContext.enforceCallingOrSelfPermission(
9923 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9924 "Only package verification agents can read the verifier device identity");
9925
9926 synchronized (mPackages) {
9927 return mSettings.getVerifierDeviceIdentityLPw();
9928 }
9929 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009930
Amith Yamasani13593602012-03-22 16:16:17 -07009931 @Override
Jeff Sharkey5d32e772012-04-12 15:59:23 -07009932 public void setPermissionEnforced(String permission, boolean enforced) {
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07009933 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
9934 if (READ_EXTERNAL_STORAGE.equals(permission)) {
9935 synchronized (mPackages) {
Jeff Sharkeyf5385772012-05-11 14:04:41 -07009936 if (mSettings.mReadExternalStorageEnforced == null
9937 || mSettings.mReadExternalStorageEnforced != enforced) {
Jeff Sharkey5d32e772012-04-12 15:59:23 -07009938 mSettings.mReadExternalStorageEnforced = enforced;
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07009939 mSettings.writeLPr();
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07009940
9941 // kill any non-foreground processes so we restart them and
9942 // grant/revoke the GID.
9943 final IActivityManager am = ActivityManagerNative.getDefault();
9944 if (am != null) {
9945 final long token = Binder.clearCallingIdentity();
9946 try {
9947 am.killProcessesBelowForeground("setPermissionEnforcement");
9948 } catch (RemoteException e) {
9949 } finally {
9950 Binder.restoreCallingIdentity(token);
9951 }
9952 }
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07009953 }
9954 }
9955 } else {
9956 throw new IllegalArgumentException("No selective enforcement for " + permission);
9957 }
9958 }
9959
9960 @Override
Jeff Sharkey5d32e772012-04-12 15:59:23 -07009961 public boolean isPermissionEnforced(String permission) {
Jeff Sharkey5d32e772012-04-12 15:59:23 -07009962 synchronized (mPackages) {
9963 return isPermissionEnforcedLocked(permission);
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07009964 }
9965 }
9966
9967 private boolean isPermissionEnforcedLocked(String permission) {
9968 if (READ_EXTERNAL_STORAGE.equals(permission)) {
Jeff Sharkeyf5385772012-05-11 14:04:41 -07009969 if (mSettings.mReadExternalStorageEnforced != null) {
9970 return mSettings.mReadExternalStorageEnforced;
9971 } else {
9972 // if user hasn't defined, fall back to secure default
9973 return Secure.getInt(mContext.getContentResolver(),
9974 Secure.READ_EXTERNAL_STORAGE_ENFORCED_DEFAULT, 0) != 0;
9975 }
Jeff Sharkey5d32e772012-04-12 15:59:23 -07009976 } else {
9977 return true;
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07009978 }
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07009979 }
Jeff Sharkeyf6f7f1d2012-06-12 17:12:08 -07009980
9981 public boolean isStorageLow() {
9982 final long token = Binder.clearCallingIdentity();
9983 try {
9984 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
9985 .getService(DeviceStorageMonitorService.SERVICE);
9986 return dsm.isMemoryLow();
9987 } finally {
9988 Binder.restoreCallingIdentity(token);
9989 }
9990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009991}