blob: 8cdca1f891aca14f074a242a9020f1e7e78cd7c6 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Rootcf0b38c2011-03-22 14:17:59 -070017package com.android.server.pm;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080018
Jeff Sharkey854b2b12012-04-13 16:03:40 -070019import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
Kenny Root27989422011-02-23 16:28:26 -080021import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
Dianne Hackbornfd7aded2013-01-22 17:10:23 -080023import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
Dianne Hackborn0ac30312011-06-17 14:49:23 -070024import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
Kenny Root27989422011-02-23 16:28:26 -080025import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
Jeff Sharkey854b2b12012-04-13 16:03:40 -070026import static com.android.internal.util.ArrayUtils.appendInt;
27import static com.android.internal.util.ArrayUtils.removeInt;
Kenny Rootddbe50d2012-09-06 13:18:37 -070028import static libcore.io.OsConstants.S_IRWXU;
29import static libcore.io.OsConstants.S_IRGRP;
30import static libcore.io.OsConstants.S_IXGRP;
31import static libcore.io.OsConstants.S_IROTH;
32import static libcore.io.OsConstants.S_IXOTH;
Kenny Root27989422011-02-23 16:28:26 -080033
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080034import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import com.android.internal.app.ResolverActivity;
Kenny Root85387d72010-08-26 10:13:11 -070036import com.android.internal.content.NativeLibraryHelper;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080037import com.android.internal.content.PackageHelper;
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -070038import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080039import com.android.internal.util.XmlUtils;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070040import com.android.server.DeviceStorageMonitorService;
41import com.android.server.EventLogTags;
42import com.android.server.IntentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043
Jason parksa3cdaa52011-01-13 14:15:43 -060044import org.xmlpull.v1.XmlPullParser;
45import org.xmlpull.v1.XmlPullParserException;
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -070046import org.xmlpull.v1.XmlSerializer;
Jason parksa3cdaa52011-01-13 14:15:43 -060047
rich canningsa2064df2012-09-30 14:52:41 -070048import android.app.ActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.app.ActivityManagerNative;
50import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080051import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080052import android.app.backup.IBackupManager;
Kenny Root5ab21572011-07-27 11:11:19 -070053import android.content.BroadcastReceiver;
Jason parksa3cdaa52011-01-13 14:15:43 -060054import android.content.ComponentName;
Kenny Root27989422011-02-23 16:28:26 -080055import android.content.Context;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070056import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.content.Intent;
58import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070059import android.content.IntentSender;
Jason parks1125d782011-01-12 09:47:26 -060060import android.content.ServiceConnection;
Jason parksa3cdaa52011-01-13 14:15:43 -060061import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.content.pm.ActivityInfo;
63import android.content.pm.ApplicationInfo;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -070064import android.content.pm.ContainerEncryptionParams;
Dianne Hackborn49237342009-08-27 20:08:01 -070065import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.content.pm.IPackageDataObserver;
67import android.content.pm.IPackageDeleteObserver;
68import android.content.pm.IPackageInstallObserver;
69import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080070import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.content.pm.IPackageStatsObserver;
72import android.content.pm.InstrumentationInfo;
Dianne Hackborn7767eac2012-08-23 18:25:40 -070073import android.content.pm.PackageCleanItem;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080075import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.content.pm.PackageManager;
Jason parksa3cdaa52011-01-13 14:15:43 -060077import android.content.pm.PackageParser;
Dianne Hackborn7767eac2012-08-23 18:25:40 -070078import android.content.pm.PackageUserState;
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -070079import android.content.pm.PackageParser.ActivityIntentInfo;
Kenny Root27989422011-02-23 16:28:26 -080080import android.content.pm.PackageStats;
Kenny Root0e2c0f32011-04-15 17:50:10 -070081import android.content.pm.ParceledListSlice;
Jason parksa3cdaa52011-01-13 14:15:43 -060082import android.content.pm.PermissionGroupInfo;
Kenny Root27989422011-02-23 16:28:26 -080083import android.content.pm.PermissionInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.content.pm.ProviderInfo;
85import android.content.pm.ResolveInfo;
86import android.content.pm.ServiceInfo;
87import android.content.pm.Signature;
Kenny Root5ab21572011-07-27 11:11:19 -070088import android.content.pm.ManifestDigest;
rich cannings706e8ba2012-08-20 13:20:14 -070089import android.content.pm.VerificationParams;
Kenny Root0aaa0d92011-09-12 16:42:55 -070090import android.content.pm.VerifierDeviceIdentity;
Kenny Root05ca4c92011-09-15 10:36:25 -070091import android.content.pm.VerifierInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.net.Uri;
93import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070094import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.os.Bundle;
Kenny Root27989422011-02-23 16:28:26 -080096import android.os.Environment;
97import android.os.FileObserver;
98import android.os.FileUtils;
99import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800101import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700102import android.os.Looper;
103import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import android.os.Parcel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import android.os.ParcelFileDescriptor;
106import android.os.Process;
Kenny Root27989422011-02-23 16:28:26 -0800107import android.os.RemoteException;
rpcraig554cb0c2012-07-05 06:41:43 -0400108import android.os.SELinux;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import android.os.ServiceManager;
110import android.os.SystemClock;
111import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700112import android.os.UserHandle;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700113import android.os.Environment.UserEnvironment;
Kenny Rootd72317a2013-04-01 15:59:59 -0700114import android.os.UserManager;
115import android.provider.Settings.Secure;
116import android.security.KeyStore;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800117import android.security.SystemKeyStore;
Kenny Root27989422011-02-23 16:28:26 -0800118import android.util.DisplayMetrics;
119import android.util.EventLog;
120import android.util.Log;
121import android.util.LogPrinter;
122import android.util.Slog;
123import android.util.SparseArray;
124import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125import android.view.Display;
126import android.view.WindowManager;
127
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -0700128import java.io.BufferedOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129import java.io.File;
130import java.io.FileDescriptor;
131import java.io.FileInputStream;
132import java.io.FileNotFoundException;
133import java.io.FileOutputStream;
134import java.io.FileReader;
135import java.io.FilenameFilter;
136import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800138import java.security.NoSuchAlgorithmException;
Kenny Root05ca4c92011-09-15 10:36:25 -0700139import java.security.PublicKey;
140import java.security.cert.CertificateException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800141import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142import java.util.ArrayList;
143import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700144import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145import java.util.Collections;
146import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800147import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148import java.util.HashMap;
149import java.util.HashSet;
150import java.util.Iterator;
151import java.util.List;
152import java.util.Map;
153import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154
Kenny Root66269ea2011-07-12 14:14:01 -0700155import libcore.io.ErrnoException;
Kenny Root3f99afc2012-04-14 10:13:10 -0700156import libcore.io.IoUtils;
Kenny Root66269ea2011-07-12 14:14:01 -0700157import libcore.io.Libcore;
Kenny Root786cbca2012-08-16 11:10:58 -0700158import libcore.io.StructStat;
Kenny Root66269ea2011-07-12 14:14:01 -0700159
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700160/**
161 * Keep track of all those .apks everywhere.
162 *
163 * This is very central to the platform's security; please run the unit
164 * tests whenever making modifications here:
165 *
166mmm frameworks/base/tests/AndroidTests
167adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
168adb 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 -0700169 *
170 * {@hide}
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700171 */
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700172public class PackageManagerService extends IPackageManager.Stub {
173 static final String TAG = "PackageManager";
174 static final boolean DEBUG_SETTINGS = false;
Dianne Hackbornc895be72013-03-11 17:48:43 -0700175 static final boolean DEBUG_PREFERRED = false;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700176 static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800177 private static final boolean DEBUG_INSTALL = false;
Kenny Root9718cf52011-02-23 16:45:26 -0800178 private static final boolean DEBUG_REMOVE = false;
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700179 private static final boolean DEBUG_BROADCASTS = false;
Kenny Root9718cf52011-02-23 16:45:26 -0800180 private static final boolean DEBUG_SHOW_INFO = false;
181 private static final boolean DEBUG_PACKAGE_INFO = false;
182 private static final boolean DEBUG_INTENT_MATCHING = false;
183 private static final boolean DEBUG_PACKAGE_SCANNING = false;
184 private static final boolean DEBUG_APP_DIR_OBSERVER = false;
Kenny Root05ca4c92011-09-15 10:36:25 -0700185 private static final boolean DEBUG_VERIFY = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400188 private static final int LOG_UID = Process.LOG_UID;
Nick Pellycd0e8392010-10-13 17:25:24 -0700189 private static final int NFC_UID = Process.NFC_UID;
Jaikumar Ganesh1abb1cb2012-01-25 16:14:50 -0800190 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800191 private static final int SHELL_UID = Process.SHELL_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 private static final boolean GET_CERTIFICATES = true;
194
195 private static final int REMOVE_EVENTS =
196 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
197 private static final int ADD_EVENTS =
198 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
199
200 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800201 // Suffix used during package installation when copying/moving
202 // package apks to install directory.
203 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
205 static final int SCAN_MONITOR = 1<<0;
206 static final int SCAN_NO_DEX = 1<<1;
207 static final int SCAN_FORCE_DEX = 1<<2;
208 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800209 static final int SCAN_NEW_INSTALL = 1<<4;
210 static final int SCAN_NO_PATHS = 1<<5;
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700211 static final int SCAN_UPDATE_TIME = 1<<6;
Dianne Hackborn661cd522011-08-22 00:26:20 -0700212 static final int SCAN_DEFER_DEX = 1<<7;
Dianne Hackbornd0c5f512012-06-07 16:53:59 -0700213 static final int SCAN_BOOTING = 1<<8;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700215 static final int REMOVE_CHATTY = 1<<16;
Kenny Root11128572010-10-11 10:51:32 -0700216
Kenny Root5ab21572011-07-27 11:11:19 -0700217 /**
218 * Whether verification is enabled by default.
219 */
rich cannings36c67c22012-09-16 16:20:23 -0700220 private static final boolean DEFAULT_VERIFY_ENABLE = true;
Kenny Root5ab21572011-07-27 11:11:19 -0700221
222 /**
223 * The default maximum time to wait for the verification agent to return in
224 * milliseconds.
225 */
rich canningsaa8513e2012-05-21 16:15:23 -0700226 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
Kenny Root5ab21572011-07-27 11:11:19 -0700227
rich canningsa6cfe522012-05-21 15:50:56 -0700228 /**
229 * The default response for package verification timeout.
230 *
231 * This can be either PackageManager.VERIFICATION_ALLOW or
232 * PackageManager.VERIFICATION_REJECT.
233 */
234 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
235
Kenny Root11128572010-10-11 10:51:32 -0700236 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
237
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800238 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
Kenny Root11128572010-10-11 10:51:32 -0700239 DEFAULT_CONTAINER_PACKAGE,
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800240 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700241
Kenny Root05ca4c92011-09-15 10:36:25 -0700242 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
243
Kenny Root85387d72010-08-26 10:13:11 -0700244 private static final String LIB_DIR_NAME = "lib";
245
Kenny Rootc78a8072010-07-27 15:18:38 -0700246 static final String mTempContainerPrefix = "smdl2tmp";
247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
249 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700250 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251
Dianne Hackborn851a5412009-05-08 12:06:44 -0700252 final int mSdkVersion = Build.VERSION.SDK_INT;
253 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
254 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 final Context mContext;
257 final boolean mFactoryTest;
Dianne Hackbornd2509fd2011-09-12 12:29:43 -0700258 final boolean mOnlyCore;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700259 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 final DisplayMetrics mMetrics;
261 final int mDefParseFlags;
262 final String[] mSeparateProcesses;
263
264 // This is where all application persistent data goes.
265 final File mAppDataDir;
266
Amith Yamasani0b285492011-04-14 17:35:23 -0700267 // This is where all application persistent data goes for secondary users.
268 final File mUserAppDataDir;
269
Kenny Root51a573c2012-05-17 13:30:28 -0700270 /** The location for ASEC container files on internal storage. */
271 final String mAsecInternalPath;
272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 // This is the object monitoring the framework dir.
274 final FileObserver mFrameworkInstallObserver;
275
276 // This is the object monitoring the system app dir.
277 final FileObserver mSystemInstallObserver;
278
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700279 // This is the object monitoring the system app dir.
280 final FileObserver mVendorInstallObserver;
281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 // This is the object monitoring mAppInstallDir.
283 final FileObserver mAppInstallObserver;
284
285 // This is the object monitoring mDrmAppPrivateInstallDir.
286 final FileObserver mDrmAppInstallObserver;
287
Kenny Rootddbe50d2012-09-06 13:18:37 -0700288 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 // LOCK HELD. Can be called with mInstallLock held.
290 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 final File mFrameworkDir;
293 final File mSystemAppDir;
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700294 final File mVendorAppDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700296 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297
Kenny Rootddbe50d2012-09-06 13:18:37 -0700298 /**
299 * Directory to which applications installed internally have native
300 * libraries copied.
301 */
302 private File mAppLibInstallDir;
303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
305 // apps.
306 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 // Lock for state used when installing and doing other long running
311 // operations. Methods that must be called with this lock held have
312 // the prefix "LI".
313 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 // These are the directories in the 3rd party applications installed dir
316 // that we have currently loaded packages from. Keys are the application's
317 // installed zip file (absolute codePath), and values are Package.
318 final HashMap<String, PackageParser.Package> mAppDirs =
319 new HashMap<String, PackageParser.Package>();
320
321 // Information for the parser to write more useful error messages.
322 File mScanningPath;
323 int mLastScanError;
324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 // Keys are String (package name), values are Package. This also serves
328 // as the lock for the global state. Methods that must be called with
329 // this lock held have the prefix "LP".
330 final HashMap<String, PackageParser.Package> mPackages =
331 new HashMap<String, PackageParser.Package>();
332
333 final Settings mSettings;
334 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335
336 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
337 int[] mGlobalGids;
338
339 // These are the built-in uid -> permission mappings that were read from the
340 // etc/permissions.xml file.
341 final SparseArray<HashSet<String>> mSystemPermissions =
342 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800343
Dianne Hackbornc895be72013-03-11 17:48:43 -0700344 static final class SharedLibraryEntry {
345 final String path;
346 final String apk;
347
348 SharedLibraryEntry(String _path, String _apk) {
349 path = _path;
350 apk = _apk;
351 }
352 }
353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354 // These are the built-in shared libraries that were read from the
355 // etc/permissions.xml file.
Dianne Hackbornc895be72013-03-11 17:48:43 -0700356 final HashMap<String, SharedLibraryEntry> mSharedLibraries
357 = new HashMap<String, SharedLibraryEntry>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800358
Dianne Hackborn49237342009-08-27 20:08:01 -0700359 // Temporary for building the final shared libraries for an .apk.
360 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800361
Dianne Hackborn49237342009-08-27 20:08:01 -0700362 // These are the features this devices supports that were read from the
363 // etc/permissions.xml file.
364 final HashMap<String, FeatureInfo> mAvailableFeatures =
365 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800366
Robert Craig0f40dc92013-03-25 06:33:03 -0400367 // If mac_permissions.xml was found for seinfo labeling.
368 boolean mFoundPolicyFile;
369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 // All available activities, for your resolving pleasure.
371 final ActivityIntentResolver mActivities =
372 new ActivityIntentResolver();
373
374 // All available receivers, for your resolving pleasure.
375 final ActivityIntentResolver mReceivers =
376 new ActivityIntentResolver();
377
378 // All available services, for your resolving pleasure.
379 final ServiceIntentResolver mServices = new ServiceIntentResolver();
380
381 // Keys are String (provider class name), values are Provider.
382 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
383 new HashMap<ComponentName, PackageParser.Provider>();
384
385 // Mapping from provider base names (first directory in content URI codePath)
386 // to the provider information.
387 final HashMap<String, PackageParser.Provider> mProviders =
388 new HashMap<String, PackageParser.Provider>();
389
390 // Mapping from instrumentation class names to info about them.
391 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
392 new HashMap<ComponentName, PackageParser.Instrumentation>();
393
394 // Mapping from permission names to info about them.
395 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
396 new HashMap<String, PackageParser.PermissionGroup>();
397
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800398 // Packages whose data we have transfered into another package, thus
399 // should no longer exist.
400 final HashSet<String> mTransferedPackages = new HashSet<String>();
401
Dianne Hackborn854060af2009-07-09 18:14:31 -0700402 // Broadcast actions that are only available to the system.
403 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800404
Kenny Root5ab21572011-07-27 11:11:19 -0700405 /** List of packages waiting for verification. */
Kenny Root05ca4c92011-09-15 10:36:25 -0700406 final SparseArray<PackageVerificationState> mPendingVerification
407 = new SparseArray<PackageVerificationState>();
Kenny Root5ab21572011-07-27 11:11:19 -0700408
Dianne Hackbornc895be72013-03-11 17:48:43 -0700409 HashSet<PackageParser.Package> mDeferredDexOpt = null;
Dianne Hackborn661cd522011-08-22 00:26:20 -0700410
Kenny Root5ab21572011-07-27 11:11:19 -0700411 /** Token for keys in mPendingVerification. */
412 private int mPendingVerificationToken = 0;
413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 boolean mSystemReady;
415 boolean mSafeMode;
416 boolean mHasSystemUidErrors;
417
418 ApplicationInfo mAndroidApplication;
419 final ActivityInfo mResolveActivity = new ActivityInfo();
420 final ResolveInfo mResolveInfo = new ResolveInfo();
421 ComponentName mResolveComponentName;
422 PackageParser.Package mPlatformPackage;
423
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700424 // Set of pending broadcasts for aggregating enable/disable of components.
Christopher Tate1e08f5c2013-05-02 13:27:27 -0700425 static class PendingPackageBroadcasts {
426 // for each user id, a map of <package name -> components within that package>
427 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
428
429 public PendingPackageBroadcasts() {
430 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>();
431 }
432
433 public ArrayList<String> get(int userId, String packageName) {
434 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
435 return packages.get(packageName);
436 }
437
438 public void put(int userId, String packageName, ArrayList<String> components) {
439 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
440 packages.put(packageName, components);
441 }
442
443 public void remove(int userId, String packageName) {
444 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
445 if (packages != null) {
446 packages.remove(packageName);
447 }
448 }
449
450 public void remove(int userId) {
451 mUidMap.remove(userId);
452 }
453
454 public int userIdCount() {
455 return mUidMap.size();
456 }
457
458 public int userIdAt(int n) {
459 return mUidMap.keyAt(n);
460 }
461
462 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
463 return mUidMap.get(userId);
464 }
465
466 public int size() {
467 // total number of pending broadcast entries across all userIds
468 int num = 0;
469 for (int i = 0; i< mUidMap.size(); i++) {
470 num += mUidMap.valueAt(i).size();
471 }
472 return num;
473 }
474
475 public void clear() {
476 mUidMap.clear();
477 }
478
479 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
480 HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
481 if (map == null) {
482 map = new HashMap<String, ArrayList<String>>();
483 mUidMap.put(userId, map);
484 }
485 return map;
486 }
487 }
488 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
489
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800490 // Service Connection to remote media container service to copy
491 // package uri's from external media onto secure containers
492 // or internal storage.
493 private IMediaContainerService mContainerService = null;
494
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700495 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800496 static final int MCS_BOUND = 3;
497 static final int END_COPY = 4;
498 static final int INIT_COPY = 5;
499 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800500 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800501 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800502 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800503 static final int MCS_RECONNECT = 10;
504 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700505 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700506 static final int WRITE_SETTINGS = 13;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700507 static final int WRITE_PACKAGE_RESTRICTIONS = 14;
Kenny Root5ab21572011-07-27 11:11:19 -0700508 static final int PACKAGE_VERIFIED = 15;
509 static final int CHECK_PENDING_VERIFICATION = 16;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700510
511 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800512
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700513 // Delay time in millisecs
514 static final int BROADCAST_DELAY = 10 * 1000;
Kenny Root9718cf52011-02-23 16:45:26 -0800515
Amith Yamasani258848d2012-08-10 17:06:33 -0700516 static UserManagerService sUserManager;
Amith Yamasani0b285492011-04-14 17:35:23 -0700517
Amith Yamasani483f3b02012-03-13 16:08:00 -0700518 // Stores a list of users whose package restrictions file needs to be updated
519 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
520
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800521 final private DefaultContainerConnection mDefContainerConn =
522 new DefaultContainerConnection();
523 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800524 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800525 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800526 IMediaContainerService imcs =
527 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800528 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800529 }
530
531 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800532 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800533 }
534 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700535
Christopher Tate1bb69062010-02-19 17:02:12 -0800536 // Recordkeeping of restore-after-install operations that are currently in flight
537 // between the Package Manager and the Backup Manager
538 class PostInstallData {
539 public InstallArgs args;
540 public PackageInstalledInfo res;
541
542 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
543 args = _a;
544 res = _r;
545 }
546 };
547 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
548 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
549
Kenny Root05ca4c92011-09-15 10:36:25 -0700550 private final String mRequiredVerifierPackage;
551
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700552 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800553 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800554 final ArrayList<HandlerParams> mPendingInstalls =
555 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800556
557 private boolean connectToService() {
558 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
559 " DefaultContainerService");
560 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700561 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Amith Yamasani27b89e62013-01-16 12:30:11 -0800562 if (mContext.bindServiceAsUser(service, mDefContainerConn,
563 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700564 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800565 mBound = true;
566 return true;
567 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700568 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800569 return false;
570 }
571
572 private void disconnectService() {
573 mContainerService = null;
574 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700575 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800576 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700577 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800578 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800579
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700580 PackageHandler(Looper looper) {
581 super(looper);
582 }
Dianne Hackborn7d608422011-08-07 16:24:18 -0700583
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700584 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700585 try {
586 doHandleMessage(msg);
587 } finally {
588 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
589 }
590 }
591
592 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700593 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800594 case INIT_COPY: {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800595 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800596 int idx = mPendingInstalls.size();
Dianne Hackbornc895be72013-03-11 17:48:43 -0700597 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800598 // If a bind was already initiated we dont really
599 // need to do anything. The pending install
600 // will be processed later on.
601 if (!mBound) {
602 // If this is the only one pending we might
603 // have to bind to the service again.
604 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800605 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800606 params.serviceError();
607 return;
608 } else {
609 // Once we bind to the service, the first
610 // pending request will be processed.
611 mPendingInstalls.add(idx, params);
612 }
613 } else {
614 mPendingInstalls.add(idx, params);
615 // Already bound to the service. Just make
616 // sure we trigger off processing the first request.
617 if (idx == 0) {
618 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800619 }
620 }
621 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800622 }
623 case MCS_BOUND: {
Kenny Root5ab21572011-07-27 11:11:19 -0700624 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800625 if (msg.obj != null) {
626 mContainerService = (IMediaContainerService) msg.obj;
627 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800628 if (mContainerService == null) {
629 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800630 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800631 for (HandlerParams params : mPendingInstalls) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800632 // Indicate service bind error
633 params.serviceError();
634 }
635 mPendingInstalls.clear();
636 } else if (mPendingInstalls.size() > 0) {
637 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800638 if (params != null) {
Dianne Hackborn7d608422011-08-07 16:24:18 -0700639 if (params.startCopy()) {
640 // We are done... look for more work or to
641 // go idle.
642 if (DEBUG_SD_INSTALL) Log.i(TAG,
643 "Checking for more work or unbind...");
644 // Delete pending install
645 if (mPendingInstalls.size() > 0) {
646 mPendingInstalls.remove(0);
647 }
648 if (mPendingInstalls.size() == 0) {
649 if (mBound) {
650 if (DEBUG_SD_INSTALL) Log.i(TAG,
651 "Posting delayed MCS_UNBIND");
652 removeMessages(MCS_UNBIND);
653 Message ubmsg = obtainMessage(MCS_UNBIND);
654 // Unbind after a little delay, to avoid
655 // continual thrashing.
656 sendMessageDelayed(ubmsg, 10000);
657 }
658 } else {
659 // There are more pending requests in queue.
660 // Just post MCS_BOUND message to trigger processing
661 // of next pending install.
662 if (DEBUG_SD_INSTALL) Log.i(TAG,
663 "Posting MCS_BOUND for next woek");
664 mHandler.sendEmptyMessage(MCS_BOUND);
665 }
666 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800667 }
668 } else {
669 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800670 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800671 }
672 break;
673 }
Kenny Root5ab21572011-07-27 11:11:19 -0700674 case MCS_RECONNECT: {
675 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800676 if (mPendingInstalls.size() > 0) {
677 if (mBound) {
678 disconnectService();
679 }
680 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800681 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800682 for (HandlerParams params : mPendingInstalls) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800683 // Indicate service bind error
684 params.serviceError();
685 }
686 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800687 }
688 }
689 break;
690 }
Kenny Root5ab21572011-07-27 11:11:19 -0700691 case MCS_UNBIND: {
Dianne Hackborn7d608422011-08-07 16:24:18 -0700692 // If there is no actual work left, then time to unbind.
Kenny Root5ab21572011-07-27 11:11:19 -0700693 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
694
695 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800696 if (mBound) {
Kenny Root5ab21572011-07-27 11:11:19 -0700697 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
698
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800699 disconnectService();
700 }
Kenny Root5ab21572011-07-27 11:11:19 -0700701 } else if (mPendingInstalls.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800702 // There are more pending requests in queue.
703 // Just post MCS_BOUND message to trigger processing
704 // of next pending install.
705 mHandler.sendEmptyMessage(MCS_BOUND);
706 }
Kenny Root5ab21572011-07-27 11:11:19 -0700707
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800708 break;
709 }
710 case MCS_GIVE_UP: {
Kenny Root5ab21572011-07-27 11:11:19 -0700711 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
Kenny Root60f7ad82011-03-22 12:49:06 -0700712 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800713 break;
714 }
Kenny Root5ab21572011-07-27 11:11:19 -0700715 case SEND_PENDING_BROADCAST: {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800716 String packages[];
Kenny Root60f7ad82011-03-22 12:49:06 -0700717 ArrayList<String> components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700718 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700719 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700720 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700721 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800722 if (mPendingBroadcasts == null) {
723 return;
724 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700725 size = mPendingBroadcasts.size();
726 if (size <= 0) {
727 // Nothing to be done. Just return
728 return;
729 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800730 packages = new String[size];
731 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700732 uids = new int[size];
Christopher Tate1e08f5c2013-05-02 13:27:27 -0700733 int i = 0; // filling out the above arrays
734
735 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
736 int packageUserId = mPendingBroadcasts.userIdAt(n);
737 Iterator<Map.Entry<String, ArrayList<String>>> it
738 = mPendingBroadcasts.packagesForUserId(packageUserId)
739 .entrySet().iterator();
740 while (it.hasNext() && i < size) {
741 Map.Entry<String, ArrayList<String>> ent = it.next();
742 packages[i] = ent.getKey();
743 components[i] = ent.getValue();
744 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
745 uids[i] = (ps != null)
746 ? UserHandle.getUid(packageUserId, ps.appId)
747 : -1;
748 i++;
749 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700750 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800751 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700752 mPendingBroadcasts.clear();
753 }
754 // Send broadcasts
755 for (int i = 0; i < size; i++) {
Kenny Root60f7ad82011-03-22 12:49:06 -0700756 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700757 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700758 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700759 break;
760 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800761 case START_CLEANING_PACKAGE: {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700762 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Jeff Sharkey752cd922012-09-23 16:25:12 -0700763 final String packageName = (String)msg.obj;
764 final int userId = msg.arg1;
765 final boolean andCode = msg.arg2 != 0;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800766 synchronized (mPackages) {
Jeff Sharkey752cd922012-09-23 16:25:12 -0700767 if (userId == UserHandle.USER_ALL) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700768 int[] users = sUserManager.getUserIds();
769 for (int user : users) {
Jeff Sharkey752cd922012-09-23 16:25:12 -0700770 mSettings.addPackageToCleanLPw(
771 new PackageCleanItem(user, packageName, andCode));
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700772 }
773 } else {
Jeff Sharkey752cd922012-09-23 16:25:12 -0700774 mSettings.addPackageToCleanLPw(
775 new PackageCleanItem(userId, packageName, andCode));
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800776 }
777 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700778 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Jeff Sharkey752cd922012-09-23 16:25:12 -0700779 startCleaningPackages();
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800780 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800781 case POST_INSTALL: {
782 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
783 PostInstallData data = mRunningInstalls.get(msg.arg1);
784 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700785 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800786
787 if (data != null) {
788 InstallArgs args = data.args;
789 PackageInstalledInfo res = data.res;
790
791 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700792 res.removedInfo.sendBroadcast(false, true, false);
Christopher Tate1bb69062010-02-19 17:02:12 -0800793 Bundle extras = new Bundle(1);
794 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackborn786b4402012-08-27 15:14:02 -0700795 // Determine the set of users who are adding this
796 // package for the first time vs. those who are seeing
797 // an update.
798 int[] firstUsers;
799 int[] updateUsers = new int[0];
800 if (res.origUsers == null || res.origUsers.length == 0) {
801 firstUsers = res.newUsers;
802 } else {
803 firstUsers = new int[0];
804 for (int i=0; i<res.newUsers.length; i++) {
805 int user = res.newUsers[i];
806 boolean isNew = true;
807 for (int j=0; j<res.origUsers.length; j++) {
808 if (res.origUsers[j] == user) {
809 isNew = false;
810 break;
811 }
812 }
813 if (isNew) {
814 int[] newFirst = new int[firstUsers.length+1];
815 System.arraycopy(firstUsers, 0, newFirst, 0,
816 firstUsers.length);
817 newFirst[firstUsers.length] = user;
818 firstUsers = newFirst;
819 } else {
820 int[] newUpdate = new int[updateUsers.length+1];
821 System.arraycopy(updateUsers, 0, newUpdate, 0,
822 updateUsers.length);
823 newUpdate[updateUsers.length] = user;
824 updateUsers = newUpdate;
825 }
826 }
827 }
828 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
829 res.pkg.applicationInfo.packageName,
830 extras, null, null, firstUsers);
Christopher Tate1bb69062010-02-19 17:02:12 -0800831 final boolean update = res.removedInfo.removedPackage != null;
832 if (update) {
833 extras.putBoolean(Intent.EXTRA_REPLACING, true);
834 }
835 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
836 res.pkg.applicationInfo.packageName,
Dianne Hackborn786b4402012-08-27 15:14:02 -0700837 extras, null, null, updateUsers);
Christopher Tate1bb69062010-02-19 17:02:12 -0800838 if (update) {
839 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
840 res.pkg.applicationInfo.packageName,
Dianne Hackborn786b4402012-08-27 15:14:02 -0700841 extras, null, null, updateUsers);
Dianne Hackborne7f97212011-02-24 14:40:20 -0800842 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
843 null, null,
Dianne Hackborn786b4402012-08-27 15:14:02 -0700844 res.pkg.applicationInfo.packageName, null, updateUsers);
Christopher Tate1bb69062010-02-19 17:02:12 -0800845 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700846 if (res.removedInfo.args != null) {
847 // Remove the replaced package's older resources safely now
848 deleteOld = true;
849 }
Matt Finifterf8a98ed2012-05-14 15:43:34 -0700850
851 // Log current value of "unknown sources" setting
852 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
853 getUnknownSourcesSettings());
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700854 }
855 // Force a gc to clear up things
856 Runtime.getRuntime().gc();
857 // We delete after a gc for applications on sdcard.
858 if (deleteOld) {
859 synchronized (mInstallLock) {
860 res.removedInfo.args.doPostDeleteLI(true);
861 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800862 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800863 if (args.observer != null) {
864 try {
865 args.observer.packageInstalled(res.name, res.returnCode);
866 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800867 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800868 }
869 }
870 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800871 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800872 }
873 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700874 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700875 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
876 boolean reportStatus = msg.arg1 == 1;
877 boolean doGc = msg.arg2 == 1;
878 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
879 if (doGc) {
880 // Force a gc to clear up stale containers.
881 Runtime.getRuntime().gc();
882 }
883 if (msg.obj != null) {
Dianne Hackbornba24e4d2011-09-01 11:17:06 -0700884 @SuppressWarnings("unchecked")
Kenny Root6dceb882012-04-12 14:23:49 -0700885 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700886 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
887 // Unload containers
888 unloadAllContainers(args);
889 }
890 if (reportStatus) {
891 try {
892 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
893 PackageHelper.getMountService().finishMediaUpdate();
894 } catch (RemoteException e) {
895 Log.e(TAG, "MountService not running?");
896 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700897 }
898 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700899 case WRITE_SETTINGS: {
900 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
901 synchronized (mPackages) {
902 removeMessages(WRITE_SETTINGS);
Amith Yamasani483f3b02012-03-13 16:08:00 -0700903 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
Kenny Root447106f2011-03-23 11:00:15 -0700904 mSettings.writeLPr();
Amith Yamasani483f3b02012-03-13 16:08:00 -0700905 mDirtyUsers.clear();
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700906 }
907 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
908 } break;
Amith Yamasani483f3b02012-03-13 16:08:00 -0700909 case WRITE_PACKAGE_RESTRICTIONS: {
Dianne Hackborne7f97212011-02-24 14:40:20 -0800910 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
911 synchronized (mPackages) {
Amith Yamasani483f3b02012-03-13 16:08:00 -0700912 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
913 for (int userId : mDirtyUsers) {
914 mSettings.writePackageRestrictionsLPr(userId);
915 }
916 mDirtyUsers.clear();
Dianne Hackborne7f97212011-02-24 14:40:20 -0800917 }
918 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
919 } break;
Kenny Root5ab21572011-07-27 11:11:19 -0700920 case CHECK_PENDING_VERIFICATION: {
921 final int verificationId = msg.arg1;
Kenny Root05ca4c92011-09-15 10:36:25 -0700922 final PackageVerificationState state = mPendingVerification.get(verificationId);
Kenny Root5ab21572011-07-27 11:11:19 -0700923
rich canningsd9ef3e52012-08-22 14:28:05 -0700924 if ((state != null) && !state.timeoutExtended()) {
Kenny Root05ca4c92011-09-15 10:36:25 -0700925 final InstallArgs args = state.getInstallArgs();
Kenny Roota503a0f2011-10-03 14:45:28 -0700926 Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
Kenny Root5ab21572011-07-27 11:11:19 -0700927 mPendingVerification.remove(verificationId);
928
rich canningsa6cfe522012-05-21 15:50:56 -0700929 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
930
931 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
rich canningsd9ef3e52012-08-22 14:28:05 -0700932 Slog.i(TAG, "Continuing with installation of "
933 + args.packageURI.toString());
934 state.setVerifierResponse(Binder.getCallingUid(),
935 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
rich canningsd1b5cfc2012-08-29 14:49:51 -0700936 broadcastPackageVerified(verificationId, args.packageURI,
rich canningsd55deb02012-10-02 14:53:08 -0700937 PackageManager.VERIFICATION_ALLOW,
938 state.getInstallArgs().getUser());
rich canningsd9ef3e52012-08-22 14:28:05 -0700939 try {
940 ret = args.copyApk(mContainerService, true);
941 } catch (RemoteException e) {
942 Slog.e(TAG, "Could not contact the ContainerService");
943 }
rich canningsd1b5cfc2012-08-29 14:49:51 -0700944 } else {
945 broadcastPackageVerified(verificationId, args.packageURI,
rich canningsd55deb02012-10-02 14:53:08 -0700946 PackageManager.VERIFICATION_REJECT,
947 state.getInstallArgs().getUser());
rich canningsa6cfe522012-05-21 15:50:56 -0700948 }
949
Kenny Root5ab21572011-07-27 11:11:19 -0700950 processPendingInstall(args, ret);
Kenny Root5ab21572011-07-27 11:11:19 -0700951 mHandler.sendEmptyMessage(MCS_UNBIND);
952 }
Kenny Root5ab21572011-07-27 11:11:19 -0700953 break;
954 }
955 case PACKAGE_VERIFIED: {
956 final int verificationId = msg.arg1;
Kenny Root5ab21572011-07-27 11:11:19 -0700957
Kenny Root05ca4c92011-09-15 10:36:25 -0700958 final PackageVerificationState state = mPendingVerification.get(verificationId);
959 if (state == null) {
Kenny Roota503a0f2011-10-03 14:45:28 -0700960 Slog.w(TAG, "Invalid verification token " + verificationId + " received");
Kenny Root5ab21572011-07-27 11:11:19 -0700961 break;
962 }
963
Kenny Root05ca4c92011-09-15 10:36:25 -0700964 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
Kenny Root5ab21572011-07-27 11:11:19 -0700965
Kenny Root05ca4c92011-09-15 10:36:25 -0700966 state.setVerifierResponse(response.callerUid, response.code);
967
968 if (state.isVerificationComplete()) {
969 mPendingVerification.remove(verificationId);
970
971 final InstallArgs args = state.getInstallArgs();
972
973 int ret;
974 if (state.isInstallAllowed()) {
975 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
rich canningsd1b5cfc2012-08-29 14:49:51 -0700976 broadcastPackageVerified(verificationId, args.packageURI,
rich canningsd55deb02012-10-02 14:53:08 -0700977 response.code, state.getInstallArgs().getUser());
Kenny Root05ca4c92011-09-15 10:36:25 -0700978 try {
979 ret = args.copyApk(mContainerService, true);
980 } catch (RemoteException e) {
981 Slog.e(TAG, "Could not contact the ContainerService");
982 }
983 } else {
984 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
Kenny Root5ab21572011-07-27 11:11:19 -0700985 }
Kenny Root05ca4c92011-09-15 10:36:25 -0700986
987 processPendingInstall(args, ret);
988
989 mHandler.sendEmptyMessage(MCS_UNBIND);
Kenny Root5ab21572011-07-27 11:11:19 -0700990 }
991
Kenny Root5ab21572011-07-27 11:11:19 -0700992 break;
993 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700994 }
995 }
996 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800997
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700998 void scheduleWriteSettingsLocked() {
999 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1000 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1001 }
1002 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07001003
1004 void scheduleWritePackageRestrictionsLocked(int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001005 if (!sUserManager.exists(userId)) return;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001006 mDirtyUsers.add(userId);
1007 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1008 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001009 }
1010 }
1011
Jeff Brownf69c8122012-09-12 17:00:34 -07001012 public static final IPackageManager main(Context context, Installer installer,
1013 boolean factoryTest, boolean onlyCore) {
1014 PackageManagerService m = new PackageManagerService(context, installer,
1015 factoryTest, onlyCore);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 ServiceManager.addService("package", m);
1017 return m;
1018 }
1019
1020 static String[] splitString(String str, char sep) {
1021 int count = 1;
1022 int i = 0;
1023 while ((i=str.indexOf(sep, i)) >= 0) {
1024 count++;
1025 i++;
1026 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 String[] res = new String[count];
1029 i=0;
1030 count = 0;
1031 int lastI=0;
1032 while ((i=str.indexOf(sep, i)) >= 0) {
1033 res[count] = str.substring(lastI, i);
1034 count++;
1035 i++;
1036 lastI = i;
1037 }
1038 res[count] = str.substring(lastI, str.length());
1039 return res;
1040 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001041
Jeff Brownf69c8122012-09-12 17:00:34 -07001042 public PackageManagerService(Context context, Installer installer,
1043 boolean factoryTest, boolean onlyCore) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001044 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001048 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 mContext = context;
1052 mFactoryTest = factoryTest;
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001053 mOnlyCore = onlyCore;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001054 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 mMetrics = new DisplayMetrics();
Amith Yamasani258848d2012-08-10 17:06:33 -07001056 mSettings = new Settings(context);
Kenny Root447106f2011-03-23 11:00:15 -07001057 mSettings.addSharedUserLPw("android.uid.system",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08001059 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, ApplicationInfo.FLAG_SYSTEM);
1060 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, ApplicationInfo.FLAG_SYSTEM);
1061 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, ApplicationInfo.FLAG_SYSTEM);
Jaikumar Ganesh1abb1cb2012-01-25 16:14:50 -08001062 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, ApplicationInfo.FLAG_SYSTEM);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001063 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064
1065 String separateProcesses = SystemProperties.get("debug.separate_processes");
1066 if (separateProcesses != null && separateProcesses.length() > 0) {
1067 if ("*".equals(separateProcesses)) {
1068 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1069 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001070 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 } else {
1072 mDefParseFlags = 0;
1073 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001074 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 + separateProcesses);
1076 }
1077 } else {
1078 mDefParseFlags = 0;
1079 mSeparateProcesses = null;
1080 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001081
Jeff Brownf69c8122012-09-12 17:00:34 -07001082 mInstaller = installer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083
1084 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
1085 Display d = wm.getDefaultDisplay();
1086 d.getMetrics(mMetrics);
1087
1088 synchronized (mInstallLock) {
Kenny Root447106f2011-03-23 11:00:15 -07001089 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 synchronized (mPackages) {
1091 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07001092 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 File dataDir = Environment.getDataDirectory();
1095 mAppDataDir = new File(dataDir, "data");
Kenny Root584c4cd2012-10-29 10:46:42 -07001096 mAppInstallDir = new File(dataDir, "app");
1097 mAppLibInstallDir = new File(dataDir, "app-lib");
Kenny Root51a573c2012-05-17 13:30:28 -07001098 mAsecInternalPath = new File(dataDir, "app-asec").getPath();
Amith Yamasani0b285492011-04-14 17:35:23 -07001099 mUserAppDataDir = new File(dataDir, "user");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1101
Dianne Hackborn4428e172012-08-24 17:43:05 -07001102 sUserManager = new UserManagerService(context, this,
1103 mInstallLock, mPackages);
Amith Yamasani0b285492011-04-14 17:35:23 -07001104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 readPermissions();
1106
Robert Craig0f40dc92013-03-25 06:33:03 -04001107 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1108
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08001109 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
Dianne Hackborn13579ed2012-11-28 18:05:36 -08001110 mSdkVersion, mOnlyCore);
Robert Craig0f40dc92013-03-25 06:33:03 -04001111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001113
1114 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001116
Suchi Amalapurapudaec1722010-01-14 21:25:16 -08001117 // Set flag to monitor and not change apk file paths when
1118 // scanning install directories.
Dianne Hackbornd0c5f512012-06-07 16:53:59 -07001119 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001120 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001121 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001122 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001123 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001128 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001129
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001130 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001131
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001132 /**
1133 * Out of paranoia, ensure that everything in the boot class
1134 * path has been dexed.
1135 */
1136 String bootClassPath = System.getProperty("java.boot.class.path");
1137 if (bootClassPath != null) {
1138 String[] paths = splitString(bootClassPath, ':');
1139 for (int i=0; i<paths.length; i++) {
1140 try {
1141 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
1142 libFiles.add(paths[i]);
1143 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
1144 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001146 } catch (FileNotFoundException e) {
1147 Slog.w(TAG, "Boot class path not found: " + paths[i]);
1148 } catch (IOException e) {
Kenny Rootfec5e752011-09-23 10:09:58 -07001149 Slog.w(TAG, "Cannot dexopt " + paths[i] + "; is it an APK or JAR? "
1150 + e.getMessage());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 }
1152 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001153 } else {
1154 Slog.w(TAG, "No BOOTCLASSPATH found!");
1155 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001156
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001157 /**
1158 * Also ensure all external libraries have had dexopt run on them.
1159 */
1160 if (mSharedLibraries.size() > 0) {
Dianne Hackbornc895be72013-03-11 17:48:43 -07001161 Iterator<SharedLibraryEntry> libs = mSharedLibraries.values().iterator();
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001162 while (libs.hasNext()) {
Dianne Hackbornc895be72013-03-11 17:48:43 -07001163 String lib = libs.next().path;
1164 if (lib == null) {
1165 continue;
1166 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001167 try {
1168 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
1169 libFiles.add(lib);
1170 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
1171 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001173 } catch (FileNotFoundException e) {
1174 Slog.w(TAG, "Library not found: " + lib);
1175 } catch (IOException e) {
Kenny Rootfec5e752011-09-23 10:09:58 -07001176 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1177 + e.getMessage());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 }
1179 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001180 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001181
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001182 // Gross hack for now: we know this file doesn't contain any
1183 // code, so don't dexopt it to avoid the resulting log spew.
1184 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
1185
1186 /**
1187 * And there are a number of commands implemented in Java, which
1188 * we currently need to do the dexopt on so that they can be
1189 * run from a non-root shell.
1190 */
1191 String[] frameworkFiles = mFrameworkDir.list();
1192 if (frameworkFiles != null) {
1193 for (int i=0; i<frameworkFiles.length; i++) {
1194 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
1195 String path = libPath.getPath();
1196 // Skip the file if we alrady did it.
1197 if (libFiles.contains(path)) {
1198 continue;
1199 }
1200 // Skip the file if it is not a type we want to dexopt.
1201 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1202 continue;
1203 }
1204 try {
1205 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
1206 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
1207 didDexOpt = true;
1208 }
1209 } catch (FileNotFoundException e) {
1210 Slog.w(TAG, "Jar not found: " + path);
1211 } catch (IOException e) {
1212 Slog.w(TAG, "Exception reading jar: " + path, e);
1213 }
1214 }
1215 }
1216
1217 if (didDexOpt) {
1218 // If we had to do a dexopt of one of the previous
1219 // things, then something on the system has changed.
1220 // Consider this significant, and wipe away all other
1221 // existing dexopt files to ensure we don't leave any
1222 // dangling around.
1223 String[] files = mDalvikCacheDir.list();
1224 if (files != null) {
1225 for (int i=0; i<files.length; i++) {
1226 String fn = files[i];
1227 if (fn.startsWith("data@app@")
1228 || fn.startsWith("data@app-private@")) {
1229 Slog.i(TAG, "Pruning dalvik file: " + fn);
1230 (new File(mDalvikCacheDir, fn)).delete();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001231 }
1232 }
1233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001235
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001236 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 mFrameworkInstallObserver = new AppDirObserver(
1238 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
1239 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -07001240 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
1241 | PackageParser.PARSE_IS_SYSTEM_DIR,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001242 scanMode | SCAN_NO_DEX, 0);
Kenny Root51a573c2012-05-17 13:30:28 -07001243
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001244 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
1246 mSystemInstallObserver = new AppDirObserver(
1247 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
1248 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -07001249 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001250 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Kenny Root208d3412012-05-07 19:42:35 -07001251
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07001252 // Collect all vendor packages.
1253 mVendorAppDir = new File("/vendor/app");
1254 mVendorInstallObserver = new AppDirObserver(
1255 mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
1256 mVendorInstallObserver.startWatching();
1257 scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001258 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07001259
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001260 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1261 mInstaller.moveFiles();
1262
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001263 // Prune any system packages that no longer exist.
Kenny Root87b5d7b2012-05-16 13:36:18 -07001264 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001265 if (!mOnlyCore) {
1266 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1267 while (psit.hasNext()) {
1268 PackageSetting ps = psit.next();
Kenny Root208d3412012-05-07 19:42:35 -07001269
1270 /*
1271 * If this is not a system app, it can't be a
1272 * disable system app.
1273 */
1274 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1275 continue;
1276 }
1277
1278 /*
1279 * If the package is scanned, it's not erased.
1280 */
Kenny Rooteca64b32012-06-25 16:37:32 -07001281 final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1282 if (scannedPkg != null) {
Kenny Root208d3412012-05-07 19:42:35 -07001283 /*
1284 * If the system app is both scanned and in the
1285 * disabled packages list, then it must have been
1286 * added via OTA. Remove it from the currently
1287 * scanned package so the previously user-installed
1288 * application can be scanned.
1289 */
1290 if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
Kenny Rooteca64b32012-06-25 16:37:32 -07001291 Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1292 + "; removing system app");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001293 removePackageLI(ps, true);
Kenny Root208d3412012-05-07 19:42:35 -07001294 }
1295
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001296 continue;
1297 }
1298
1299 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001300 psit.remove();
1301 String msg = "System package " + ps.name
1302 + " no longer exists; wiping its data";
1303 reportSettingsProblem(Log.WARN, msg);
Dianne Hackborn4428e172012-08-24 17:43:05 -07001304 removeDataDirsLI(ps.name);
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001305 } else {
Kenny Root87b5d7b2012-05-16 13:36:18 -07001306 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1307 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1308 possiblyDeletedUpdatedSystemApps.add(ps.name);
1309 }
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001310 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001311 }
1312 }
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 //look for any incomplete package installations
Kenny Root447106f2011-03-23 11:00:15 -07001315 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 //clean up list
1317 for(int i = 0; i < deletePkgsList.size(); i++) {
1318 //clean up here
1319 cleanupInstallFailedPackage(deletePkgsList.get(i));
1320 }
1321 //delete tmp files
1322 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001323
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001324 if (!mOnlyCore) {
1325 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1326 SystemClock.uptimeMillis());
1327 mAppInstallObserver = new AppDirObserver(
1328 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
1329 mAppInstallObserver.startWatching();
1330 scanDirLI(mAppInstallDir, 0, scanMode, 0);
1331
1332 mDrmAppInstallObserver = new AppDirObserver(
1333 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
1334 mDrmAppInstallObserver.startWatching();
1335 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1336 scanMode, 0);
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001337
1338 /**
Kenny Root87b5d7b2012-05-16 13:36:18 -07001339 * Remove disable package settings for any updated system
1340 * apps that were removed via an OTA. If they're not a
1341 * previously-updated app, remove them completely.
1342 * Otherwise, just revoke their system-level permissions.
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001343 */
Kenny Root87b5d7b2012-05-16 13:36:18 -07001344 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001345 PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
Kenny Root87b5d7b2012-05-16 13:36:18 -07001346 mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1347
1348 String msg;
1349 if (deletedPkg == null) {
1350 msg = "Updated system package " + deletedAppName
1351 + " no longer exists; wiping its data";
Dianne Hackborn4428e172012-08-24 17:43:05 -07001352 removeDataDirsLI(deletedAppName);
Kenny Root87b5d7b2012-05-16 13:36:18 -07001353 } else {
1354 msg = "Updated system app + " + deletedAppName
1355 + " no longer present; removing system privileges for "
1356 + deletedAppName;
1357
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001358 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1359
1360 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1361 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1362 }
Kenny Root87b5d7b2012-05-16 13:36:18 -07001363 reportSettingsProblem(Log.WARN, msg);
Kenny Rootc52d6fd2012-05-07 23:04:52 -07001364 }
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001365 } else {
1366 mAppInstallObserver = null;
1367 mDrmAppInstallObserver = null;
1368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369
Dianne Hackbornc895be72013-03-11 17:48:43 -07001370 // Now that we know all of the shared libraries, update all clients to have
1371 // the correct library paths.
1372 updateAllSharedLibrariesLPw();
1373
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001374 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001376 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 + ((SystemClock.uptimeMillis()-startTime)/1000f)
1378 + " seconds");
1379
Dianne Hackbornf22221f2010-04-05 18:35:42 -07001380 // If the platform SDK has changed since the last time we booted,
1381 // we need to re-grant app permission to catch any new ones that
1382 // appear. This is really a hack, and means that apps can in some
1383 // cases get permissions that the user didn't initially explicitly
1384 // allow... it would be nice to have some better way to handle
1385 // this situation.
1386 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1387 != mSdkVersion;
1388 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1389 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1390 + "; regranting permissions for internal storage");
1391 mSettings.mInternalSdkPlatform = mSdkVersion;
1392
Dianne Hackborne639da72012-02-21 15:11:13 -08001393 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1394 | (regrantPermissions
1395 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1396 : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397
Dianne Hackborn4d491a62013-04-01 18:10:51 -07001398 // If this is the first boot, and it is a normal boot, then
1399 // we need to initialize the default preferred apps.
1400 if (!mRestoredSettings && !onlyCore) {
1401 mSettings.readDefaultPreferredAppsLPw(this, 0);
1402 }
1403
Kenny Root447106f2011-03-23 11:00:15 -07001404 // can downgrade to reader
1405 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001407 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 // Now after opening every single application zip, make sure they
1411 // are all flushed. Not really needed, but keeps things nice and
1412 // tidy.
1413 Runtime.getRuntime().gc();
Kenny Root05ca4c92011-09-15 10:36:25 -07001414
1415 mRequiredVerifierPackage = getRequiredVerifierLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 } // synchronized (mPackages)
1417 } // synchronized (mInstallLock)
1418 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001419
Dianne Hackborn58f42a52011-10-10 13:46:34 -07001420 public boolean isFirstBoot() {
1421 return !mRestoredSettings;
1422 }
1423
Dianne Hackborn13579ed2012-11-28 18:05:36 -08001424 public boolean isOnlyCoreApps() {
1425 return mOnlyCore;
1426 }
1427
Kenny Root05ca4c92011-09-15 10:36:25 -07001428 private String getRequiredVerifierLPr() {
1429 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1430 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
Amith Yamasani483f3b02012-03-13 16:08:00 -07001431 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
Kenny Root05ca4c92011-09-15 10:36:25 -07001432
1433 String requiredVerifier = null;
1434
1435 final int N = receivers.size();
1436 for (int i = 0; i < N; i++) {
1437 final ResolveInfo info = receivers.get(i);
1438
1439 if (info.activityInfo == null) {
1440 continue;
1441 }
1442
1443 final String packageName = info.activityInfo.packageName;
1444
1445 final PackageSetting ps = mSettings.mPackages.get(packageName);
1446 if (ps == null) {
1447 continue;
1448 }
1449
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001450 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1451 if (!gp.grantedPermissions
Kenny Root05ca4c92011-09-15 10:36:25 -07001452 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1453 continue;
1454 }
1455
1456 if (requiredVerifier != null) {
1457 throw new RuntimeException("There can be only one required verifier");
1458 }
1459
1460 requiredVerifier = packageName;
1461 }
1462
1463 return requiredVerifier;
1464 }
1465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 @Override
1467 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1468 throws RemoteException {
1469 try {
1470 return super.onTransact(code, data, reply, flags);
1471 } catch (RuntimeException e) {
1472 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001473 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 }
1475 throw e;
1476 }
1477 }
1478
Dianne Hackborne6620b22010-01-22 14:46:21 -08001479 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001480 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
Dianne Hackborn4428e172012-08-24 17:43:05 -07001481 removeDataDirsLI(ps.name);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001482 if (ps.codePath != null) {
1483 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001484 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001485 }
1486 }
1487 if (ps.resourcePath != null) {
1488 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001489 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001490 }
1491 }
Kenny Root447106f2011-03-23 11:00:15 -07001492 mSettings.removePackageLPw(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 }
1494
1495 void readPermissions() {
1496 // Read permissions from .../etc/permission directory.
1497 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1498 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001499 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 return;
1501 }
1502 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001503 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 return;
1505 }
1506
1507 // Iterate over the files in the directory and scan .xml files
1508 for (File f : libraryDir.listFiles()) {
1509 // We'll read platform.xml last
1510 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1511 continue;
1512 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001515 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 continue;
1517 }
1518 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001519 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 continue;
1521 }
1522
1523 readPermissionsFromXml(f);
1524 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1527 final File permFile = new File(Environment.getRootDirectory(),
1528 "etc/permissions/platform.xml");
1529 readPermissionsFromXml(permFile);
1530 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001531
1532 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 FileReader permReader = null;
1534 try {
1535 permReader = new FileReader(permFile);
1536 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001537 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 return;
1539 }
1540
1541 try {
1542 XmlPullParser parser = Xml.newPullParser();
1543 parser.setInput(permReader);
1544
1545 XmlUtils.beginDocument(parser, "permissions");
1546
1547 while (true) {
1548 XmlUtils.nextElement(parser);
1549 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1550 break;
1551 }
1552
1553 String name = parser.getName();
1554 if ("group".equals(name)) {
1555 String gidStr = parser.getAttributeValue(null, "gid");
1556 if (gidStr != null) {
Romain Guy01d159d2013-02-25 13:22:42 -08001557 int gid = Process.getGidForName(gidStr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 mGlobalGids = appendInt(mGlobalGids, gid);
1559 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001560 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 + parser.getPositionDescription());
1562 }
1563
1564 XmlUtils.skipCurrentTag(parser);
1565 continue;
1566 } else if ("permission".equals(name)) {
1567 String perm = parser.getAttributeValue(null, "name");
1568 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001569 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 + parser.getPositionDescription());
1571 XmlUtils.skipCurrentTag(parser);
1572 continue;
1573 }
1574 perm = perm.intern();
1575 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 } else if ("assign-permission".equals(name)) {
1578 String perm = parser.getAttributeValue(null, "name");
1579 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001580 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 + parser.getPositionDescription());
1582 XmlUtils.skipCurrentTag(parser);
1583 continue;
1584 }
1585 String uidStr = parser.getAttributeValue(null, "uid");
1586 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001587 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 + parser.getPositionDescription());
1589 XmlUtils.skipCurrentTag(parser);
1590 continue;
1591 }
1592 int uid = Process.getUidForName(uidStr);
1593 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001594 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 + uidStr + "\" at "
1596 + parser.getPositionDescription());
1597 XmlUtils.skipCurrentTag(parser);
1598 continue;
1599 }
1600 perm = perm.intern();
1601 HashSet<String> perms = mSystemPermissions.get(uid);
1602 if (perms == null) {
1603 perms = new HashSet<String>();
1604 mSystemPermissions.put(uid, perms);
1605 }
1606 perms.add(perm);
1607 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 } else if ("library".equals(name)) {
1610 String lname = parser.getAttributeValue(null, "name");
1611 String lfile = parser.getAttributeValue(null, "file");
1612 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001613 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 + parser.getPositionDescription());
1615 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001616 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 + parser.getPositionDescription());
1618 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001619 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackbornc895be72013-03-11 17:48:43 -07001620 mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null));
Dianne Hackborn49237342009-08-27 20:08:01 -07001621 }
1622 XmlUtils.skipCurrentTag(parser);
1623 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001624
Dianne Hackborn49237342009-08-27 20:08:01 -07001625 } else if ("feature".equals(name)) {
1626 String fname = parser.getAttributeValue(null, "name");
1627 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001628 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001629 + parser.getPositionDescription());
1630 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001631 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001632 FeatureInfo fi = new FeatureInfo();
1633 fi.name = fname;
1634 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 }
1636 XmlUtils.skipCurrentTag(parser);
1637 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 } else {
1640 XmlUtils.skipCurrentTag(parser);
1641 continue;
1642 }
1643
1644 }
Brian Carlstromfd9ddd12010-11-04 11:24:58 -07001645 permReader.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001647 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001649 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 }
1651 }
1652
1653 void readPermission(XmlPullParser parser, String name)
1654 throws IOException, XmlPullParserException {
1655
1656 name = name.intern();
1657
1658 BasePermission bp = mSettings.mPermissions.get(name);
1659 if (bp == null) {
1660 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1661 mSettings.mPermissions.put(name, bp);
1662 }
1663 int outerDepth = parser.getDepth();
1664 int type;
1665 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1666 && (type != XmlPullParser.END_TAG
1667 || parser.getDepth() > outerDepth)) {
1668 if (type == XmlPullParser.END_TAG
1669 || type == XmlPullParser.TEXT) {
1670 continue;
1671 }
1672
1673 String tagName = parser.getName();
1674 if ("group".equals(tagName)) {
1675 String gidStr = parser.getAttributeValue(null, "gid");
1676 if (gidStr != null) {
1677 int gid = Process.getGidForName(gidStr);
1678 bp.gids = appendInt(bp.gids, gid);
1679 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001680 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 + parser.getPositionDescription());
1682 }
1683 }
1684 XmlUtils.skipCurrentTag(parser);
1685 }
1686 }
1687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 static int[] appendInts(int[] cur, int[] add) {
1689 if (add == null) return cur;
1690 if (cur == null) return add;
1691 final int N = add.length;
1692 for (int i=0; i<N; i++) {
1693 cur = appendInt(cur, add[i]);
1694 }
1695 return cur;
1696 }
1697
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001698 static int[] removeInts(int[] cur, int[] rem) {
1699 if (rem == null) return cur;
1700 if (cur == null) return cur;
1701 final int N = rem.length;
1702 for (int i=0; i<N; i++) {
1703 cur = removeInt(cur, rem[i]);
1704 }
1705 return cur;
1706 }
1707
Amith Yamasani13593602012-03-22 16:16:17 -07001708 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1709 if (!sUserManager.exists(userId)) return null;
1710 PackageInfo pi;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001711 final PackageSetting ps = (PackageSetting) p.mExtras;
1712 if (ps == null) {
1713 return null;
1714 }
1715 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1716 final PackageUserState state = ps.readUserState(userId);
Jeff Sharkey94d7ddb2013-03-06 15:02:12 -08001717 return PackageParser.generatePackageInfo(p, gp.gids, flags,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001718 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1719 state, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 }
1721
Amith Yamasani483f3b02012-03-13 16:08:00 -07001722 @Override
1723 public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001724 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07001725 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
Kenny Root447106f2011-03-23 11:00:15 -07001726 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 synchronized (mPackages) {
1728 PackageParser.Package p = mPackages.get(packageName);
Kenny Root9718cf52011-02-23 16:45:26 -08001729 if (DEBUG_PACKAGE_INFO)
1730 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 if (p != null) {
Amith Yamasani13593602012-03-22 16:16:17 -07001732 return generatePackageInfo(p, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 }
1734 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001735 return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 }
1737 }
1738 return null;
1739 }
1740
Dianne Hackborn47096932010-02-11 15:57:09 -08001741 public String[] currentToCanonicalPackageNames(String[] names) {
1742 String[] out = new String[names.length];
Kenny Root447106f2011-03-23 11:00:15 -07001743 // reader
Dianne Hackborn47096932010-02-11 15:57:09 -08001744 synchronized (mPackages) {
1745 for (int i=names.length-1; i>=0; i--) {
1746 PackageSetting ps = mSettings.mPackages.get(names[i]);
1747 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1748 }
1749 }
1750 return out;
1751 }
1752
1753 public String[] canonicalToCurrentPackageNames(String[] names) {
1754 String[] out = new String[names.length];
Kenny Root447106f2011-03-23 11:00:15 -07001755 // reader
Dianne Hackborn47096932010-02-11 15:57:09 -08001756 synchronized (mPackages) {
1757 for (int i=names.length-1; i>=0; i--) {
1758 String cur = mSettings.mRenamedPackages.get(names[i]);
1759 out[i] = cur != null ? cur : names[i];
1760 }
1761 }
1762 return out;
1763 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07001764
1765 @Override
1766 public int getPackageUid(String packageName, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001767 if (!sUserManager.exists(userId)) return -1;
Amith Yamasanif203aee2012-08-29 18:41:53 -07001768 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
Kenny Root447106f2011-03-23 11:00:15 -07001769 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 synchronized (mPackages) {
1771 PackageParser.Package p = mPackages.get(packageName);
1772 if(p != null) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001773 return UserHandle.getUid(userId, p.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 }
1775 PackageSetting ps = mSettings.mPackages.get(packageName);
1776 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1777 return -1;
1778 }
1779 p = ps.pkg;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001780 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 }
1782 }
1783
1784 public int[] getPackageGids(String packageName) {
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -07001785 final boolean enforcedDefault = isPermissionEnforcedDefault(READ_EXTERNAL_STORAGE);
Kenny Root447106f2011-03-23 11:00:15 -07001786 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 synchronized (mPackages) {
1788 PackageParser.Package p = mPackages.get(packageName);
Kenny Root9718cf52011-02-23 16:45:26 -08001789 if (DEBUG_PACKAGE_INFO)
1790 Log.v(TAG, "getPackageGids" + packageName + ": " + p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 if (p != null) {
1792 final PackageSetting ps = (PackageSetting)p.mExtras;
1793 final SharedUserSetting suid = ps.sharedUser;
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07001794 int[] gids = suid != null ? suid.gids : ps.gids;
1795
1796 // include GIDs for any unenforced permissions
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -07001797 if (!isPermissionEnforcedLocked(READ_EXTERNAL_STORAGE, enforcedDefault)) {
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07001798 final BasePermission basePerm = mSettings.mPermissions.get(
1799 READ_EXTERNAL_STORAGE);
1800 gids = appendInts(gids, basePerm.gids);
1801 }
1802
1803 return gids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 }
1805 }
1806 // stupid thing to indicate an error.
1807 return new int[0];
1808 }
1809
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001810 static final PermissionInfo generatePermissionInfo(
1811 BasePermission bp, int flags) {
1812 if (bp.perm != null) {
1813 return PackageParser.generatePermissionInfo(bp.perm, flags);
1814 }
1815 PermissionInfo pi = new PermissionInfo();
1816 pi.name = bp.name;
1817 pi.packageName = bp.sourcePackage;
1818 pi.nonLocalizedLabel = bp.name;
1819 pi.protectionLevel = bp.protectionLevel;
1820 return pi;
1821 }
1822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 public PermissionInfo getPermissionInfo(String name, int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001824 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 synchronized (mPackages) {
1826 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001827 if (p != null) {
1828 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 }
1830 return null;
1831 }
1832 }
1833
1834 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001835 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 synchronized (mPackages) {
1837 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1838 for (BasePermission p : mSettings.mPermissions.values()) {
1839 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001840 if (p.perm == null || p.perm.info.group == null) {
1841 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 }
1843 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001844 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1846 }
1847 }
1848 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 if (out.size() > 0) {
1851 return out;
1852 }
1853 return mPermissionGroups.containsKey(group) ? out : null;
1854 }
1855 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001858 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 synchronized (mPackages) {
1860 return PackageParser.generatePermissionGroupInfo(
1861 mPermissionGroups.get(name), flags);
1862 }
1863 }
1864
1865 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001866 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 synchronized (mPackages) {
1868 final int N = mPermissionGroups.size();
1869 ArrayList<PermissionGroupInfo> out
1870 = new ArrayList<PermissionGroupInfo>(N);
1871 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1872 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1873 }
1874 return out;
1875 }
1876 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001877
Amith Yamasani483f3b02012-03-13 16:08:00 -07001878 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
1879 int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001880 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 PackageSetting ps = mSettings.mPackages.get(packageName);
Kenny Root447106f2011-03-23 11:00:15 -07001882 if (ps != null) {
1883 if (ps.pkg == null) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001884 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
1885 flags, userId);
Kenny Root447106f2011-03-23 11:00:15 -07001886 if (pInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 return pInfo.applicationInfo;
1888 }
1889 return null;
1890 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001891 return PackageParser.generateApplicationInfo(ps.pkg, flags,
1892 ps.readUserState(userId), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 }
1894 return null;
1895 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001896
Amith Yamasani483f3b02012-03-13 16:08:00 -07001897 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
1898 int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001899 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 PackageSetting ps = mSettings.mPackages.get(packageName);
Kenny Root447106f2011-03-23 11:00:15 -07001901 if (ps != null) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001902 PackageParser.Package pkg = ps.pkg;
1903 if (pkg == null) {
1904 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
1905 return null;
1906 }
1907 pkg = new PackageParser.Package(packageName);
1908 pkg.applicationInfo.packageName = packageName;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001909 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001910 pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1911 pkg.applicationInfo.sourceDir = ps.codePathString;
1912 pkg.applicationInfo.dataDir =
Amith Yamasani317046a2012-08-29 18:48:08 -07001913 getDataPathForPackage(packageName, 0).getPath();
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001914 pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001916 // pkg.mSetEnabled = ps.getEnabled(userId);
1917 // pkg.mSetStopped = ps.getStopped(userId);
1918 return generatePackageInfo(pkg, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 }
1920 return null;
1921 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001922
Amith Yamasani483f3b02012-03-13 16:08:00 -07001923 @Override
1924 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001925 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07001926 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
Kenny Root447106f2011-03-23 11:00:15 -07001927 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 synchronized (mPackages) {
1929 PackageParser.Package p = mPackages.get(packageName);
Kenny Root9718cf52011-02-23 16:45:26 -08001930 if (DEBUG_PACKAGE_INFO) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 TAG, "getApplicationInfo " + packageName
1932 + ": " + p);
1933 if (p != null) {
Amith Yamasani13593602012-03-22 16:16:17 -07001934 PackageSetting ps = mSettings.mPackages.get(packageName);
1935 if (ps == null) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 // Note: isEnabledLP() does not apply here - always return info
Jeff Sharkey38f86882012-10-11 16:10:23 -07001937 return PackageParser.generateApplicationInfo(
1938 p, flags, ps.readUserState(userId), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 }
1940 if ("android".equals(packageName)||"system".equals(packageName)) {
1941 return mAndroidApplication;
1942 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001943 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07001944 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 }
1946 }
1947 return null;
1948 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001949
1950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1952 mContext.enforceCallingOrSelfPermission(
1953 android.Manifest.permission.CLEAR_APP_CACHE, null);
1954 // Queue up an async operation since clearing cache may take a little while.
1955 mHandler.post(new Runnable() {
1956 public void run() {
1957 mHandler.removeCallbacks(this);
1958 int retCode = -1;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001959 synchronized (mInstallLock) {
1960 retCode = mInstaller.freeCache(freeStorageSize);
1961 if (retCode < 0) {
1962 Slog.w(TAG, "Couldn't clear application caches");
1963 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 if (observer != null) {
1966 try {
1967 observer.onRemoveCompleted(null, (retCode >= 0));
1968 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001969 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 }
1971 }
1972 }
1973 });
1974 }
1975
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001976 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001977 mContext.enforceCallingOrSelfPermission(
1978 android.Manifest.permission.CLEAR_APP_CACHE, null);
1979 // Queue up an async operation since clearing cache may take a little while.
1980 mHandler.post(new Runnable() {
1981 public void run() {
1982 mHandler.removeCallbacks(this);
1983 int retCode = -1;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001984 synchronized (mInstallLock) {
1985 retCode = mInstaller.freeCache(freeStorageSize);
1986 if (retCode < 0) {
1987 Slog.w(TAG, "Couldn't clear application caches");
1988 }
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001989 }
1990 if(pi != null) {
1991 try {
1992 // Callback via pending intent
1993 int code = (retCode >= 0) ? 1 : 0;
1994 pi.sendIntent(null, code, null,
1995 null, null);
1996 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001997 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001998 }
1999 }
2000 }
2001 });
2002 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002003
Amith Yamasani483f3b02012-03-13 16:08:00 -07002004 @Override
2005 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002006 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07002007 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 synchronized (mPackages) {
2009 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002010
Kenny Root9718cf52011-02-23 16:45:26 -08002011 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
Amith Yamasani483f3b02012-03-13 16:08:00 -07002012 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
Amith Yamasani13593602012-03-22 16:16:17 -07002013 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2014 if (ps == null) return null;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002015 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2016 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 }
2018 if (mResolveComponentName.equals(component)) {
2019 return mResolveActivity;
2020 }
2021 }
2022 return null;
2023 }
2024
Amith Yamasani483f3b02012-03-13 16:08:00 -07002025 @Override
2026 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002027 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07002028 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 synchronized (mPackages) {
2030 PackageParser.Activity a = mReceivers.mActivities.get(component);
Kenny Root9718cf52011-02-23 16:45:26 -08002031 if (DEBUG_PACKAGE_INFO) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 TAG, "getReceiverInfo " + component + ": " + a);
Amith Yamasani483f3b02012-03-13 16:08:00 -07002033 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
Amith Yamasani13593602012-03-22 16:16:17 -07002034 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2035 if (ps == null) return null;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002036 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2037 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002038 }
2039 }
2040 return null;
2041 }
2042
Amith Yamasani483f3b02012-03-13 16:08:00 -07002043 @Override
2044 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002045 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07002046 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 synchronized (mPackages) {
2048 PackageParser.Service s = mServices.mServices.get(component);
Kenny Root9718cf52011-02-23 16:45:26 -08002049 if (DEBUG_PACKAGE_INFO) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 TAG, "getServiceInfo " + component + ": " + s);
Amith Yamasani483f3b02012-03-13 16:08:00 -07002051 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
Amith Yamasani13593602012-03-22 16:16:17 -07002052 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2053 if (ps == null) return null;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002054 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2055 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 }
2057 }
2058 return null;
2059 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002060
Amith Yamasani483f3b02012-03-13 16:08:00 -07002061 @Override
2062 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002063 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07002064 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
Dianne Hackborn361199b2010-08-30 17:42:07 -07002065 synchronized (mPackages) {
2066 PackageParser.Provider p = mProvidersByComponent.get(component);
Kenny Root9718cf52011-02-23 16:45:26 -08002067 if (DEBUG_PACKAGE_INFO) Log.v(
Dianne Hackborn361199b2010-08-30 17:42:07 -07002068 TAG, "getProviderInfo " + component + ": " + p);
Amith Yamasani483f3b02012-03-13 16:08:00 -07002069 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
Amith Yamasani13593602012-03-22 16:16:17 -07002070 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2071 if (ps == null) return null;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002072 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2073 userId);
Dianne Hackborn361199b2010-08-30 17:42:07 -07002074 }
2075 }
2076 return null;
2077 }
2078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 public String[] getSystemSharedLibraryNames() {
2080 Set<String> libSet;
2081 synchronized (mPackages) {
2082 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07002083 int size = libSet.size();
2084 if (size > 0) {
2085 String[] libs = new String[size];
2086 libSet.toArray(libs);
2087 return libs;
2088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002090 return null;
2091 }
2092
2093 public FeatureInfo[] getSystemAvailableFeatures() {
2094 Collection<FeatureInfo> featSet;
2095 synchronized (mPackages) {
2096 featSet = mAvailableFeatures.values();
2097 int size = featSet.size();
2098 if (size > 0) {
2099 FeatureInfo[] features = new FeatureInfo[size+1];
2100 featSet.toArray(features);
2101 FeatureInfo fi = new FeatureInfo();
2102 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2103 FeatureInfo.GL_ES_VERSION_UNDEFINED);
2104 features[size] = fi;
2105 return features;
2106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 }
2108 return null;
2109 }
2110
Dianne Hackborn039c68e2009-09-26 16:39:23 -07002111 public boolean hasSystemFeature(String name) {
2112 synchronized (mPackages) {
2113 return mAvailableFeatures.containsKey(name);
2114 }
2115 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002116
Amith Yamasani483f3b02012-03-13 16:08:00 -07002117 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002118 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
Amith Yamasani483f3b02012-03-13 16:08:00 -07002119 return;
2120
2121 throw new SecurityException("Caller uid=" + uid
2122 + " is not privileged to communicate with user=" + userId);
2123 }
2124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 public int checkPermission(String permName, String pkgName) {
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -07002126 final boolean enforcedDefault = isPermissionEnforcedDefault(permName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 synchronized (mPackages) {
2128 PackageParser.Package p = mPackages.get(pkgName);
2129 if (p != null && p.mExtras != null) {
2130 PackageSetting ps = (PackageSetting)p.mExtras;
2131 if (ps.sharedUser != null) {
2132 if (ps.sharedUser.grantedPermissions.contains(permName)) {
2133 return PackageManager.PERMISSION_GRANTED;
2134 }
2135 } else if (ps.grantedPermissions.contains(permName)) {
2136 return PackageManager.PERMISSION_GRANTED;
2137 }
2138 }
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -07002139 if (!isPermissionEnforcedLocked(permName, enforcedDefault)) {
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07002140 return PackageManager.PERMISSION_GRANTED;
2141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 }
2143 return PackageManager.PERMISSION_DENIED;
2144 }
2145
2146 public int checkUidPermission(String permName, int uid) {
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -07002147 final boolean enforcedDefault = isPermissionEnforcedDefault(permName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002148 synchronized (mPackages) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002149 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002151 GrantedPermissions gp = (GrantedPermissions)obj;
2152 if (gp.grantedPermissions.contains(permName)) {
2153 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 }
2155 } else {
2156 HashSet<String> perms = mSystemPermissions.get(uid);
2157 if (perms != null && perms.contains(permName)) {
2158 return PackageManager.PERMISSION_GRANTED;
2159 }
2160 }
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -07002161 if (!isPermissionEnforcedLocked(permName, enforcedDefault)) {
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -07002162 return PackageManager.PERMISSION_GRANTED;
2163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 }
2165 return PackageManager.PERMISSION_DENIED;
2166 }
2167
Amith Yamasanif203aee2012-08-29 18:41:53 -07002168 /**
2169 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2170 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2171 * @param message the message to log on security exception
2172 * @return
2173 */
2174 private void enforceCrossUserPermission(int callingUid, int userId,
2175 boolean requireFullPermission, String message) {
2176 if (userId < 0) {
2177 throw new IllegalArgumentException("Invalid userId " + userId);
2178 }
2179 if (userId == UserHandle.getUserId(callingUid)) return;
2180 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2181 if (requireFullPermission) {
2182 mContext.enforceCallingOrSelfPermission(
2183 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2184 } else {
2185 try {
2186 mContext.enforceCallingOrSelfPermission(
2187 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2188 } catch (SecurityException se) {
2189 mContext.enforceCallingOrSelfPermission(
2190 android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2191 }
2192 }
2193 }
2194 }
2195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 private BasePermission findPermissionTreeLP(String permName) {
2197 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2198 if (permName.startsWith(bp.name) &&
2199 permName.length() > bp.name.length() &&
2200 permName.charAt(bp.name.length()) == '.') {
2201 return bp;
2202 }
2203 }
2204 return null;
2205 }
2206
2207 private BasePermission checkPermissionTreeLP(String permName) {
2208 if (permName != null) {
2209 BasePermission bp = findPermissionTreeLP(permName);
2210 if (bp != null) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002211 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 return bp;
2213 }
2214 throw new SecurityException("Calling uid "
2215 + Binder.getCallingUid()
2216 + " is not allowed to add to permission tree "
2217 + bp.name + " owned by uid " + bp.uid);
2218 }
2219 }
2220 throw new SecurityException("No permission tree found for " + permName);
2221 }
2222
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002223 static boolean compareStrings(CharSequence s1, CharSequence s2) {
2224 if (s1 == null) {
2225 return s2 == null;
2226 }
2227 if (s2 == null) {
2228 return false;
2229 }
2230 if (s1.getClass() != s2.getClass()) {
2231 return false;
2232 }
2233 return s1.equals(s2);
2234 }
2235
2236 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2237 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07002238 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002239 if (pi1.protectionLevel != pi2.protectionLevel) return false;
2240 if (!compareStrings(pi1.name, pi2.name)) return false;
2241 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2242 // We'll take care of setting this one.
2243 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2244 // These are not currently stored in settings.
2245 //if (!compareStrings(pi1.group, pi2.group)) return false;
2246 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2247 //if (pi1.labelRes != pi2.labelRes) return false;
2248 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2249 return true;
2250 }
2251
2252 boolean addPermissionLocked(PermissionInfo info, boolean async) {
2253 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2254 throw new SecurityException("Label must be specified in permission");
2255 }
2256 BasePermission tree = checkPermissionTreeLP(info.name);
2257 BasePermission bp = mSettings.mPermissions.get(info.name);
2258 boolean added = bp == null;
2259 boolean changed = true;
Dianne Hackborne639da72012-02-21 15:11:13 -08002260 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002261 if (added) {
2262 bp = new BasePermission(info.name, tree.sourcePackage,
2263 BasePermission.TYPE_DYNAMIC);
2264 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2265 throw new SecurityException(
2266 "Not allowed to modify non-dynamic permission "
2267 + info.name);
2268 } else {
Dianne Hackborne639da72012-02-21 15:11:13 -08002269 if (bp.protectionLevel == fixedLevel
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002270 && bp.perm.owner.equals(tree.perm.owner)
2271 && bp.uid == tree.uid
2272 && comparePermissionInfos(bp.perm.info, info)) {
2273 changed = false;
2274 }
2275 }
Dianne Hackborne639da72012-02-21 15:11:13 -08002276 bp.protectionLevel = fixedLevel;
2277 info = new PermissionInfo(info);
2278 info.protectionLevel = fixedLevel;
2279 bp.perm = new PackageParser.Permission(tree.perm.owner, info);
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002280 bp.perm.info.packageName = tree.perm.info.packageName;
2281 bp.uid = tree.uid;
2282 if (added) {
2283 mSettings.mPermissions.put(info.name, bp);
2284 }
2285 if (changed) {
2286 if (!async) {
Kenny Root447106f2011-03-23 11:00:15 -07002287 mSettings.writeLPr();
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002288 } else {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002289 scheduleWriteSettingsLocked();
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002290 }
2291 }
2292 return added;
2293 }
2294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002295 public boolean addPermission(PermissionInfo info) {
2296 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07002297 return addPermissionLocked(info, false);
2298 }
2299 }
2300
2301 public boolean addPermissionAsync(PermissionInfo info) {
2302 synchronized (mPackages) {
2303 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002304 }
2305 }
2306
2307 public void removePermission(String name) {
2308 synchronized (mPackages) {
2309 checkPermissionTreeLP(name);
2310 BasePermission bp = mSettings.mPermissions.get(name);
2311 if (bp != null) {
2312 if (bp.type != BasePermission.TYPE_DYNAMIC) {
2313 throw new SecurityException(
2314 "Not allowed to modify non-dynamic permission "
2315 + name);
2316 }
2317 mSettings.mPermissions.remove(name);
Kenny Root447106f2011-03-23 11:00:15 -07002318 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319 }
2320 }
2321 }
2322
Nick Kralevichc4986142013-03-24 14:27:17 -07002323 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2324 int index = pkg.requestedPermissions.indexOf(bp.name);
2325 if (index == -1) {
2326 throw new SecurityException("Package " + pkg.packageName
2327 + " has not requested permission " + bp.name);
2328 }
2329 boolean isNormal =
2330 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2331 == PermissionInfo.PROTECTION_NORMAL);
2332 boolean isDangerous =
2333 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2334 == PermissionInfo.PROTECTION_DANGEROUS);
2335 boolean isDevelopment =
2336 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2337
2338 if (!isNormal && !isDangerous && !isDevelopment) {
2339 throw new SecurityException("Permission " + bp.name
2340 + " is not a changeable permission type");
2341 }
2342
2343 if (isNormal || isDangerous) {
2344 if (pkg.requestedPermissionsRequired.get(index)) {
2345 throw new SecurityException("Can't change " + bp.name
2346 + ". It is required by the application");
2347 }
2348 }
2349 }
2350
Dianne Hackborne639da72012-02-21 15:11:13 -08002351 public void grantPermission(String packageName, String permissionName) {
2352 mContext.enforceCallingOrSelfPermission(
2353 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2354 synchronized (mPackages) {
2355 final PackageParser.Package pkg = mPackages.get(packageName);
2356 if (pkg == null) {
2357 throw new IllegalArgumentException("Unknown package: " + packageName);
2358 }
2359 final BasePermission bp = mSettings.mPermissions.get(permissionName);
2360 if (bp == null) {
Nick Kralevichc4986142013-03-24 14:27:17 -07002361 throw new IllegalArgumentException("Unknown permission: " + permissionName);
Dianne Hackborne639da72012-02-21 15:11:13 -08002362 }
Nick Kralevichc4986142013-03-24 14:27:17 -07002363
2364 checkGrantRevokePermissions(pkg, bp);
2365
Dianne Hackborne639da72012-02-21 15:11:13 -08002366 final PackageSetting ps = (PackageSetting) pkg.mExtras;
2367 if (ps == null) {
2368 return;
2369 }
Nick Kralevichc4986142013-03-24 14:27:17 -07002370 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
Dianne Hackborne639da72012-02-21 15:11:13 -08002371 if (gp.grantedPermissions.add(permissionName)) {
2372 if (ps.haveGids) {
2373 gp.gids = appendInts(gp.gids, bp.gids);
2374 }
2375 mSettings.writeLPr();
2376 }
2377 }
2378 }
2379
2380 public void revokePermission(String packageName, String permissionName) {
Dianne Hackbornf1b78242013-04-08 22:28:59 -07002381 int changedAppId = -1;
2382
Dianne Hackborne639da72012-02-21 15:11:13 -08002383 synchronized (mPackages) {
2384 final PackageParser.Package pkg = mPackages.get(packageName);
2385 if (pkg == null) {
2386 throw new IllegalArgumentException("Unknown package: " + packageName);
2387 }
2388 if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2389 mContext.enforceCallingOrSelfPermission(
2390 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2391 }
2392 final BasePermission bp = mSettings.mPermissions.get(permissionName);
2393 if (bp == null) {
Nick Kralevichc4986142013-03-24 14:27:17 -07002394 throw new IllegalArgumentException("Unknown permission: " + permissionName);
Dianne Hackborne639da72012-02-21 15:11:13 -08002395 }
Nick Kralevichc4986142013-03-24 14:27:17 -07002396
2397 checkGrantRevokePermissions(pkg, bp);
2398
Dianne Hackborne639da72012-02-21 15:11:13 -08002399 final PackageSetting ps = (PackageSetting) pkg.mExtras;
2400 if (ps == null) {
2401 return;
2402 }
Nick Kralevichc4986142013-03-24 14:27:17 -07002403 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
Dianne Hackborne639da72012-02-21 15:11:13 -08002404 if (gp.grantedPermissions.remove(permissionName)) {
2405 gp.grantedPermissions.remove(permissionName);
2406 if (ps.haveGids) {
2407 gp.gids = removeInts(gp.gids, bp.gids);
2408 }
2409 mSettings.writeLPr();
Dianne Hackbornf1b78242013-04-08 22:28:59 -07002410 changedAppId = ps.appId;
2411 }
2412 }
2413
2414 if (changedAppId >= 0) {
2415 // We changed the perm on someone, kill its processes.
2416 IActivityManager am = ActivityManagerNative.getDefault();
2417 if (am != null) {
2418 final int callingUserId = UserHandle.getCallingUserId();
2419 final long ident = Binder.clearCallingIdentity();
2420 try {
2421 //XXX we should only revoke for the calling user's app permissions,
2422 // but for now we impact all users.
2423 //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2424 // "revoke " + permissionName);
2425 int[] users = sUserManager.getUserIds();
2426 for (int user : users) {
2427 am.killUid(UserHandle.getUid(user, changedAppId),
2428 "revoke " + permissionName);
2429 }
2430 } catch (RemoteException e) {
2431 } finally {
2432 Binder.restoreCallingIdentity(ident);
2433 }
Dianne Hackborne639da72012-02-21 15:11:13 -08002434 }
2435 }
2436 }
2437
Dianne Hackborn854060af2009-07-09 18:14:31 -07002438 public boolean isProtectedBroadcast(String actionName) {
2439 synchronized (mPackages) {
2440 return mProtectedBroadcasts.contains(actionName);
2441 }
2442 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 public int checkSignatures(String pkg1, String pkg2) {
2445 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002446 final PackageParser.Package p1 = mPackages.get(pkg1);
2447 final PackageParser.Package p2 = mPackages.get(pkg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002448 if (p1 == null || p1.mExtras == null
2449 || p2 == null || p2.mExtras == null) {
2450 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2451 }
Kenny Root447106f2011-03-23 11:00:15 -07002452 return compareSignatures(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002453 }
2454 }
2455
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002456 public int checkUidSignatures(int uid1, int uid2) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002457 // Map to base uids.
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002458 uid1 = UserHandle.getAppId(uid1);
2459 uid2 = UserHandle.getAppId(uid2);
Kenny Root447106f2011-03-23 11:00:15 -07002460 // reader
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002461 synchronized (mPackages) {
2462 Signature[] s1;
2463 Signature[] s2;
Kenny Root447106f2011-03-23 11:00:15 -07002464 Object obj = mSettings.getUserIdLPr(uid1);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002465 if (obj != null) {
2466 if (obj instanceof SharedUserSetting) {
2467 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2468 } else if (obj instanceof PackageSetting) {
2469 s1 = ((PackageSetting)obj).signatures.mSignatures;
2470 } else {
2471 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2472 }
2473 } else {
2474 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2475 }
Kenny Root447106f2011-03-23 11:00:15 -07002476 obj = mSettings.getUserIdLPr(uid2);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002477 if (obj != null) {
2478 if (obj instanceof SharedUserSetting) {
2479 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2480 } else if (obj instanceof PackageSetting) {
2481 s2 = ((PackageSetting)obj).signatures.mSignatures;
2482 } else {
2483 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2484 }
2485 } else {
2486 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2487 }
Kenny Root447106f2011-03-23 11:00:15 -07002488 return compareSignatures(s1, s2);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002489 }
2490 }
2491
Kenny Root447106f2011-03-23 11:00:15 -07002492 static int compareSignatures(Signature[] s1, Signature[] s2) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002493 if (s1 == null) {
2494 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 ? PackageManager.SIGNATURE_NEITHER_SIGNED
2496 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2497 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002498 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2500 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002501 HashSet<Signature> set1 = new HashSet<Signature>();
2502 for (Signature sig : s1) {
2503 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002505 HashSet<Signature> set2 = new HashSet<Signature>();
2506 for (Signature sig : s2) {
2507 set2.add(sig);
2508 }
2509 // Make sure s2 contains all signatures in s1.
2510 if (set1.equals(set2)) {
2511 return PackageManager.SIGNATURE_MATCH;
2512 }
2513 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 }
2515
2516 public String[] getPackagesForUid(int uid) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002517 uid = UserHandle.getAppId(uid);
Kenny Root447106f2011-03-23 11:00:15 -07002518 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002520 Object obj = mSettings.getUserIdLPr(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 if (obj instanceof SharedUserSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002522 final SharedUserSetting sus = (SharedUserSetting) obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 final int N = sus.packages.size();
Kenny Root447106f2011-03-23 11:00:15 -07002524 final String[] res = new String[N];
2525 final Iterator<PackageSetting> it = sus.packages.iterator();
2526 int i = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 while (it.hasNext()) {
2528 res[i++] = it.next().name;
2529 }
2530 return res;
2531 } else if (obj instanceof PackageSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002532 final PackageSetting ps = (PackageSetting) obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 return new String[] { ps.name };
2534 }
2535 }
2536 return null;
2537 }
2538
2539 public String getNameForUid(int uid) {
Kenny Root447106f2011-03-23 11:00:15 -07002540 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 synchronized (mPackages) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002542 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 if (obj instanceof SharedUserSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002544 final SharedUserSetting sus = (SharedUserSetting) obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 return sus.name + ":" + sus.userId;
2546 } else if (obj instanceof PackageSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002547 final PackageSetting ps = (PackageSetting) obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 return ps.name;
2549 }
2550 }
2551 return null;
2552 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 public int getUidForSharedUser(String sharedUserName) {
2555 if(sharedUserName == null) {
2556 return -1;
2557 }
Kenny Root447106f2011-03-23 11:00:15 -07002558 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002560 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
Amith Yamasani742a6712011-05-04 14:49:28 -07002561 if (suid == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 return -1;
2563 }
2564 return suid.userId;
2565 }
2566 }
2567
Amith Yamasani483f3b02012-03-13 16:08:00 -07002568 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002570 int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002571 if (!sUserManager.exists(userId)) return null;
Amith Yamasanif203aee2012-08-29 18:41:53 -07002572 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
Amith Yamasani483f3b02012-03-13 16:08:00 -07002573 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2574 return chooseBestActivity(intent, resolvedType, flags, query, userId);
Mihai Predaeae850c2009-05-13 10:13:48 +02002575 }
2576
Mihai Predaeae850c2009-05-13 10:13:48 +02002577 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002578 int flags, List<ResolveInfo> query, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 if (query != null) {
2580 final int N = query.size();
2581 if (N == 1) {
2582 return query.get(0);
2583 } else if (N > 1) {
2584 // If there is more than one activity with the same priority,
2585 // then let the user decide between them.
2586 ResolveInfo r0 = query.get(0);
2587 ResolveInfo r1 = query.get(1);
Kenny Root4dfe6ff2011-02-23 17:00:43 -08002588 if (DEBUG_INTENT_MATCHING) {
2589 Log.d(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2590 + r1.activityInfo.name + "=" + r1.priority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 }
2592 // If the first activity has a higher priority, or a different
2593 // default, then it is always desireable to pick it.
2594 if (r0.priority != r1.priority
2595 || r0.preferredOrder != r1.preferredOrder
2596 || r0.isDefault != r1.isDefault) {
2597 return query.get(0);
2598 }
2599 // If we have saved a preference for a preferred activity for
2600 // this Intent, use that.
2601 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002602 flags, query, r0.priority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 if (ri != null) {
2604 return ri;
2605 }
Dianne Hackborn8da429e2012-09-23 12:52:19 -07002606 if (userId != 0) {
2607 ri = new ResolveInfo(mResolveInfo);
2608 ri.activityInfo = new ActivityInfo(ri.activityInfo);
2609 ri.activityInfo.applicationInfo = new ApplicationInfo(
2610 ri.activityInfo.applicationInfo);
2611 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2612 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2613 return ri;
2614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 return mResolveInfo;
2616 }
2617 }
2618 return null;
2619 }
2620
2621 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002622 int flags, List<ResolveInfo> query, int priority, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07002623 if (!sUserManager.exists(userId)) return null;
Kenny Root447106f2011-03-23 11:00:15 -07002624 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 synchronized (mPackages) {
Dianne Hackbornf5b86712011-12-05 17:42:41 -08002626 if (intent.getSelector() != null) {
2627 intent = intent.getSelector();
2628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
Dianne Hackborn63092712012-10-07 14:45:35 -07002630 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
2631 List<PreferredActivity> prefs = pir != null
2632 ? pir.queryIntent(intent, resolvedType,
2633 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2634 : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 if (prefs != null && prefs.size() > 0) {
2636 // First figure out how good the original match set is.
2637 // We will only allow preferred activities that came
2638 // from the same match quality.
2639 int match = 0;
Kenny Root447106f2011-03-23 11:00:15 -07002640
2641 if (DEBUG_PREFERRED) {
2642 Log.v(TAG, "Figuring out best match...");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002643 }
Kenny Root447106f2011-03-23 11:00:15 -07002644
2645 final int N = query.size();
2646 for (int j=0; j<N; j++) {
2647 final ResolveInfo ri = query.get(j);
2648 if (DEBUG_PREFERRED) {
2649 Log.v(TAG, "Match for " + ri.activityInfo + ": 0x"
2650 + Integer.toHexString(match));
2651 }
2652 if (ri.match > match) {
2653 match = ri.match;
2654 }
2655 }
2656
2657 if (DEBUG_PREFERRED) {
2658 Log.v(TAG, "Best match: 0x" + Integer.toHexString(match));
2659 }
2660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 match &= IntentFilter.MATCH_CATEGORY_MASK;
2662 final int M = prefs.size();
2663 for (int i=0; i<M; i++) {
Kenny Root447106f2011-03-23 11:00:15 -07002664 final PreferredActivity pa = prefs.get(i);
Dianne Hackbornf8b8a3f2011-03-04 00:05:31 -08002665 if (pa.mPref.mMatch != match) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 continue;
2667 }
Dianne Hackborn77119bc2012-10-23 14:32:48 -07002668 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
2669 flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 if (DEBUG_PREFERRED) {
2671 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002672 if (ai != null) {
2673 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2674 } else {
2675 Log.v(TAG, " null");
2676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 }
Dianne Hackborn04505102012-02-29 12:34:04 -08002678 if (ai == null) {
2679 // This previously registered preferred activity
2680 // component is no longer known. Most likely an update
2681 // to the app was installed and in the new version this
2682 // component no longer exists. Clean it up by removing
2683 // it from the preferred activities list, and skip it.
2684 Slog.w(TAG, "Removing dangling preferred activity: "
2685 + pa.mPref.mComponent);
Dianne Hackborn63092712012-10-07 14:45:35 -07002686 pir.removeFilter(pa);
Dianne Hackborn04505102012-02-29 12:34:04 -08002687 continue;
2688 }
2689 for (int j=0; j<N; j++) {
2690 final ResolveInfo ri = query.get(j);
2691 if (!ri.activityInfo.applicationInfo.packageName
2692 .equals(ai.applicationInfo.packageName)) {
2693 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 }
Dianne Hackborn04505102012-02-29 12:34:04 -08002695 if (!ri.activityInfo.name.equals(ai.name)) {
2696 continue;
2697 }
2698
2699 // Okay we found a previously set preferred app.
2700 // If the result set is different from when this
2701 // was created, we need to clear it and re-ask the
2702 // user their preference.
2703 if (!pa.mPref.sameSet(query, priority)) {
2704 Slog.i(TAG, "Result set changed, dropping preferred activity for "
2705 + intent + " type " + resolvedType);
Dianne Hackborn63092712012-10-07 14:45:35 -07002706 pir.removeFilter(pa);
Dianne Hackborn04505102012-02-29 12:34:04 -08002707 return null;
2708 }
2709
2710 // Yay!
2711 return ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712 }
2713 }
2714 }
2715 }
2716 return null;
2717 }
2718
Amith Yamasani483f3b02012-03-13 16:08:00 -07002719 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 public List<ResolveInfo> queryIntentActivities(Intent intent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002721 String resolvedType, int flags, int userId) {
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002722 if (!sUserManager.exists(userId)) return Collections.emptyList();
Amith Yamasanif203aee2012-08-29 18:41:53 -07002723 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
Dianne Hackbornf5b86712011-12-05 17:42:41 -08002724 ComponentName comp = intent.getComponent();
2725 if (comp == null) {
2726 if (intent.getSelector() != null) {
2727 intent = intent.getSelector();
2728 comp = intent.getComponent();
2729 }
2730 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732 if (comp != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002733 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
Amith Yamasani483f3b02012-03-13 16:08:00 -07002734 final ActivityInfo ai = getActivityInfo(comp, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 if (ai != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002736 final ResolveInfo ri = new ResolveInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 ri.activityInfo = ai;
2738 list.add(ri);
2739 }
2740 return list;
2741 }
2742
Kenny Root447106f2011-03-23 11:00:15 -07002743 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002745 final String pkgName = intent.getPackage();
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002746 if (pkgName == null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002747 return mActivities.queryIntent(intent, resolvedType, flags, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002748 }
Kenny Root447106f2011-03-23 11:00:15 -07002749 final PackageParser.Package pkg = mPackages.get(pkgName);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002750 if (pkg != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002751 return mActivities.queryIntentForPackage(intent, resolvedType, flags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002752 pkg.activities, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002753 }
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002754 return new ArrayList<ResolveInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 }
2756 }
2757
Amith Yamasani483f3b02012-03-13 16:08:00 -07002758 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2760 Intent[] specifics, String[] specificTypes, Intent intent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002761 String resolvedType, int flags, int userId) {
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002762 if (!sUserManager.exists(userId)) return Collections.emptyList();
Amith Yamasanif203aee2012-08-29 18:41:53 -07002763 enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
2764 "query intent activity options");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 final String resultsAction = intent.getAction();
2766
Kenny Root447106f2011-03-23 11:00:15 -07002767 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
Amith Yamasani483f3b02012-03-13 16:08:00 -07002768 | PackageManager.GET_RESOLVED_FILTER, userId);
Kenny Root447106f2011-03-23 11:00:15 -07002769
2770 if (DEBUG_INTENT_MATCHING) {
2771 Log.v(TAG, "Query " + intent + ": " + results);
2772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773
2774 int specificsPos = 0;
2775 int N;
2776
2777 // todo: note that the algorithm used here is O(N^2). This
2778 // isn't a problem in our current environment, but if we start running
2779 // into situations where we have more than 5 or 10 matches then this
2780 // should probably be changed to something smarter...
2781
2782 // First we go through and resolve each of the specific items
2783 // that were supplied, taking care of removing any corresponding
2784 // duplicate items in the generic resolve list.
2785 if (specifics != null) {
2786 for (int i=0; i<specifics.length; i++) {
2787 final Intent sintent = specifics[i];
2788 if (sintent == null) {
2789 continue;
2790 }
2791
Kenny Root447106f2011-03-23 11:00:15 -07002792 if (DEBUG_INTENT_MATCHING) {
2793 Log.v(TAG, "Specific #" + i + ": " + sintent);
2794 }
2795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 String action = sintent.getAction();
2797 if (resultsAction != null && resultsAction.equals(action)) {
2798 // If this action was explicitly requested, then don't
2799 // remove things that have it.
2800 action = null;
2801 }
Kenny Root447106f2011-03-23 11:00:15 -07002802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 ResolveInfo ri = null;
2804 ActivityInfo ai = null;
Kenny Root447106f2011-03-23 11:00:15 -07002805
2806 ComponentName comp = sintent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002807 if (comp == null) {
2808 ri = resolveIntent(
2809 sintent,
2810 specificTypes != null ? specificTypes[i] : null,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002811 flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 if (ri == null) {
2813 continue;
2814 }
2815 if (ri == mResolveInfo) {
2816 // ACK! Must do something better with this.
2817 }
2818 ai = ri.activityInfo;
2819 comp = new ComponentName(ai.applicationInfo.packageName,
2820 ai.name);
2821 } else {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002822 ai = getActivityInfo(comp, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 if (ai == null) {
2824 continue;
2825 }
2826 }
2827
2828 // Look for any generic query activities that are duplicates
2829 // of this specific one, and remove them from the results.
Kenny Root9718cf52011-02-23 16:45:26 -08002830 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 N = results.size();
2832 int j;
2833 for (j=specificsPos; j<N; j++) {
2834 ResolveInfo sri = results.get(j);
2835 if ((sri.activityInfo.name.equals(comp.getClassName())
2836 && sri.activityInfo.applicationInfo.packageName.equals(
2837 comp.getPackageName()))
2838 || (action != null && sri.filter.matchAction(action))) {
2839 results.remove(j);
Kenny Root9718cf52011-02-23 16:45:26 -08002840 if (DEBUG_INTENT_MATCHING) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 TAG, "Removing duplicate item from " + j
2842 + " due to specific " + specificsPos);
2843 if (ri == null) {
2844 ri = sri;
2845 }
2846 j--;
2847 N--;
2848 }
2849 }
2850
2851 // Add this specific item to its proper place.
2852 if (ri == null) {
2853 ri = new ResolveInfo();
2854 ri.activityInfo = ai;
2855 }
2856 results.add(specificsPos, ri);
2857 ri.specificIndex = i;
2858 specificsPos++;
2859 }
2860 }
2861
2862 // Now we go through the remaining generic results and remove any
2863 // duplicate actions that are found here.
2864 N = results.size();
2865 for (int i=specificsPos; i<N-1; i++) {
2866 final ResolveInfo rii = results.get(i);
2867 if (rii.filter == null) {
2868 continue;
2869 }
2870
2871 // Iterate over all of the actions of this result's intent
2872 // filter... typically this should be just one.
2873 final Iterator<String> it = rii.filter.actionsIterator();
2874 if (it == null) {
2875 continue;
2876 }
2877 while (it.hasNext()) {
2878 final String action = it.next();
2879 if (resultsAction != null && resultsAction.equals(action)) {
2880 // If this action was explicitly requested, then don't
2881 // remove things that have it.
2882 continue;
2883 }
2884 for (int j=i+1; j<N; j++) {
2885 final ResolveInfo rij = results.get(j);
2886 if (rij.filter != null && rij.filter.hasAction(action)) {
2887 results.remove(j);
Kenny Root9718cf52011-02-23 16:45:26 -08002888 if (DEBUG_INTENT_MATCHING) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002889 TAG, "Removing duplicate item from " + j
2890 + " due to action " + action + " at " + i);
2891 j--;
2892 N--;
2893 }
2894 }
2895 }
2896
2897 // If the caller didn't request filter information, drop it now
2898 // so we don't have to marshall/unmarshall it.
2899 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2900 rii.filter = null;
2901 }
2902 }
2903
2904 // Filter out the caller activity if so requested.
2905 if (caller != null) {
2906 N = results.size();
2907 for (int i=0; i<N; i++) {
2908 ActivityInfo ainfo = results.get(i).activityInfo;
2909 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2910 && caller.getClassName().equals(ainfo.name)) {
2911 results.remove(i);
2912 break;
2913 }
2914 }
2915 }
2916
2917 // If the caller didn't request filter information,
2918 // drop them now so we don't have to
2919 // marshall/unmarshall it.
2920 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2921 N = results.size();
2922 for (int i=0; i<N; i++) {
2923 results.get(i).filter = null;
2924 }
2925 }
2926
Kenny Root9718cf52011-02-23 16:45:26 -08002927 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002928 return results;
2929 }
2930
Amith Yamasani483f3b02012-03-13 16:08:00 -07002931 @Override
2932 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
2933 int userId) {
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002934 if (!sUserManager.exists(userId)) return Collections.emptyList();
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002935 ComponentName comp = intent.getComponent();
Dianne Hackbornf5b86712011-12-05 17:42:41 -08002936 if (comp == null) {
2937 if (intent.getSelector() != null) {
2938 intent = intent.getSelector();
2939 comp = intent.getComponent();
2940 }
2941 }
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002942 if (comp != null) {
2943 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
Amith Yamasani483f3b02012-03-13 16:08:00 -07002944 ActivityInfo ai = getReceiverInfo(comp, flags, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002945 if (ai != null) {
2946 ResolveInfo ri = new ResolveInfo();
2947 ri.activityInfo = ai;
2948 list.add(ri);
2949 }
2950 return list;
2951 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002952
Kenny Root447106f2011-03-23 11:00:15 -07002953 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002954 synchronized (mPackages) {
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002955 String pkgName = intent.getPackage();
2956 if (pkgName == null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002957 return mReceivers.queryIntent(intent, resolvedType, flags, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002958 }
Kenny Root447106f2011-03-23 11:00:15 -07002959 final PackageParser.Package pkg = mPackages.get(pkgName);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002960 if (pkg != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07002961 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
2962 userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002963 }
2964 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965 }
2966 }
2967
Amith Yamasani483f3b02012-03-13 16:08:00 -07002968 @Override
2969 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
2970 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
Amith Yamasani13593602012-03-22 16:16:17 -07002971 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002972 if (query != null) {
2973 if (query.size() >= 1) {
2974 // If there is more than one service with the same priority,
2975 // just arbitrarily pick the first one.
2976 return query.get(0);
2977 }
2978 }
2979 return null;
2980 }
2981
Amith Yamasani483f3b02012-03-13 16:08:00 -07002982 @Override
2983 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
2984 int userId) {
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002985 if (!sUserManager.exists(userId)) return Collections.emptyList();
Dianne Hackbornf5b86712011-12-05 17:42:41 -08002986 ComponentName comp = intent.getComponent();
2987 if (comp == null) {
2988 if (intent.getSelector() != null) {
2989 intent = intent.getSelector();
2990 comp = intent.getComponent();
2991 }
2992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002993 if (comp != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002994 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
Amith Yamasani483f3b02012-03-13 16:08:00 -07002995 final ServiceInfo si = getServiceInfo(comp, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002996 if (si != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002997 final ResolveInfo ri = new ResolveInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998 ri.serviceInfo = si;
2999 list.add(ri);
3000 }
3001 return list;
3002 }
3003
Kenny Root447106f2011-03-23 11:00:15 -07003004 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003005 synchronized (mPackages) {
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07003006 String pkgName = intent.getPackage();
3007 if (pkgName == null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003008 return mServices.queryIntent(intent, resolvedType, flags, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07003009 }
Kenny Root447106f2011-03-23 11:00:15 -07003010 final PackageParser.Package pkg = mPackages.get(pkgName);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07003011 if (pkg != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003012 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3013 userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07003014 }
3015 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016 }
3017 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003018
Amith Yamasani151ec4c2012-09-07 19:25:16 -07003019 @Override
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08003020 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
Kenny Root0e2c0f32011-04-15 17:50:10 -07003021 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
Amith Yamasani151ec4c2012-09-07 19:25:16 -07003022
3023 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003024
Kenny Root447106f2011-03-23 11:00:15 -07003025 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026 synchronized (mPackages) {
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08003027 ArrayList<PackageInfo> list;
Kenny Root0e2c0f32011-04-15 17:50:10 -07003028 if (listUninstalled) {
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08003029 list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3030 for (PackageSetting ps : mSettings.mPackages.values()) {
3031 PackageInfo pi;
3032 if (ps.pkg != null) {
3033 pi = generatePackageInfo(ps.pkg, flags, userId);
3034 } else {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003035 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 }
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08003037 if (pi != null) {
3038 list.add(pi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003039 }
3040 }
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08003041 } else {
3042 list = new ArrayList<PackageInfo>(mPackages.size());
3043 for (PackageParser.Package p : mPackages.values()) {
3044 PackageInfo pi = generatePackageInfo(p, flags, userId);
3045 if (pi != null) {
3046 list.add(pi);
3047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 }
3049 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07003050
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08003051 return new ParceledListSlice<PackageInfo>(list);
3052 }
3053 }
3054
3055 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3056 String[] permissions, boolean[] tmp, int flags, int userId) {
3057 int numMatch = 0;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003058 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08003059 for (int i=0; i<permissions.length; i++) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003060 if (gp.grantedPermissions.contains(permissions[i])) {
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08003061 tmp[i] = true;
3062 numMatch++;
3063 } else {
3064 tmp[i] = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003066 }
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08003067 if (numMatch == 0) {
3068 return;
3069 }
3070 PackageInfo pi;
3071 if (ps.pkg != null) {
3072 pi = generatePackageInfo(ps.pkg, flags, userId);
3073 } else {
3074 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3075 }
3076 if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3077 if (numMatch == permissions.length) {
3078 pi.requestedPermissions = permissions;
3079 } else {
3080 pi.requestedPermissions = new String[numMatch];
3081 numMatch = 0;
3082 for (int i=0; i<permissions.length; i++) {
3083 if (tmp[i]) {
3084 pi.requestedPermissions[numMatch] = permissions[i];
3085 numMatch++;
3086 }
3087 }
3088 }
3089 }
3090 list.add(pi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003091 }
3092
Amith Yamasani483f3b02012-03-13 16:08:00 -07003093 @Override
Dianne Hackborne7991752013-01-16 17:56:46 -08003094 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08003095 String[] permissions, int flags, int userId) {
Dianne Hackborne7991752013-01-16 17:56:46 -08003096 if (!sUserManager.exists(userId)) return null;
Dianne Hackborne7991752013-01-16 17:56:46 -08003097 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3098
3099 // writer
3100 synchronized (mPackages) {
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08003101 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3102 boolean[] tmpBools = new boolean[permissions.length];
Dianne Hackborne7991752013-01-16 17:56:46 -08003103 if (listUninstalled) {
3104 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08003105 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
Dianne Hackborne7991752013-01-16 17:56:46 -08003106 }
3107 } else {
3108 for (PackageParser.Package pkg : mPackages.values()) {
3109 PackageSetting ps = (PackageSetting)pkg.mExtras;
3110 if (ps != null) {
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08003111 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3112 userId);
3113 }
3114 }
3115 }
3116
3117 return new ParceledListSlice<PackageInfo>(list);
3118 }
3119 }
3120
3121 @Override
3122 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3123 if (!sUserManager.exists(userId)) return null;
3124 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3125
3126 // writer
3127 synchronized (mPackages) {
3128 ArrayList<ApplicationInfo> list;
3129 if (listUninstalled) {
3130 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3131 for (PackageSetting ps : mSettings.mPackages.values()) {
3132 ApplicationInfo ai;
3133 if (ps.pkg != null) {
3134 ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3135 ps.readUserState(userId), userId);
3136 } else {
3137 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3138 }
3139 if (ai != null) {
3140 list.add(ai);
3141 }
3142 }
3143 } else {
3144 list = new ArrayList<ApplicationInfo>(mPackages.size());
3145 for (PackageParser.Package p : mPackages.values()) {
3146 if (p.mExtras != null) {
3147 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3148 ((PackageSetting)p.mExtras).readUserState(userId), userId);
3149 if (ai != null) {
3150 list.add(ai);
Dianne Hackborne7991752013-01-16 17:56:46 -08003151 }
3152 }
3153 }
3154 }
3155
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -08003156 return new ParceledListSlice<ApplicationInfo>(list);
Dianne Hackborne7991752013-01-16 17:56:46 -08003157 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 }
3159
3160 public List<ApplicationInfo> getPersistentApplications(int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07003161 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003162
Kenny Root447106f2011-03-23 11:00:15 -07003163 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003164 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07003165 final Iterator<PackageParser.Package> i = mPackages.values().iterator();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003166 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 while (i.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07003168 final PackageParser.Package p = i.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003169 if (p.applicationInfo != null
3170 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07003171 && (!mSafeMode || isSystemApp(p))) {
Amith Yamasani13593602012-03-22 16:16:17 -07003172 PackageSetting ps = mSettings.mPackages.get(p.packageName);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003173 if (ps != null) {
3174 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3175 ps.readUserState(userId), userId);
3176 if (ai != null) {
3177 finalList.add(ai);
3178 }
3179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 }
3181 }
3182 }
3183
3184 return finalList;
3185 }
3186
Amith Yamasani483f3b02012-03-13 16:08:00 -07003187 @Override
3188 public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07003189 if (!sUserManager.exists(userId)) return null;
Kenny Root447106f2011-03-23 11:00:15 -07003190 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191 synchronized (mPackages) {
3192 final PackageParser.Provider provider = mProviders.get(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003193 PackageSetting ps = provider != null
3194 ? mSettings.mPackages.get(provider.owner.packageName)
3195 : null;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003196 return ps != null
Amith Yamasani483f3b02012-03-13 16:08:00 -07003197 && mSettings.isEnabledLPr(provider.info, flags, userId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 && (!mSafeMode || (provider.info.applicationInfo.flags
3199 &ApplicationInfo.FLAG_SYSTEM) != 0)
Amith Yamasani13593602012-03-22 16:16:17 -07003200 ? PackageParser.generateProviderInfo(provider, flags,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003201 ps.readUserState(userId), userId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003202 : null;
3203 }
3204 }
3205
Fred Quintana718d8a22009-04-29 17:53:20 -07003206 /**
3207 * @deprecated
3208 */
Kenny Root60f7ad82011-03-22 12:49:06 -07003209 @Deprecated
3210 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
Kenny Root447106f2011-03-23 11:00:15 -07003211 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003212 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07003213 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProviders.entrySet()
3214 .iterator();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003215 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003216 while (i.hasNext()) {
3217 Map.Entry<String, PackageParser.Provider> entry = i.next();
3218 PackageParser.Provider p = entry.getValue();
Amith Yamasani13593602012-03-22 16:16:17 -07003219 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003221 if (ps != null && p.syncable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 && (!mSafeMode || (p.info.applicationInfo.flags
3223 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003224 ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3225 ps.readUserState(userId), userId);
3226 if (info != null) {
3227 outNames.add(entry.getKey());
3228 outInfo.add(info);
3229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 }
3231 }
3232 }
3233 }
3234
3235 public List<ProviderInfo> queryContentProviders(String processName,
3236 int uid, int flags) {
3237 ArrayList<ProviderInfo> finalList = null;
3238
Kenny Root447106f2011-03-23 11:00:15 -07003239 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07003241 final Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
Amith Yamasani483f3b02012-03-13 16:08:00 -07003242 final int userId = processName != null ?
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003243 UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003244 while (i.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07003245 final PackageParser.Provider p = i.next();
Amith Yamasani13593602012-03-22 16:16:17 -07003246 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003247 if (ps != null && p.info.authority != null
Kenny Root447106f2011-03-23 11:00:15 -07003248 && (processName == null
3249 || (p.info.processName.equals(processName)
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003250 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
Amith Yamasani483f3b02012-03-13 16:08:00 -07003251 && mSettings.isEnabledLPr(p.info, flags, userId)
Kenny Root447106f2011-03-23 11:00:15 -07003252 && (!mSafeMode
3253 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 if (finalList == null) {
3255 finalList = new ArrayList<ProviderInfo>(3);
3256 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003257 ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3258 ps.readUserState(userId), userId);
Dianne Hackborn4428e172012-08-24 17:43:05 -07003259 if (info != null) {
3260 finalList.add(info);
3261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003262 }
3263 }
3264 }
3265
3266 if (finalList != null) {
3267 Collections.sort(finalList, mProviderInitOrderSorter);
3268 }
3269
3270 return finalList;
3271 }
3272
3273 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3274 int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07003275 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276 synchronized (mPackages) {
3277 final PackageParser.Instrumentation i = mInstrumentation.get(name);
3278 return PackageParser.generateInstrumentationInfo(i, flags);
3279 }
3280 }
3281
3282 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3283 int flags) {
3284 ArrayList<InstrumentationInfo> finalList =
3285 new ArrayList<InstrumentationInfo>();
3286
Kenny Root447106f2011-03-23 11:00:15 -07003287 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003288 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07003289 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003290 while (i.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07003291 final PackageParser.Instrumentation p = i.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292 if (targetPackage == null
3293 || targetPackage.equals(p.info.targetPackage)) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07003294 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3295 flags);
3296 if (ii != null) {
3297 finalList.add(ii);
3298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 }
3300 }
3301 }
3302
3303 return finalList;
3304 }
3305
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003306 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 String[] files = dir.list();
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07003308 if (files == null) {
3309 Log.d(TAG, "No files in app dir " + dir);
3310 return;
3311 }
3312
Kenny Root4dfe6ff2011-02-23 17:00:43 -08003313 if (DEBUG_PACKAGE_SCANNING) {
Joe Onorato431bb222010-10-18 19:13:23 -04003314 Log.d(TAG, "Scanning app dir " + dir);
3315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316
3317 int i;
3318 for (i=0; i<files.length; i++) {
3319 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003320 if (!isPackageFilename(files[i])) {
3321 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08003322 continue;
3323 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003324 PackageParser.Package pkg = scanPackageLI(file,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003325 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003326 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08003327 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
3328 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003329 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003330 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003331 file.delete();
3332 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 }
3334 }
3335
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003336 private static File getSettingsProblemFile() {
3337 File dataDir = Environment.getDataDirectory();
3338 File systemDir = new File(dataDir, "system");
3339 File fname = new File(systemDir, "uiderrors.txt");
3340 return fname;
3341 }
3342
Kenny Rootcf0b38c2011-03-22 14:17:59 -07003343 static void reportSettingsProblem(int priority, String msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003345 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 FileOutputStream out = new FileOutputStream(fname, true);
3347 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003348 SimpleDateFormat formatter = new SimpleDateFormat();
3349 String dateString = formatter.format(new Date(System.currentTimeMillis()));
3350 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 pw.close();
3352 FileUtils.setPermissions(
3353 fname.toString(),
3354 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
3355 -1, -1);
3356 } catch (java.io.IOException e) {
3357 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003358 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 }
3360
3361 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
3362 PackageParser.Package pkg, File srcFile, int parseFlags) {
3363 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07003364 if (ps != null
3365 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07003366 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07003367 if (ps.signatures.mSignatures != null
3368 && ps.signatures.mSignatures.length != 0) {
3369 // Optimization: reuse the existing cached certificates
3370 // if the package appears to be unchanged.
3371 pkg.mSignatures = ps.signatures.mSignatures;
3372 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003373 }
Jeff Browne7600722010-04-07 18:28:23 -07003374
3375 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003376 } else {
Jeff Browne7600722010-04-07 18:28:23 -07003377 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
3378 }
3379
3380 if (!pp.collectCertificates(pkg, parseFlags)) {
3381 mLastScanError = pp.getParseError();
3382 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 }
3384 }
3385 return true;
3386 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388 /*
3389 * Scan a package and return the newly parsed package.
3390 * Returns null in case of errors and the error code is stored in mLastScanError
3391 */
3392 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003393 int parseFlags, int scanMode, long currentTime, UserHandle user) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003394 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003395 String scanPath = scanFile.getPath();
Dianne Hackbornc895be72013-03-11 17:48:43 -07003396 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003398 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003399 pp.setSeparateProcesses(mSeparateProcesses);
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07003400 pp.setOnlyCoreApps(mOnlyCore);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003401 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003402 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 if (pkg == null) {
3404 mLastScanError = pp.getParseError();
3405 return null;
3406 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003407 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003408 PackageSetting updatedPkg;
Kenny Root447106f2011-03-23 11:00:15 -07003409 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003411 // Look to see if we already know about this package.
3412 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08003413 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003414 // This package has been renamed to its original name. Let's
3415 // use that.
Kenny Root447106f2011-03-23 11:00:15 -07003416 ps = mSettings.peekPackageLPr(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003417 }
3418 // If there was no original package, see one for the real package name.
3419 if (ps == null) {
Kenny Root447106f2011-03-23 11:00:15 -07003420 ps = mSettings.peekPackageLPr(pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003421 }
3422 // Check to see if this package could be hiding/updating a system
3423 // package. Must look for it either under the original or real
3424 // package name depending on our state.
Kenny Rootc52d6fd2012-05-07 23:04:52 -07003425 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
Dianne Hackbornc895be72013-03-11 17:48:43 -07003426 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003428 // First check if this is a system package that may involve an update
3429 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07003430 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003431 // The path has changed from what was last scanned... check the
3432 // version of the new path against what we have stored to determine
3433 // what to do.
Dianne Hackbornc895be72013-03-11 17:48:43 -07003434 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003435 if (pkg.mVersionCode < ps.versionCode) {
3436 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003437 // Ignore entry. Skip it.
3438 Log.i(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborncef65ee2010-09-30 18:27:22 -07003439 + " ignored: updated version " + ps.versionCode
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003440 + " better than this " + pkg.mVersionCode);
Dianne Hackbornc4d27a72013-01-22 18:30:17 -08003441 if (!updatedPkg.codePath.equals(scanFile)) {
3442 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
3443 + ps.name + " changing from " + updatedPkg.codePathString
3444 + " to " + scanFile);
3445 updatedPkg.codePath = scanFile;
3446 updatedPkg.codePathString = scanFile.toString();
3447 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07003448 updatedPkg.pkg = pkg;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003449 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3450 return null;
3451 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003452 // The current app on the system partion is better than
3453 // what we have updated to on the data partition; switch
3454 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003455 // At this point, its safely assumed that package installation for
3456 // apps in system partition will go through. If not there won't be a working
3457 // version of the app
Kenny Root447106f2011-03-23 11:00:15 -07003458 // writer
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003459 synchronized (mPackages) {
3460 // Just remove the loaded entries from package lists.
3461 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003462 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003463 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003464 + "reverting from " + ps.codePathString
3465 + ": new version " + pkg.mVersionCode
3466 + " better than installed " + ps.versionCode);
Kenny Root88670d82012-05-09 15:47:35 -07003467
3468 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3469 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
Dianne Hackborn4428e172012-08-24 17:43:05 -07003470 synchronized (mInstallLock) {
Kenny Root208d3412012-05-07 19:42:35 -07003471 args.cleanUpResourcesLI();
3472 }
3473 synchronized (mPackages) {
3474 mSettings.enableSystemPackageLPw(ps.name);
3475 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003477 }
3478 }
Kenny Root208d3412012-05-07 19:42:35 -07003479
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003480 if (updatedPkg != null) {
Kenny Root208d3412012-05-07 19:42:35 -07003481 // An updated system app will not have the PARSE_IS_SYSTEM flag set
3482 // initially
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003483 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
3484 }
3485 // Verify certificates against what was last scanned
3486 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003487 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003488 return null;
3489 }
Kenny Root208d3412012-05-07 19:42:35 -07003490
3491 /*
3492 * A new system app appeared, but we already had a non-system one of the
3493 * same name installed earlier.
3494 */
3495 boolean shouldHideSystemApp = false;
3496 if (updatedPkg == null && ps != null
3497 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
3498 /*
3499 * Check to make sure the signatures match first. If they don't,
3500 * wipe the installed application and its data.
3501 */
3502 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
3503 != PackageManager.SIGNATURE_MATCH) {
Dianne Hackbornc895be72013-03-11 17:48:43 -07003504 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
Christopher Tateacee6e92013-05-14 16:11:44 -07003505 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
Kenny Root208d3412012-05-07 19:42:35 -07003506 ps = null;
3507 } else {
3508 /*
3509 * If the newly-added system app is an older version than the
3510 * already installed version, hide it. It will be scanned later
3511 * and re-added like an update.
3512 */
3513 if (pkg.mVersionCode < ps.versionCode) {
3514 shouldHideSystemApp = true;
3515 } else {
3516 /*
3517 * The newly found system app is a newer version that the
3518 * one previously installed. Simply remove the
3519 * already-installed application and replace it with our own
3520 * while keeping the application data.
3521 */
3522 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
3523 + ps.codePathString + ": new version " + pkg.mVersionCode
3524 + " better than installed " + ps.versionCode);
Kenny Root88670d82012-05-09 15:47:35 -07003525 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3526 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
Dianne Hackborn4428e172012-08-24 17:43:05 -07003527 synchronized (mInstallLock) {
Kenny Root208d3412012-05-07 19:42:35 -07003528 args.cleanUpResourcesLI();
3529 }
3530 }
3531 }
3532 }
3533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003534 // The apk is forward locked (not public) if its code and resources
Masanori Ogino2d910072012-05-07 16:44:48 +09003535 // are kept in different files. (except for app in either system or
3536 // vendor path).
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003537 // TODO grab this value from PackageSettings
Masanori Ogino2d910072012-05-07 16:44:48 +09003538 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
3539 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
3540 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
3541 }
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07003542 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003543
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003544 String codePath = null;
3545 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003546 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
3547 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003548 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003549 } else {
3550 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003551 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003552 }
3553 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003554 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003555 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003556 codePath = pkg.mScanPath;
3557 // Set application objects path explicitly.
3558 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003559 // Note that we invoke the following method only if we are about to unpack an application
Kenny Root208d3412012-05-07 19:42:35 -07003560 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003561 | SCAN_UPDATE_SIGNATURE, currentTime, user);
Kenny Root208d3412012-05-07 19:42:35 -07003562
3563 /*
3564 * If the system app should be overridden by a previously installed
3565 * data, hide the system app now and let the /data/app scan pick it up
3566 * again.
3567 */
3568 if (shouldHideSystemApp) {
3569 synchronized (mPackages) {
3570 /*
3571 * We have to grant systems permissions before we hide, because
3572 * grantPermissions will assume the package update is trying to
3573 * expand its permissions.
3574 */
3575 grantPermissionsLPw(pkg, true);
3576 mSettings.disableSystemPackageLPw(pkg.packageName);
3577 }
3578 }
3579
3580 return scannedPkg;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003581 }
3582
Kenny Root85387d72010-08-26 10:13:11 -07003583 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
3584 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003585 pkg.mPath = pkg.mScanPath = destCodePath;
3586 pkg.applicationInfo.sourceDir = destCodePath;
3587 pkg.applicationInfo.publicSourceDir = destResPath;
3588 }
3589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003590 private static String fixProcessName(String defProcessName,
3591 String processName, int uid) {
3592 if (processName == null) {
3593 return defProcessName;
3594 }
3595 return processName;
3596 }
3597
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003598 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003599 PackageParser.Package pkg) {
3600 if (pkgSetting.signatures.mSignatures != null) {
3601 // Already existing package. Make sure signatures match
Kenny Root447106f2011-03-23 11:00:15 -07003602 if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003603 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003604 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003605 + " signatures do not match the previously installed version; ignoring!");
3606 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003607 return false;
3608 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003609 }
3610 // Check for shared user signatures
3611 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
Kenny Root447106f2011-03-23 11:00:15 -07003612 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003613 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3614 Slog.e(TAG, "Package " + pkg.packageName
3615 + " has no signatures that match those in shared user "
3616 + pkgSetting.sharedUser.name + "; ignoring!");
3617 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
3618 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 }
3621 return true;
3622 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003623
Kenny Root461ff1f2011-08-09 09:43:03 -07003624 /**
3625 * Enforces that only the system UID or root's UID can call a method exposed
3626 * via Binder.
3627 *
3628 * @param message used as message if SecurityException is thrown
3629 * @throws SecurityException if the caller is not system or root
3630 */
3631 private static final void enforceSystemOrRoot(String message) {
3632 final int uid = Binder.getCallingUid();
3633 if (uid != Process.SYSTEM_UID && uid != 0) {
3634 throw new SecurityException(message);
3635 }
3636 }
3637
Dianne Hackborn661cd522011-08-22 00:26:20 -07003638 public void performBootDexOpt() {
Dianne Hackbornc895be72013-03-11 17:48:43 -07003639 HashSet<PackageParser.Package> pkgs = null;
Dianne Hackborn661cd522011-08-22 00:26:20 -07003640 synchronized (mPackages) {
Dianne Hackbornc895be72013-03-11 17:48:43 -07003641 pkgs = mDeferredDexOpt;
3642 mDeferredDexOpt = null;
Dianne Hackborn661cd522011-08-22 00:26:20 -07003643 }
3644 if (pkgs != null) {
Dianne Hackbornc895be72013-03-11 17:48:43 -07003645 int i = 0;
3646 for (PackageParser.Package pkg : pkgs) {
Dianne Hackborn58f42a52011-10-10 13:46:34 -07003647 if (!isFirstBoot()) {
Dianne Hackbornc895be72013-03-11 17:48:43 -07003648 i++;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07003649 try {
3650 ActivityManagerNative.getDefault().showBootMessage(
3651 mContext.getResources().getString(
3652 com.android.internal.R.string.android_upgrading_apk,
Dianne Hackbornc895be72013-03-11 17:48:43 -07003653 i, pkgs.size()), true);
Dianne Hackborn58f42a52011-10-10 13:46:34 -07003654 } catch (RemoteException e) {
3655 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07003656 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07003657 PackageParser.Package p = pkg;
Dianne Hackborn661cd522011-08-22 00:26:20 -07003658 synchronized (mInstallLock) {
3659 if (!p.mDidDexOpt) {
Dianne Hackbornc895be72013-03-11 17:48:43 -07003660 performDexOptLI(p, false, false, true);
Dianne Hackborn661cd522011-08-22 00:26:20 -07003661 }
3662 }
3663 }
3664 }
3665 }
3666
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003667 public boolean performDexOpt(String packageName) {
Kenny Root461ff1f2011-08-09 09:43:03 -07003668 enforceSystemOrRoot("Only the system can request dexopt be performed");
3669
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003670 if (!mNoDexOpt) {
3671 return false;
3672 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003673
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003674 PackageParser.Package p;
3675 synchronized (mPackages) {
3676 p = mPackages.get(packageName);
3677 if (p == null || p.mDidDexOpt) {
3678 return false;
3679 }
3680 }
3681 synchronized (mInstallLock) {
Dianne Hackbornc895be72013-03-11 17:48:43 -07003682 return performDexOptLI(p, false, false, true) == DEX_OPT_PERFORMED;
3683 }
3684 }
3685
3686 private void performDexOptLibsLI(ArrayList<String> libs, boolean forceDex, boolean defer,
3687 HashSet<String> done) {
3688 for (int i=0; i<libs.size(); i++) {
3689 PackageParser.Package libPkg;
3690 String libName;
3691 synchronized (mPackages) {
3692 libName = libs.get(i);
3693 SharedLibraryEntry lib = mSharedLibraries.get(libName);
3694 if (lib != null && lib.apk != null) {
3695 libPkg = mPackages.get(lib.apk);
3696 } else {
3697 libPkg = null;
3698 }
3699 }
3700 if (libPkg != null && !done.contains(libName)) {
3701 performDexOptLI(libPkg, forceDex, defer, done);
3702 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003703 }
3704 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003705
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003706 static final int DEX_OPT_SKIPPED = 0;
3707 static final int DEX_OPT_PERFORMED = 1;
Dianne Hackborn661cd522011-08-22 00:26:20 -07003708 static final int DEX_OPT_DEFERRED = 2;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003709 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003710
Dianne Hackbornc895be72013-03-11 17:48:43 -07003711 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
3712 HashSet<String> done) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003713 boolean performed = false;
Dianne Hackbornc895be72013-03-11 17:48:43 -07003714 if (done != null) {
3715 done.add(pkg.packageName);
3716 if (pkg.usesLibraries != null) {
3717 performDexOptLibsLI(pkg.usesLibraries, forceDex, defer, done);
3718 }
3719 if (pkg.usesOptionalLibraries != null) {
3720 performDexOptLibsLI(pkg.usesOptionalLibraries, forceDex, defer, done);
3721 }
3722 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003723 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003724 String path = pkg.mScanPath;
3725 int ret = 0;
3726 try {
3727 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Dianne Hackborn661cd522011-08-22 00:26:20 -07003728 if (!forceDex && defer) {
Dianne Hackbornc895be72013-03-11 17:48:43 -07003729 if (mDeferredDexOpt == null) {
3730 mDeferredDexOpt = new HashSet<PackageParser.Package>();
3731 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07003732 mDeferredDexOpt.add(pkg);
3733 return DEX_OPT_DEFERRED;
3734 } else {
3735 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
Kenny Root6a9b2cb2012-09-17 14:02:39 -07003736 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
3737 ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg));
Dianne Hackborn661cd522011-08-22 00:26:20 -07003738 pkg.mDidDexOpt = true;
3739 performed = true;
3740 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003741 }
3742 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003743 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003744 ret = -1;
3745 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07003746 Slog.w(TAG, "IOException reading apk: " + path, e);
3747 ret = -1;
3748 } catch (dalvik.system.StaleDexCacheError e) {
3749 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
3750 ret = -1;
3751 } catch (Exception e) {
3752 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003753 ret = -1;
3754 }
3755 if (ret < 0) {
3756 //error from installer
3757 return DEX_OPT_FAILED;
3758 }
3759 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003760
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003761 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
3762 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08003763
Dianne Hackbornc895be72013-03-11 17:48:43 -07003764 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
3765 boolean inclDependencies) {
3766 HashSet<String> done;
3767 boolean performed = false;
3768 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
3769 done = new HashSet<String>();
3770 done.add(pkg.packageName);
3771 } else {
3772 done = null;
3773 }
3774 return performDexOptLI(pkg, forceDex, defer, done);
3775 }
3776
Kenny Root447106f2011-03-23 11:00:15 -07003777 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003778 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003779 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003780 + " to " + newPkg.packageName
3781 + ": old package not in system partition");
3782 return false;
3783 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003784 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003785 + " to " + newPkg.packageName
3786 + ": old package still exists");
3787 return false;
3788 }
3789 return true;
3790 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003791
Amith Yamasani0b285492011-04-14 17:35:23 -07003792 File getDataPathForUser(int userId) {
3793 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003794 }
Amith Yamasani0b285492011-04-14 17:35:23 -07003795
3796 private File getDataPathForPackage(String packageName, int userId) {
Kenny Root9c8625e2011-07-25 09:42:22 -07003797 /*
3798 * Until we fully support multiple users, return the directory we
3799 * previously would have. The PackageManagerTests will need to be
3800 * revised when this is changed back..
3801 */
3802 if (userId == 0) {
3803 return new File(mAppDataDir, packageName);
3804 } else {
3805 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
Amith Yamasani0f3f29b2011-05-09 14:17:14 -07003806 + File.separator + packageName);
Kenny Root9c8625e2011-07-25 09:42:22 -07003807 }
Amith Yamasani0b285492011-04-14 17:35:23 -07003808 }
3809
Robert Craig0f40dc92013-03-25 06:33:03 -04003810 private int createDataDirsLI(String packageName, int uid, String seinfo) {
Dave Burke383fa182012-10-23 23:12:19 -07003811 int[] users = sUserManager.getUserIds();
Robert Craig0f40dc92013-03-25 06:33:03 -04003812 int res = mInstaller.install(packageName, uid, uid, seinfo);
Dave Burke383fa182012-10-23 23:12:19 -07003813 if (res < 0) {
3814 return res;
3815 }
3816 for (int user : users) {
3817 if (user != 0) {
3818 res = mInstaller.createUserData(packageName,
Nick Kralevich15069212013-01-09 15:54:56 -08003819 UserHandle.getUid(user, uid), user);
Dave Burke383fa182012-10-23 23:12:19 -07003820 if (res < 0) {
3821 return res;
3822 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07003823 }
3824 }
Dave Burke383fa182012-10-23 23:12:19 -07003825 return res;
Dianne Hackborn4428e172012-08-24 17:43:05 -07003826 }
3827
3828 private int removeDataDirsLI(String packageName) {
3829 int[] users = sUserManager.getUserIds();
3830 int res = 0;
3831 for (int user : users) {
3832 int resInner = mInstaller.remove(packageName, user);
3833 if (resInner < 0) {
3834 res = resInner;
3835 }
3836 }
Kenny Rootddbe50d2012-09-06 13:18:37 -07003837
3838 final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
3839 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
3840 if (!nativeLibraryFile.delete()) {
3841 Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
3842 }
3843
Dianne Hackborn4428e172012-08-24 17:43:05 -07003844 return res;
3845 }
3846
Dianne Hackbornc895be72013-03-11 17:48:43 -07003847 private int addSharedLibraryLPw(final SharedLibraryEntry file, int num,
3848 PackageParser.Package changingLib) {
3849 if (file.path != null) {
3850 mTmpSharedLibraries[num] = file.path;
3851 return num+1;
3852 }
3853 PackageParser.Package p = mPackages.get(file.apk);
3854 if (changingLib != null && changingLib.packageName.equals(file.apk)) {
3855 // If we are doing this while in the middle of updating a library apk,
3856 // then we need to make sure to use that new apk for determining the
3857 // dependencies here. (We haven't yet finished committing the new apk
3858 // to the package manager state.)
3859 if (p == null || p.packageName.equals(changingLib.packageName)) {
3860 p = changingLib;
3861 }
3862 }
3863 if (p != null) {
3864 String path = p.mPath;
3865 for (int i=0; i<num; i++) {
3866 if (mTmpSharedLibraries[i].equals(path)) {
3867 return num;
3868 }
3869 }
3870 mTmpSharedLibraries[num] = p.mPath;
3871 return num+1;
3872 }
3873 return num;
3874 }
3875
3876 private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
3877 PackageParser.Package changingLib) {
3878 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
3879 if (mTmpSharedLibraries == null ||
3880 mTmpSharedLibraries.length < mSharedLibraries.size()) {
3881 mTmpSharedLibraries = new String[mSharedLibraries.size()];
3882 }
3883 int num = 0;
3884 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
3885 for (int i=0; i<N; i++) {
3886 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
3887 if (file == null) {
3888 Slog.e(TAG, "Package " + pkg.packageName
3889 + " requires unavailable shared library "
3890 + pkg.usesLibraries.get(i) + "; failing!");
3891 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
3892 return false;
3893 }
3894 num = addSharedLibraryLPw(file, num, changingLib);
3895 }
3896 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
3897 for (int i=0; i<N; i++) {
3898 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
3899 if (file == null) {
3900 Slog.w(TAG, "Package " + pkg.packageName
3901 + " desires unavailable shared library "
3902 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
3903 } else {
3904 num = addSharedLibraryLPw(file, num, changingLib);
3905 }
3906 }
3907 if (num > 0) {
3908 pkg.usesLibraryFiles = new String[num];
3909 System.arraycopy(mTmpSharedLibraries, 0,
3910 pkg.usesLibraryFiles, 0, num);
3911 } else {
3912 pkg.usesLibraryFiles = null;
3913 }
3914 }
3915 return true;
3916 }
3917
3918 private static boolean hasString(List<String> list, List<String> which) {
3919 if (list == null) {
3920 return false;
3921 }
3922 for (int i=list.size()-1; i>=0; i--) {
3923 for (int j=which.size()-1; j>=0; j--) {
3924 if (which.get(j).equals(list.get(i))) {
3925 return true;
3926 }
3927 }
3928 }
3929 return false;
3930 }
3931
3932 private void updateAllSharedLibrariesLPw() {
3933 for (PackageParser.Package pkg : mPackages.values()) {
3934 updateSharedLibrariesLPw(pkg, null);
3935 }
3936 }
3937
3938 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
3939 PackageParser.Package changingPkg) {
3940 ArrayList<PackageParser.Package> res = null;
3941 for (PackageParser.Package pkg : mPackages.values()) {
3942 if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
3943 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
3944 if (res == null) {
3945 res = new ArrayList<PackageParser.Package>();
3946 }
3947 res.add(pkg);
3948 updateSharedLibrariesLPw(pkg, changingPkg);
3949 }
3950 }
3951 return res;
3952 }
3953
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003954 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07003955 int parseFlags, int scanMode, long currentTime, UserHandle user) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003956 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08003957 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
3958 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003959 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003960 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003961 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
3962 return null;
3963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964 mScanningPath = scanFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003966 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3967 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
3968 }
3969
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003970 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003971 synchronized (mPackages) {
3972 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003973 Slog.w(TAG, "*************************************************");
3974 Slog.w(TAG, "Core android package being redefined. Skipping.");
3975 Slog.w(TAG, " file=" + mScanningPath);
3976 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3978 return null;
3979 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003981 // Set up information for our fall-back user intent resolution
3982 // activity.
3983 mPlatformPackage = pkg;
3984 pkg.mVersionCode = mSdkVersion;
3985 mAndroidApplication = pkg.applicationInfo;
3986 mResolveActivity.applicationInfo = mAndroidApplication;
3987 mResolveActivity.name = ResolverActivity.class.getName();
3988 mResolveActivity.packageName = mAndroidApplication.packageName;
Dianne Hackborn8da429e2012-09-23 12:52:19 -07003989 mResolveActivity.processName = "system:ui";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003990 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
3991 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
Joe Onorato646f46e2010-11-08 15:08:56 -08003992 mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993 mResolveActivity.exported = true;
3994 mResolveActivity.enabled = true;
3995 mResolveInfo.activityInfo = mResolveActivity;
3996 mResolveInfo.priority = 0;
3997 mResolveInfo.preferredOrder = 0;
3998 mResolveInfo.match = 0;
3999 mResolveComponentName = new ComponentName(
4000 mAndroidApplication.packageName, mResolveActivity.name);
4001 }
4002 }
4003
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004004 if (DEBUG_PACKAGE_SCANNING) {
4005 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4006 Log.d(TAG, "Scanning package " + pkg.packageName);
4007 }
4008
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004009 if (mPackages.containsKey(pkg.packageName)
4010 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004011 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 + " already installed. Skipping duplicate.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4014 return null;
4015 }
4016
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004017 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004018 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
4019 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 SharedUserSetting suid = null;
4022 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004023
Kenny Root502e9a42011-01-10 13:48:15 -08004024 if (!isSystemApp(pkg)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004025 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08004026 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004027 pkg.mRealPackage = null;
4028 pkg.mAdoptPermissions = null;
4029 }
Kenny Root502e9a42011-01-10 13:48:15 -08004030
Kenny Root447106f2011-03-23 11:00:15 -07004031 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032 synchronized (mPackages) {
Dianne Hackbornc895be72013-03-11 17:48:43 -07004033 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4034 // Check all shared libraries and map to their actual file path.
4035 // We only do this here for apps not on a system dir, because those
4036 // are the only ones that can fail an install due to this. We
4037 // will take care of the system apps by updating all of their
4038 // library paths after the scan is done.
4039 if (!updateSharedLibrariesLPw(pkg, null)) {
4040 return null;
Dianne Hackborn49237342009-08-27 20:08:01 -07004041 }
Kenny Root1683afa2011-01-07 14:27:50 -08004042 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004044 if (pkg.mSharedUserId != null) {
Kenny Root447106f2011-03-23 11:00:15 -07004045 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 pkg.applicationInfo.flags, true);
4047 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004048 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004049 + " for shared user failed");
4050 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4051 return null;
4052 }
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004053 if (DEBUG_PACKAGE_SCANNING) {
4054 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4055 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
4056 + "): packages=" + suid.packages);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004057 }
4058 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004059
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08004060 // Check if we are renaming from an original package name.
4061 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004062 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08004063 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004064 // This package may need to be renamed to a previously
4065 // installed name. Let's check on that...
Kenny Root447106f2011-03-23 11:00:15 -07004066 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08004067 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004068 // This package had originally been installed as the
4069 // original name, and we have already taken care of
4070 // transitioning to the new one. Just update the new
4071 // one to continue using the old name.
4072 realName = pkg.mRealPackage;
4073 if (!pkg.packageName.equals(renamed)) {
4074 // Callers into this function may have already taken
4075 // care of renaming the package; only do it here if
4076 // it is not already done.
4077 pkg.setPackageName(renamed);
4078 }
4079
Dianne Hackbornc1552392010-03-03 16:19:01 -08004080 } else {
4081 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
Kenny Root447106f2011-03-23 11:00:15 -07004082 if ((origPackage = mSettings.peekPackageLPr(
Dianne Hackbornc1552392010-03-03 16:19:01 -08004083 pkg.mOriginalPackages.get(i))) != null) {
4084 // We do have the package already installed under its
4085 // original name... should we use it?
Kenny Root447106f2011-03-23 11:00:15 -07004086 if (!verifyPackageUpdateLPr(origPackage, pkg)) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08004087 // New package is not compatible with original.
4088 origPackage = null;
4089 continue;
4090 } else if (origPackage.sharedUser != null) {
4091 // Make sure uid is compatible between packages.
4092 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004093 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08004094 + " to " + pkg.packageName + ": old uid "
4095 + origPackage.sharedUser.name
4096 + " differs from " + pkg.mSharedUserId);
4097 origPackage = null;
4098 continue;
4099 }
4100 } else {
4101 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
4102 + pkg.packageName + " to old name " + origPackage.name);
4103 }
4104 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08004105 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08004106 }
4107 }
4108 }
4109
4110 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004111 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08004112 + " was transferred to another, but its .apk remains");
4113 }
4114
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07004115 // Just create the setting, don't add it yet. For already existing packages
4116 // the PkgSetting exists already and doesn't have to be created.
Kenny Root447106f2011-03-23 11:00:15 -07004117 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07004118 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07004119 pkg.applicationInfo.flags, user, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004120 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004121 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004122 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4123 return null;
4124 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004125
4126 if (pkgSetting.origPackage != null) {
4127 // If we are first transitioning from an original package,
4128 // fix up the new package's name now. We need to do this after
4129 // looking up the package under its new name, so getPackageLP
4130 // can take care of fiddling things correctly.
4131 pkg.setPackageName(origPackage.name);
4132
4133 // File a report about this.
4134 String msg = "New package " + pkgSetting.realName
4135 + " renamed to replace old package " + pkgSetting.name;
4136 reportSettingsProblem(Log.WARN, msg);
4137
4138 // Make a note of it.
4139 mTransferedPackages.add(origPackage.name);
4140
4141 // No longer need to retain this.
4142 pkgSetting.origPackage = null;
4143 }
4144
4145 if (realName != null) {
4146 // Make a note of it.
4147 mTransferedPackages.add(pkg.packageName);
4148 }
4149
Kenny Rootc52d6fd2012-05-07 23:04:52 -07004150 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004151 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
4152 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004153
Robert Craig0f40dc92013-03-25 06:33:03 -04004154 if (mFoundPolicyFile) {
4155 SELinuxMMAC.assignSeinfoValue(pkg);
4156 }
4157
Amith Yamasani13593602012-03-22 16:16:17 -07004158 pkg.applicationInfo.uid = pkgSetting.appId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004160
Suchi Amalapurapuae181712010-03-30 14:01:02 -07004161 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004162 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004163 return null;
4164 }
4165 // The signature has changed, but this package is in the system
4166 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07004167 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004168 // However... if this package is part of a shared user, but it
4169 // doesn't match the signature of the shared user, let's fail.
4170 // What this means is that you can't change the signatures
4171 // associated with an overall shared user, which doesn't seem all
4172 // that unreasonable.
4173 if (pkgSetting.sharedUser != null) {
Kenny Root447106f2011-03-23 11:00:15 -07004174 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07004175 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
4176 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004177 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
4178 return null;
4179 }
4180 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004181 // File a report about this.
4182 String msg = "System package " + pkg.packageName
4183 + " signature changed; retaining data.";
4184 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004185 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004186
The Android Open Source Project10592532009-03-18 17:39:46 -07004187 // Verify that this new package doesn't have any content providers
4188 // that conflict with existing packages. Only do this if the
4189 // package isn't already installed, since we don't want to break
4190 // things that are installed.
4191 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
Kenny Root62cc6902011-02-23 16:49:21 -08004192 final int N = pkg.providers.size();
The Android Open Source Project10592532009-03-18 17:39:46 -07004193 int i;
4194 for (i=0; i<N; i++) {
4195 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08004196 if (p.info.authority != null) {
4197 String names[] = p.info.authority.split(";");
4198 for (int j = 0; j < names.length; j++) {
4199 if (mProviders.containsKey(names[j])) {
4200 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004201 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08004202 " (in package " + pkg.applicationInfo.packageName +
4203 ") is already used by "
4204 + ((other != null && other.getComponentName() != null)
4205 ? other.getComponentName().getPackageName() : "?"));
4206 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
4207 return null;
4208 }
The Android Open Source Project10592532009-03-18 17:39:46 -07004209 }
4210 }
4211 }
4212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004213
Kenny Root447106f2011-03-23 11:00:15 -07004214 if (pkg.mAdoptPermissions != null) {
4215 // This package wants to adopt ownership of permissions from
4216 // another package.
4217 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
4218 final String origName = pkg.mAdoptPermissions.get(i);
4219 final PackageSetting orig = mSettings.peekPackageLPr(origName);
4220 if (orig != null) {
4221 if (verifyPackageUpdateLPr(orig, pkg)) {
4222 Slog.i(TAG, "Adopting permissions from " + origName + " to "
4223 + pkg.packageName);
4224 mSettings.transferPermissionsLPw(origName, pkg.packageName);
4225 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004226 }
4227 }
4228 }
4229 }
Kenny Root447106f2011-03-23 11:00:15 -07004230
4231 final String pkgName = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004232
Dianne Hackborn78d6883692010-10-07 01:12:46 -07004233 final long scanFileTime = scanFile.lastModified();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004235 pkg.applicationInfo.processName = fixProcessName(
4236 pkg.applicationInfo.packageName,
4237 pkg.applicationInfo.processName,
4238 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004239
4240 File dataPath;
4241 if (mPlatformPackage == pkg) {
4242 // The system package is special.
4243 dataPath = new File (Environment.getDataDirectory(), "system");
4244 pkg.applicationInfo.dataDir = dataPath.getPath();
4245 } else {
4246 // This is a normal package, need to make its data directory.
Dave Burke383fa182012-10-23 23:12:19 -07004247 dataPath = getDataPathForPackage(pkg.packageName, 0);
Dianne Hackbornd0c5f512012-06-07 16:53:59 -07004248
Dave Burke383fa182012-10-23 23:12:19 -07004249 boolean uidError = false;
4250
4251 if (dataPath.exists()) {
4252 int currentUid = 0;
4253 try {
4254 StructStat stat = Libcore.os.stat(dataPath.getPath());
4255 currentUid = stat.st_uid;
4256 } catch (ErrnoException e) {
4257 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004259
Dave Burke383fa182012-10-23 23:12:19 -07004260 // If we have mismatched owners for the data path, we have a problem.
4261 if (currentUid != pkg.applicationInfo.uid) {
4262 boolean recovered = false;
4263 if (currentUid == 0) {
4264 // The directory somehow became owned by root. Wow.
4265 // This is probably because the system was stopped while
4266 // installd was in the middle of messing with its libs
4267 // directory. Ask installd to fix that.
4268 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
4269 pkg.applicationInfo.uid);
4270 if (ret >= 0) {
4271 recovered = true;
4272 String msg = "Package " + pkg.packageName
4273 + " unexpectedly changed to uid 0; recovered to " +
4274 + pkg.applicationInfo.uid;
4275 reportSettingsProblem(Log.WARN, msg);
4276 }
4277 }
4278 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4279 || (scanMode&SCAN_BOOTING) != 0)) {
4280 // If this is a system app, we can at least delete its
4281 // current data so the application will still work.
4282 int ret = removeDataDirsLI(pkgName);
4283 if (ret >= 0) {
4284 // TODO: Kill the processes first
4285 // Old data gone!
4286 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
4287 ? "System package " : "Third party package ";
4288 String msg = prefix + pkg.packageName
4289 + " has changed from uid: "
4290 + currentUid + " to "
4291 + pkg.applicationInfo.uid + "; old data erased";
4292 reportSettingsProblem(Log.WARN, msg);
4293 recovered = true;
4294
4295 // And now re-install the app.
Robert Craig0f40dc92013-03-25 06:33:03 -04004296 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
4297 pkg.applicationInfo.seinfo);
Dave Burke383fa182012-10-23 23:12:19 -07004298 if (ret == -1) {
4299 // Ack should not happen!
4300 msg = prefix + pkg.packageName
4301 + " could not have data directory re-created after delete.";
4302 reportSettingsProblem(Log.WARN, msg);
4303 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4304 return null;
4305 }
4306 }
4307 if (!recovered) {
4308 mHasSystemUidErrors = true;
4309 }
4310 } else if (!recovered) {
4311 // If we allow this install to proceed, we will be broken.
4312 // Abort, abort!
4313 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
4314 return null;
4315 }
4316 if (!recovered) {
4317 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
4318 + pkg.applicationInfo.uid + "/fs_"
4319 + currentUid;
4320 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
4321 String msg = "Package " + pkg.packageName
4322 + " has mismatched uid: "
4323 + currentUid + " on disk, "
4324 + pkg.applicationInfo.uid + " in settings";
4325 // writer
4326 synchronized (mPackages) {
4327 mSettings.mReadMessages.append(msg);
4328 mSettings.mReadMessages.append('\n');
4329 uidError = true;
4330 if (!pkgSetting.uidError) {
4331 reportSettingsProblem(Log.ERROR, msg);
4332 }
4333 }
4334 }
4335 }
Kenny Root4525f5b2012-10-22 14:24:23 -07004336 pkg.applicationInfo.dataDir = dataPath.getPath();
Dave Burke383fa182012-10-23 23:12:19 -07004337 } else {
4338 if (DEBUG_PACKAGE_SCANNING) {
4339 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4340 Log.v(TAG, "Want this data dir: " + dataPath);
4341 }
Nick Kralevich15069212013-01-09 15:54:56 -08004342 //invoke installer to do the actual installation
Robert Craig0f40dc92013-03-25 06:33:03 -04004343 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
4344 pkg.applicationInfo.seinfo);
Dave Burke383fa182012-10-23 23:12:19 -07004345 if (ret < 0) {
4346 // Error from installer
4347 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4348 return null;
4349 }
4350
4351 if (dataPath.exists()) {
4352 pkg.applicationInfo.dataDir = dataPath.getPath();
4353 } else {
4354 Slog.w(TAG, "Unable to create data directory: " + dataPath);
4355 pkg.applicationInfo.dataDir = null;
4356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004357 }
Kenny Root85387d72010-08-26 10:13:11 -07004358
4359 /*
Dave Burke383fa182012-10-23 23:12:19 -07004360 * Set the data dir to the default "/data/data/<package name>/lib"
4361 * if we got here without anyone telling us different (e.g., apps
4362 * stored on SD card have their native libraries stored in the ASEC
4363 * container with the APK).
4364 *
4365 * This happens during an upgrade from a package settings file that
4366 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07004367 */
Dave Burke383fa182012-10-23 23:12:19 -07004368 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
Kenny Rootbd135c12010-10-05 12:26:27 -07004369 if (pkgSetting.nativeLibraryPathString == null) {
Kenny Rootddbe50d2012-09-06 13:18:37 -07004370 setInternalAppNativeLibraryPath(pkg, pkgSetting);
Kenny Rootbd135c12010-10-05 12:26:27 -07004371 } else {
4372 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
4373 }
Kenny Root85387d72010-08-26 10:13:11 -07004374 }
Dave Burke383fa182012-10-23 23:12:19 -07004375
4376 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004377 }
4378
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004379 String path = scanFile.getPath();
4380 /* Note: We don't want to unpack the native binaries for
4381 * system applications, unless they have been updated
4382 * (the binaries are already under /system/lib).
4383 * Also, don't unpack libs for apps on the external card
4384 * since they should have their libraries in the ASEC
4385 * container already.
4386 *
4387 * In other words, we're going to unpack the binaries
4388 * only for non-system apps and system app upgrades.
4389 */
4390 if (pkg.applicationInfo.nativeLibraryDir != null) {
4391 try {
Kenny Rootddbe50d2012-09-06 13:18:37 -07004392 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
Kenny Root5832ead2011-08-02 15:47:08 -07004393 final String dataPathString = dataPath.getCanonicalPath();
Kenny Roote68d58a2010-10-18 16:08:54 -07004394
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004395 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4396 /*
4397 * Upgrading from a previous version of the OS sometimes
4398 * leaves native libraries in the /data/data/<app>/lib
4399 * directory for system apps even when they shouldn't be.
4400 * Recent changes in the JNI library search path
4401 * necessitates we remove those to match previous behavior.
4402 */
4403 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
4404 Log.i(TAG, "removed obsolete native libraries for system package "
4405 + path);
Kenny Root831baa22010-10-05 12:29:25 -07004406 }
Kenny Roota3e90792012-10-18 10:58:36 -07004407 } else {
4408 if (!isForwardLocked(pkg) && !isExternal(pkg)) {
4409 /*
4410 * Update native library dir if it starts with
4411 * /data/data
4412 */
4413 if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
4414 setInternalAppNativeLibraryPath(pkg, pkgSetting);
4415 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
4416 }
Kenny Root66269ea2011-07-12 14:14:01 -07004417
Kenny Roota3e90792012-10-18 10:58:36 -07004418 try {
4419 if (copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir) != PackageManager.INSTALL_SUCCEEDED) {
4420 Slog.e(TAG, "Unable to copy native libraries");
4421 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4422 return null;
4423 }
4424 } catch (IOException e) {
4425 Slog.e(TAG, "Unable to copy native libraries", e);
Kenny Rootddbe50d2012-09-06 13:18:37 -07004426 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4427 return null;
4428 }
Kenny Rootddbe50d2012-09-06 13:18:37 -07004429 }
4430
Dianne Hackborn40e9f292012-11-27 19:12:23 -08004431 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
Kenny Roota3e90792012-10-18 10:58:36 -07004432 final int[] userIds = sUserManager.getUserIds();
4433 synchronized (mInstallLock) {
4434 for (int userId : userIds) {
4435 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
4436 pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
4437 Slog.w(TAG, "Failed linking native library dir (user=" + userId
4438 + ")");
4439 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4440 return null;
4441 }
4442 }
Nick Kralevich7de350a2012-09-07 15:48:11 -07004443 }
Kenny Root831baa22010-10-05 12:29:25 -07004444 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004445 } catch (IOException ioe) {
Kenny Rootddbe50d2012-09-06 13:18:37 -07004446 Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004447 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004448 }
4449 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004450
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004451 if ((scanMode&SCAN_NO_DEX) == 0) {
Dianne Hackbornc895be72013-03-11 17:48:43 -07004452 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
Dianne Hackborn661cd522011-08-22 00:26:20 -07004453 == DEX_OPT_FAILED) {
Jeff Brown5d6d90f2011-07-11 13:04:53 -07004454 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
4455 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004456 }
4457 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004459 if (mFactoryTest && pkg.requestedPermissions.contains(
4460 android.Manifest.permission.FACTORY_TEST)) {
4461 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
4462 }
4463
Dianne Hackbornc895be72013-03-11 17:48:43 -07004464 ArrayList<PackageParser.Package> clientLibPkgs = null;
4465
4466 // writer
4467 synchronized (mPackages) {
4468 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4469 // Only system apps can add new shared libraries.
4470 if (pkg.libraryNames != null) {
4471 for (int i=0; i<pkg.libraryNames.size(); i++) {
4472 String name = pkg.libraryNames.get(i);
4473 boolean allowed = false;
4474 if (isUpdatedSystemApp(pkg)) {
4475 // New library entries can only be added through the
4476 // system image. This is important to get rid of a lot
4477 // of nasty edge cases: for example if we allowed a non-
4478 // system update of the app to add a library, then uninstalling
4479 // the update would make the library go away, and assumptions
4480 // we made such as through app install filtering would now
4481 // have allowed apps on the device which aren't compatible
4482 // with it. Better to just have the restriction here, be
4483 // conservative, and create many fewer cases that can negatively
4484 // impact the user experience.
4485 final PackageSetting sysPs = mSettings
4486 .getDisabledSystemPkgLPr(pkg.packageName);
4487 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
4488 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
4489 if (name.equals(sysPs.pkg.libraryNames.get(j))) {
4490 allowed = true;
4491 allowed = true;
4492 break;
4493 }
4494 }
4495 }
4496 } else {
4497 allowed = true;
4498 }
4499 if (allowed) {
4500 if (!mSharedLibraries.containsKey(name)) {
4501 mSharedLibraries.put(name, new SharedLibraryEntry(null,
4502 pkg.packageName));
4503 } else if (!name.equals(pkg.packageName)) {
4504 Slog.w(TAG, "Package " + pkg.packageName + " library "
4505 + name + " already exists; skipping");
4506 }
4507 } else {
4508 Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
4509 + name + " that is not declared on system image; skipping");
4510 }
4511 }
4512 if ((scanMode&SCAN_BOOTING) == 0) {
4513 // If we are not booting, we need to update any applications
4514 // that are clients of our shared library. If we are booting,
4515 // this will all be done once the scan is complete.
4516 clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
4517 }
4518 }
4519 }
4520 }
4521
4522 // We also need to dexopt any apps that are dependent on this library. Note that
4523 // if these fail, we should abort the install since installing the library will
4524 // result in some apps being broken.
4525 if (clientLibPkgs != null) {
4526 if ((scanMode&SCAN_NO_DEX) == 0) {
4527 for (int i=0; i<clientLibPkgs.size(); i++) {
4528 PackageParser.Package clientPkg = clientLibPkgs.get(i);
4529 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
4530 == DEX_OPT_FAILED) {
4531 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
4532 return null;
4533 }
4534 }
4535 }
4536 }
4537
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004538 // Request the ActivityManager to kill the process(only for existing packages)
4539 // so that we do not end up in a confused state while the user is still using the older
4540 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004541 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004542 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004543 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004544 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004545
Dianne Hackbornc895be72013-03-11 17:48:43 -07004546 // Also need to kill any apps that are dependent on the library.
4547 if (clientLibPkgs != null) {
4548 for (int i=0; i<clientLibPkgs.size(); i++) {
4549 PackageParser.Package clientPkg = clientLibPkgs.get(i);
4550 killApplication(clientPkg.applicationInfo.packageName,
4551 clientPkg.applicationInfo.uid);
4552 }
4553 }
4554
Kenny Root447106f2011-03-23 11:00:15 -07004555 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004556 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004557 // We don't expect installation to fail beyond this point,
4558 if ((scanMode&SCAN_MONITOR) != 0) {
4559 mAppDirs.put(pkg.mPath, pkg);
4560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004561 // Add the new setting to mSettings
Kenny Root447106f2011-03-23 11:00:15 -07004562 mSettings.insertPackageSettingLPw(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004563 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07004564 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004565 // Make sure we don't accidentally delete its data.
Jeff Sharkey752cd922012-09-23 16:25:12 -07004566 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
4567 while (iter.hasNext()) {
4568 PackageCleanItem item = iter.next();
4569 if (pkgName.equals(item.packageName)) {
4570 iter.remove();
4571 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07004572 }
Jeff Sharkey752cd922012-09-23 16:25:12 -07004573
Dianne Hackborn78d6883692010-10-07 01:12:46 -07004574 // Take care of first install / last update times.
4575 if (currentTime != 0) {
4576 if (pkgSetting.firstInstallTime == 0) {
4577 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
4578 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
4579 pkgSetting.lastUpdateTime = currentTime;
4580 }
4581 } else if (pkgSetting.firstInstallTime == 0) {
4582 // We need *something*. Take time time stamp of the file.
4583 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
4584 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
4585 if (scanFileTime != pkgSetting.timeStamp) {
4586 // A package on the system image has changed; consider this
4587 // to be an update.
4588 pkgSetting.lastUpdateTime = scanFileTime;
4589 }
4590 }
4591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004592 int N = pkg.providers.size();
4593 StringBuilder r = null;
4594 int i;
4595 for (i=0; i<N; i++) {
4596 PackageParser.Provider p = pkg.providers.get(i);
4597 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
4598 p.info.processName, pkg.applicationInfo.uid);
4599 mProvidersByComponent.put(new ComponentName(p.info.packageName,
4600 p.info.name), p);
4601 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08004602 if (p.info.authority != null) {
4603 String names[] = p.info.authority.split(";");
4604 p.info.authority = null;
4605 for (int j = 0; j < names.length; j++) {
4606 if (j == 1 && p.syncable) {
4607 // We only want the first authority for a provider to possibly be
4608 // syncable, so if we already added this provider using a different
4609 // authority clear the syncable flag. We copy the provider before
4610 // changing it because the mProviders object contains a reference
4611 // to a provider that we don't want to change.
4612 // Only do this for the second authority since the resulting provider
4613 // object can be the same for all future authorities for this provider.
4614 p = new PackageParser.Provider(p);
4615 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004616 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08004617 if (!mProviders.containsKey(names[j])) {
4618 mProviders.put(names[j], p);
4619 if (p.info.authority == null) {
4620 p.info.authority = names[j];
4621 } else {
4622 p.info.authority = p.info.authority + ";" + names[j];
4623 }
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004624 if (DEBUG_PACKAGE_SCANNING) {
4625 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4626 Log.d(TAG, "Registered content provider: " + names[j]
4627 + ", className = " + p.info.name + ", isSyncable = "
4628 + p.info.isSyncable);
4629 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08004630 } else {
4631 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004632 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08004633 " (in package " + pkg.applicationInfo.packageName +
4634 "): name already used by "
4635 + ((other != null && other.getComponentName() != null)
4636 ? other.getComponentName().getPackageName() : "?"));
4637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004638 }
4639 }
4640 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4641 if (r == null) {
4642 r = new StringBuilder(256);
4643 } else {
4644 r.append(' ');
4645 }
4646 r.append(p.info.name);
4647 }
4648 }
4649 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004650 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004651 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004653 N = pkg.services.size();
4654 r = null;
4655 for (i=0; i<N; i++) {
4656 PackageParser.Service s = pkg.services.get(i);
4657 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
4658 s.info.processName, pkg.applicationInfo.uid);
4659 mServices.addService(s);
4660 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4661 if (r == null) {
4662 r = new StringBuilder(256);
4663 } else {
4664 r.append(' ');
4665 }
4666 r.append(s.info.name);
4667 }
4668 }
4669 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004670 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004671 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004673 N = pkg.receivers.size();
4674 r = null;
4675 for (i=0; i<N; i++) {
4676 PackageParser.Activity a = pkg.receivers.get(i);
4677 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
4678 a.info.processName, pkg.applicationInfo.uid);
4679 mReceivers.addActivity(a, "receiver");
4680 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4681 if (r == null) {
4682 r = new StringBuilder(256);
4683 } else {
4684 r.append(' ');
4685 }
4686 r.append(a.info.name);
4687 }
4688 }
4689 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004690 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004691 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004693 N = pkg.activities.size();
4694 r = null;
4695 for (i=0; i<N; i++) {
4696 PackageParser.Activity a = pkg.activities.get(i);
4697 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
4698 a.info.processName, pkg.applicationInfo.uid);
4699 mActivities.addActivity(a, "activity");
4700 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4701 if (r == null) {
4702 r = new StringBuilder(256);
4703 } else {
4704 r.append(' ');
4705 }
4706 r.append(a.info.name);
4707 }
4708 }
4709 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004710 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004711 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004713 N = pkg.permissionGroups.size();
4714 r = null;
4715 for (i=0; i<N; i++) {
4716 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
4717 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
4718 if (cur == null) {
4719 mPermissionGroups.put(pg.info.name, pg);
4720 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4721 if (r == null) {
4722 r = new StringBuilder(256);
4723 } else {
4724 r.append(' ');
4725 }
4726 r.append(pg.info.name);
4727 }
4728 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004729 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004730 + pg.info.packageName + " ignored: original from "
4731 + cur.info.packageName);
4732 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4733 if (r == null) {
4734 r = new StringBuilder(256);
4735 } else {
4736 r.append(' ');
4737 }
4738 r.append("DUP:");
4739 r.append(pg.info.name);
4740 }
4741 }
4742 }
4743 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004744 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004745 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004747 N = pkg.permissions.size();
4748 r = null;
4749 for (i=0; i<N; i++) {
4750 PackageParser.Permission p = pkg.permissions.get(i);
4751 HashMap<String, BasePermission> permissionMap =
4752 p.tree ? mSettings.mPermissionTrees
4753 : mSettings.mPermissions;
4754 p.group = mPermissionGroups.get(p.info.group);
4755 if (p.info.group == null || p.group != null) {
4756 BasePermission bp = permissionMap.get(p.info.name);
4757 if (bp == null) {
4758 bp = new BasePermission(p.info.name, p.info.packageName,
4759 BasePermission.TYPE_NORMAL);
4760 permissionMap.put(p.info.name, bp);
4761 }
4762 if (bp.perm == null) {
4763 if (bp.sourcePackage == null
4764 || bp.sourcePackage.equals(p.info.packageName)) {
4765 BasePermission tree = findPermissionTreeLP(p.info.name);
4766 if (tree == null
4767 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004768 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004769 bp.perm = p;
4770 bp.uid = pkg.applicationInfo.uid;
4771 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4772 if (r == null) {
4773 r = new StringBuilder(256);
4774 } else {
4775 r.append(' ');
4776 }
4777 r.append(p.info.name);
4778 }
4779 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004780 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004781 + p.info.packageName + " ignored: base tree "
4782 + tree.name + " is from package "
4783 + tree.sourcePackage);
4784 }
4785 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004786 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004787 + p.info.packageName + " ignored: original from "
4788 + bp.sourcePackage);
4789 }
4790 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4791 if (r == null) {
4792 r = new StringBuilder(256);
4793 } else {
4794 r.append(' ');
4795 }
4796 r.append("DUP:");
4797 r.append(p.info.name);
4798 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004799 if (bp.perm == p) {
4800 bp.protectionLevel = p.info.protectionLevel;
4801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004802 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004803 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004804 + p.info.packageName + " ignored: no group "
4805 + p.group);
4806 }
4807 }
4808 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004809 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004810 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004812 N = pkg.instrumentation.size();
4813 r = null;
4814 for (i=0; i<N; i++) {
4815 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
4816 a.info.packageName = pkg.applicationInfo.packageName;
4817 a.info.sourceDir = pkg.applicationInfo.sourceDir;
4818 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
4819 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07004820 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004821 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004822 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4823 if (r == null) {
4824 r = new StringBuilder(256);
4825 } else {
4826 r.append(' ');
4827 }
4828 r.append(a.info.name);
4829 }
4830 }
4831 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004832 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004833 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004834
Dianne Hackborn854060af2009-07-09 18:14:31 -07004835 if (pkg.protectedBroadcasts != null) {
4836 N = pkg.protectedBroadcasts.size();
4837 for (i=0; i<N; i++) {
4838 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
4839 }
4840 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004842 pkgSetting.setTimeStamp(scanFileTime);
4843 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004845 return pkg;
4846 }
4847
Kenny Rootddbe50d2012-09-06 13:18:37 -07004848 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
4849 PackageSetting pkgSetting) {
4850 final String apkLibPath = getApkName(pkgSetting.codePathString);
4851 final String nativeLibraryPath = new File(mAppLibInstallDir, apkLibPath).getPath();
4852 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
4853 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
4854 }
4855
4856 private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir)
4857 throws IOException {
4858 if (!nativeLibraryDir.isDirectory()) {
4859 nativeLibraryDir.delete();
Kenny Root9bbd70a2012-09-10 11:13:36 -07004860
Kenny Rootddbe50d2012-09-06 13:18:37 -07004861 if (!nativeLibraryDir.mkdir()) {
4862 throw new IOException("Cannot create " + nativeLibraryDir.getPath());
4863 }
Kenny Root9bbd70a2012-09-10 11:13:36 -07004864
Kenny Rootddbe50d2012-09-06 13:18:37 -07004865 try {
4866 Libcore.os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH
4867 | S_IXOTH);
4868 } catch (ErrnoException e) {
4869 throw new IOException("Cannot chmod native library directory "
4870 + nativeLibraryDir.getPath(), e);
4871 }
Kenny Root9bbd70a2012-09-10 11:13:36 -07004872 } else if (!SELinux.restorecon(nativeLibraryDir)) {
4873 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
Kenny Rootddbe50d2012-09-06 13:18:37 -07004874 }
4875
4876 /*
4877 * If this is an internal application or our nativeLibraryPath points to
4878 * the app-lib directory, unpack the libraries if necessary.
4879 */
4880 return NativeLibraryHelper.copyNativeBinariesIfNeededLI(scanFile, nativeLibraryDir);
4881 }
4882
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004883 private void killApplication(String pkgName, int appId) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004884 // Request the ActivityManager to kill the process(only for existing packages)
4885 // so that we do not end up in a confused state while the user is still using the older
4886 // version of the application while the new one gets installed.
4887 IActivityManager am = ActivityManagerNative.getDefault();
4888 if (am != null) {
4889 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004890 am.killApplicationWithAppId(pkgName, appId);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004891 } catch (RemoteException e) {
4892 }
4893 }
4894 }
4895
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004896 void removePackageLI(PackageSetting ps, boolean chatty) {
4897 if (DEBUG_INSTALL) {
4898 if (chatty)
4899 Log.d(TAG, "Removing package " + ps.name);
4900 }
4901
4902 // writer
4903 synchronized (mPackages) {
4904 mPackages.remove(ps.name);
4905 if (ps.codePathString != null) {
4906 mAppDirs.remove(ps.codePathString);
4907 }
4908
4909 final PackageParser.Package pkg = ps.pkg;
4910 if (pkg != null) {
4911 cleanPackageDataStructuresLILPw(pkg, chatty);
4912 }
4913 }
4914 }
4915
4916 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004917 if (DEBUG_INSTALL) {
4918 if (chatty)
4919 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
4920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004921
Kenny Root447106f2011-03-23 11:00:15 -07004922 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004923 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004924 mPackages.remove(pkg.applicationInfo.packageName);
4925 if (pkg.mPath != null) {
4926 mAppDirs.remove(pkg.mPath);
4927 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004928 cleanPackageDataStructuresLILPw(pkg, chatty);
4929 }
4930 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004931
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004932 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
4933 int N = pkg.providers.size();
4934 StringBuilder r = null;
4935 int i;
4936 for (i=0; i<N; i++) {
4937 PackageParser.Provider p = pkg.providers.get(i);
4938 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
4939 p.info.name));
4940 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004941
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004942 /* There was another ContentProvider with this authority when
4943 * this app was installed so this authority is null,
4944 * Ignore it as we don't have to unregister the provider.
4945 */
4946 continue;
4947 }
4948 String names[] = p.info.authority.split(";");
4949 for (int j = 0; j < names.length; j++) {
4950 if (mProviders.get(names[j]) == p) {
4951 mProviders.remove(names[j]);
4952 if (DEBUG_REMOVE) {
4953 if (chatty)
4954 Log.d(TAG, "Unregistered content provider: " + names[j]
4955 + ", className = " + p.info.name + ", isSyncable = "
4956 + p.info.isSyncable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004957 }
4958 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004959 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07004960 if (DEBUG_REMOVE && chatty) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004961 if (r == null) {
4962 r = new StringBuilder(256);
4963 } else {
4964 r.append(' ');
4965 }
4966 r.append(p.info.name);
4967 }
4968 }
4969 if (r != null) {
4970 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r);
4971 }
4972
4973 N = pkg.services.size();
4974 r = null;
4975 for (i=0; i<N; i++) {
4976 PackageParser.Service s = pkg.services.get(i);
4977 mServices.removeService(s);
4978 if (chatty) {
4979 if (r == null) {
4980 r = new StringBuilder(256);
4981 } else {
4982 r.append(' ');
4983 }
4984 r.append(s.info.name);
4985 }
4986 }
4987 if (r != null) {
4988 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r);
4989 }
4990
4991 N = pkg.receivers.size();
4992 r = null;
4993 for (i=0; i<N; i++) {
4994 PackageParser.Activity a = pkg.receivers.get(i);
4995 mReceivers.removeActivity(a, "receiver");
Dianne Hackbornc895be72013-03-11 17:48:43 -07004996 if (DEBUG_REMOVE && chatty) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004997 if (r == null) {
4998 r = new StringBuilder(256);
4999 } else {
5000 r.append(' ');
5001 }
5002 r.append(a.info.name);
5003 }
5004 }
5005 if (r != null) {
5006 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r);
5007 }
5008
5009 N = pkg.activities.size();
5010 r = null;
5011 for (i=0; i<N; i++) {
5012 PackageParser.Activity a = pkg.activities.get(i);
5013 mActivities.removeActivity(a, "activity");
Dianne Hackbornc895be72013-03-11 17:48:43 -07005014 if (DEBUG_REMOVE && chatty) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07005015 if (r == null) {
5016 r = new StringBuilder(256);
5017 } else {
5018 r.append(' ');
5019 }
5020 r.append(a.info.name);
5021 }
5022 }
5023 if (r != null) {
5024 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r);
5025 }
5026
5027 N = pkg.permissions.size();
5028 r = null;
5029 for (i=0; i<N; i++) {
5030 PackageParser.Permission p = pkg.permissions.get(i);
5031 BasePermission bp = mSettings.mPermissions.get(p.info.name);
5032 if (bp == null) {
5033 bp = mSettings.mPermissionTrees.get(p.info.name);
5034 }
5035 if (bp != null && bp.perm == p) {
5036 bp.perm = null;
Dianne Hackbornc895be72013-03-11 17:48:43 -07005037 if (DEBUG_REMOVE && chatty) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005038 if (r == null) {
5039 r = new StringBuilder(256);
5040 } else {
5041 r.append(' ');
5042 }
5043 r.append(p.info.name);
5044 }
5045 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07005046 }
5047 if (r != null) {
5048 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
5049 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005050
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07005051 N = pkg.instrumentation.size();
5052 r = null;
5053 for (i=0; i<N; i++) {
5054 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5055 mInstrumentation.remove(a.getComponentName());
Dianne Hackbornc895be72013-03-11 17:48:43 -07005056 if (DEBUG_REMOVE && chatty) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07005057 if (r == null) {
5058 r = new StringBuilder(256);
5059 } else {
5060 r.append(' ');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005061 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07005062 r.append(a.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005063 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07005064 }
5065 if (r != null) {
5066 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005067 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07005068
5069 r = null;
5070 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5071 // Only system apps can hold shared libraries.
5072 if (pkg.libraryNames != null) {
5073 for (i=0; i<pkg.libraryNames.size(); i++) {
5074 String name = pkg.libraryNames.get(i);
5075 SharedLibraryEntry cur = mSharedLibraries.get(name);
5076 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
5077 mSharedLibraries.remove(name);
5078 if (DEBUG_REMOVE && chatty) {
5079 if (r == null) {
5080 r = new StringBuilder(256);
5081 } else {
5082 r.append(' ');
5083 }
5084 r.append(name);
5085 }
5086 }
5087 }
5088 }
5089 }
5090 if (r != null) {
5091 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r);
5092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005093 }
5094
5095 private static final boolean isPackageFilename(String name) {
5096 return name != null && name.endsWith(".apk");
5097 }
5098
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005099 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
5100 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
5101 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
5102 return true;
5103 }
5104 }
5105 return false;
5106 }
Dianne Hackborne639da72012-02-21 15:11:13 -08005107
5108 static final int UPDATE_PERMISSIONS_ALL = 1<<0;
5109 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
5110 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
5111
Kenny Root447106f2011-03-23 11:00:15 -07005112 private void updatePermissionsLPw(String changingPkg,
Dianne Hackborne639da72012-02-21 15:11:13 -08005113 PackageParser.Package pkgInfo, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005114 // Make sure there are no dangling permission trees.
Kenny Root447106f2011-03-23 11:00:15 -07005115 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005116 while (it.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07005117 final BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005118 if (bp.packageSetting == null) {
5119 // We may not yet have parsed the package, so just see if
5120 // we still know about its settings.
5121 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
5122 }
5123 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005124 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005125 + " from package " + bp.sourcePackage);
5126 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005127 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
5128 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
5129 Slog.i(TAG, "Removing old permission tree: " + bp.name
5130 + " from package " + bp.sourcePackage);
Dianne Hackborne639da72012-02-21 15:11:13 -08005131 flags |= UPDATE_PERMISSIONS_ALL;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005132 it.remove();
5133 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005134 }
5135 }
5136
5137 // Make sure all dynamic permissions have been assigned to a package,
5138 // and make sure there are no dangling permissions.
5139 it = mSettings.mPermissions.values().iterator();
5140 while (it.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07005141 final BasePermission bp = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005142 if (bp.type == BasePermission.TYPE_DYNAMIC) {
5143 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
5144 + bp.name + " pkg=" + bp.sourcePackage
5145 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005146 if (bp.packageSetting == null && bp.pendingInfo != null) {
Kenny Root447106f2011-03-23 11:00:15 -07005147 final BasePermission tree = findPermissionTreeLP(bp.name);
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07005148 if (tree != null && tree.perm != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005149 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005150 bp.perm = new PackageParser.Permission(tree.perm.owner,
5151 new PermissionInfo(bp.pendingInfo));
5152 bp.perm.info.packageName = tree.perm.info.packageName;
5153 bp.perm.info.name = bp.name;
5154 bp.uid = tree.uid;
5155 }
5156 }
5157 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005158 if (bp.packageSetting == null) {
5159 // We may not yet have parsed the package, so just see if
5160 // we still know about its settings.
5161 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
5162 }
5163 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005164 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005165 + " from package " + bp.sourcePackage);
5166 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005167 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
5168 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
5169 Slog.i(TAG, "Removing old permission: " + bp.name
5170 + " from package " + bp.sourcePackage);
Dianne Hackborne639da72012-02-21 15:11:13 -08005171 flags |= UPDATE_PERMISSIONS_ALL;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005172 it.remove();
5173 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005174 }
5175 }
5176
5177 // Now update the permissions for all packages, in particular
5178 // replace the granted permissions of the system packages.
Dianne Hackborne639da72012-02-21 15:11:13 -08005179 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005180 for (PackageParser.Package pkg : mPackages.values()) {
5181 if (pkg != pkgInfo) {
Dianne Hackborne639da72012-02-21 15:11:13 -08005182 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005183 }
5184 }
5185 }
5186
5187 if (pkgInfo != null) {
Dianne Hackborne639da72012-02-21 15:11:13 -08005188 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005189 }
5190 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005191
Kenny Root447106f2011-03-23 11:00:15 -07005192 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
5193 final PackageSetting ps = (PackageSetting) pkg.mExtras;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005194 if (ps == null) {
5195 return;
5196 }
5197 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackborne639da72012-02-21 15:11:13 -08005198 HashSet<String> origPermissions = gp.grantedPermissions;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005199 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005201 if (replace) {
5202 ps.permissionsFixed = false;
5203 if (gp == ps) {
Dianne Hackborne639da72012-02-21 15:11:13 -08005204 origPermissions = new HashSet<String>(gp.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005205 gp.grantedPermissions.clear();
5206 gp.gids = mGlobalGids;
5207 }
5208 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005210 if (gp.gids == null) {
5211 gp.gids = mGlobalGids;
5212 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005214 final int N = pkg.requestedPermissions.size();
5215 for (int i=0; i<N; i++) {
Kenny Root447106f2011-03-23 11:00:15 -07005216 final String name = pkg.requestedPermissions.get(i);
Nick Kralevich1cd6c6e2013-03-18 12:56:33 -07005217 final boolean required = pkg.requestedPermissionsRequired.get(i);
Kenny Root447106f2011-03-23 11:00:15 -07005218 final BasePermission bp = mSettings.mPermissions.get(name);
Kenny Root4dfe6ff2011-02-23 17:00:43 -08005219 if (DEBUG_INSTALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005220 if (gp != ps) {
Kenny Root4dfe6ff2011-02-23 17:00:43 -08005221 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005222 }
5223 }
Nick Kralevichdaae5412013-04-01 13:12:26 -07005224
5225 if (bp == null || bp.packageSetting == null) {
5226 Slog.w(TAG, "Unknown permission " + name
5227 + " in package " + pkg.packageName);
5228 continue;
5229 }
5230
5231 final String perm = bp.name;
5232 boolean allowed;
5233 boolean allowedSig = false;
5234 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
5235 if (level == PermissionInfo.PROTECTION_NORMAL
5236 || level == PermissionInfo.PROTECTION_DANGEROUS) {
Nick Kralevich60792852013-04-03 14:12:24 -07005237 // We grant a normal or dangerous permission if any of the following
5238 // are true:
5239 // 1) The permission is required
5240 // 2) The permission is optional, but was granted in the past
5241 // 3) The permission is optional, but was requested by an
5242 // app in /system (not /data)
5243 //
5244 // Otherwise, reject the permission.
5245 allowed = (required || origPermissions.contains(perm)
5246 || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
Nick Kralevichdaae5412013-04-01 13:12:26 -07005247 } else if (bp.packageSetting == null) {
5248 // This permission is invalid; skip it.
5249 allowed = false;
5250 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
Nick Kralevich94b8c932013-04-02 09:27:27 -07005251 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005252 if (allowed) {
Nick Kralevichdaae5412013-04-01 13:12:26 -07005253 allowedSig = true;
5254 }
5255 } else {
5256 allowed = false;
5257 }
5258 if (DEBUG_INSTALL) {
5259 if (gp != ps) {
5260 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
5261 }
5262 }
5263 if (allowed) {
Nick Kralevich60792852013-04-03 14:12:24 -07005264 if (!isSystemApp(ps) && ps.permissionsFixed) {
Nick Kralevichdaae5412013-04-01 13:12:26 -07005265 // If this is an existing, non-system package, then
5266 // we can't add any new permissions to it.
5267 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
Nick Kralevichdaae5412013-04-01 13:12:26 -07005268 // Except... if this is a permission that was added
5269 // to the platform (note: need to only do this when
5270 // updating the platform).
Nick Kralevich3337dbf2013-04-01 13:27:30 -07005271 allowed = isNewPlatformPermissionForPackage(perm, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005272 }
Nick Kralevichdaae5412013-04-01 13:12:26 -07005273 }
5274 if (allowed) {
5275 if (!gp.grantedPermissions.contains(perm)) {
5276 changedPermission = true;
5277 gp.grantedPermissions.add(perm);
5278 gp.gids = appendInts(gp.gids, bp.gids);
5279 } else if (!ps.haveGids) {
5280 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005281 }
5282 } else {
Nick Kralevichdaae5412013-04-01 13:12:26 -07005283 Slog.w(TAG, "Not granting permission " + perm
5284 + " to package " + pkg.packageName
5285 + " because it was previously installed without");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005286 }
5287 } else {
Nick Kralevichdaae5412013-04-01 13:12:26 -07005288 if (gp.grantedPermissions.remove(perm)) {
5289 changedPermission = true;
5290 gp.gids = removeInts(gp.gids, bp.gids);
5291 Slog.i(TAG, "Un-granting permission " + perm
5292 + " from package " + pkg.packageName
5293 + " (protectionLevel=" + bp.protectionLevel
5294 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
5295 + ")");
5296 } else {
5297 Slog.w(TAG, "Not granting permission " + perm
5298 + " to package " + pkg.packageName
5299 + " (protectionLevel=" + bp.protectionLevel
5300 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
5301 + ")");
5302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005303 }
5304 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005305
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005306 if ((changedPermission || replace) && !ps.permissionsFixed &&
Nick Kralevich60792852013-04-03 14:12:24 -07005307 !isSystemApp(ps) || isUpdatedSystemApp(ps)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005308 // This is the first that we have heard about this package, so the
5309 // permissions we have now selected are fixed until explicitly
5310 // changed.
5311 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005312 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07005313 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005314 }
Nick Kralevich35bee33d2013-04-01 13:08:00 -07005315
Nick Kralevich3337dbf2013-04-01 13:27:30 -07005316 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
5317 boolean allowed = false;
5318 final int NP = PackageParser.NEW_PERMISSIONS.length;
5319 for (int ip=0; ip<NP; ip++) {
5320 final PackageParser.NewPermissionInfo npi
5321 = PackageParser.NEW_PERMISSIONS[ip];
5322 if (npi.name.equals(perm)
5323 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
5324 allowed = true;
5325 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
5326 + pkg.packageName);
5327 break;
5328 }
5329 }
5330 return allowed;
5331 }
5332
Nick Kralevich94b8c932013-04-02 09:27:27 -07005333 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
Nick Kralevich35bee33d2013-04-01 13:08:00 -07005334 BasePermission bp, HashSet<String> origPermissions) {
5335 boolean allowed;
5336 allowed = (compareSignatures(
5337 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
5338 == PackageManager.SIGNATURE_MATCH)
5339 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
5340 == PackageManager.SIGNATURE_MATCH);
5341 if (!allowed && (bp.protectionLevel
5342 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
5343 if (isSystemApp(pkg)) {
5344 // For updated system applications, a system permission
5345 // is granted only if it had been defined by the original application.
5346 if (isUpdatedSystemApp(pkg)) {
5347 final PackageSetting sysPs = mSettings
5348 .getDisabledSystemPkgLPr(pkg.packageName);
5349 final GrantedPermissions origGp = sysPs.sharedUser != null
5350 ? sysPs.sharedUser : sysPs;
5351 if (origGp.grantedPermissions.contains(perm)) {
5352 allowed = true;
5353 } else {
5354 // The system apk may have been updated with an older
5355 // version of the one on the data partition, but which
5356 // granted a new system permission that it didn't have
5357 // before. In this case we do want to allow the app to
5358 // now get the new permission, because it is allowed by
5359 // the system image.
5360 allowed = false;
5361 if (sysPs.pkg != null) {
5362 for (int j=0;
5363 j<sysPs.pkg.requestedPermissions.size(); j++) {
5364 if (perm.equals(
5365 sysPs.pkg.requestedPermissions.get(j))) {
5366 allowed = true;
5367 break;
5368 }
5369 }
5370 }
5371 }
5372 } else {
5373 allowed = true;
5374 }
5375 }
5376 }
5377 if (!allowed && (bp.protectionLevel
5378 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
5379 // For development permissions, a development permission
5380 // is granted only if it was already granted.
5381 allowed = origPermissions.contains(perm);
5382 }
5383 return allowed;
5384 }
5385
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08005386 final class ActivityIntentResolver
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005387 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Kenny Root60f7ad82011-03-22 12:49:06 -07005388 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005389 boolean defaultOnly, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005390 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005391 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005392 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005393 }
5394
Amith Yamasani483f3b02012-03-13 16:08:00 -07005395 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
5396 int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005397 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005398 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02005399 return super.queryIntent(intent, resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005400 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005401 }
5402
Kenny Root60f7ad82011-03-22 12:49:06 -07005403 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005404 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005405 if (!sUserManager.exists(userId)) return null;
Mihai Predaeae850c2009-05-13 10:13:48 +02005406 if (packageActivities == null) {
5407 return null;
5408 }
5409 mFlags = flags;
5410 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
Kenny Root62cc6902011-02-23 16:49:21 -08005411 final int N = packageActivities.size();
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07005412 ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
5413 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02005414
5415 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02005416 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02005417 intentFilters = packageActivities.get(i).intents;
5418 if (intentFilters != null && intentFilters.size() > 0) {
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07005419 PackageParser.ActivityIntentInfo[] array =
5420 new PackageParser.ActivityIntentInfo[intentFilters.size()];
5421 intentFilters.toArray(array);
5422 listCut.add(array);
Mihai Predac3320db2009-05-18 20:15:32 +02005423 }
Mihai Predaeae850c2009-05-13 10:13:48 +02005424 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07005425 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
Mihai Predaeae850c2009-05-13 10:13:48 +02005426 }
5427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005428 public final void addActivity(PackageParser.Activity a, String type) {
Kenny Root502e9a42011-01-10 13:48:15 -08005429 final boolean systemApp = isSystemApp(a.info.applicationInfo);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005430 mActivities.put(a.getComponentName(), a);
Kenny Root9718cf52011-02-23 16:45:26 -08005431 if (DEBUG_SHOW_INFO)
5432 Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005433 TAG, " " + type + " " +
5434 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
Kenny Root9718cf52011-02-23 16:45:26 -08005435 if (DEBUG_SHOW_INFO)
5436 Log.v(TAG, " Class=" + a.info.name);
Kenny Root62cc6902011-02-23 16:49:21 -08005437 final int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02005438 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005439 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
Kenny Root502e9a42011-01-10 13:48:15 -08005440 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
5441 intent.setPriority(0);
5442 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
5443 + a.className + " with priority > 0, forcing to 0");
5444 }
Kenny Root9718cf52011-02-23 16:45:26 -08005445 if (DEBUG_SHOW_INFO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005446 Log.v(TAG, " IntentFilter:");
5447 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
5448 }
5449 if (!intent.debugCheck()) {
5450 Log.w(TAG, "==> For Activity " + a.info.name);
5451 }
5452 addFilter(intent);
5453 }
5454 }
5455
5456 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005457 mActivities.remove(a.getComponentName());
Kenny Root9718cf52011-02-23 16:45:26 -08005458 if (DEBUG_SHOW_INFO) {
5459 Log.v(TAG, " " + type + " "
5460 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
5461 : a.info.name) + ":");
5462 Log.v(TAG, " Class=" + a.info.name);
5463 }
5464 final int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02005465 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005466 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
Kenny Root9718cf52011-02-23 16:45:26 -08005467 if (DEBUG_SHOW_INFO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005468 Log.v(TAG, " IntentFilter:");
5469 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
5470 }
5471 removeFilter(intent);
5472 }
5473 }
5474
5475 @Override
5476 protected boolean allowFilterResult(
5477 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
5478 ActivityInfo filterAi = filter.activity.info;
5479 for (int i=dest.size()-1; i>=0; i--) {
5480 ActivityInfo destAi = dest.get(i).activityInfo;
5481 if (destAi.name == filterAi.name
5482 && destAi.packageName == filterAi.packageName) {
5483 return false;
5484 }
5485 }
5486 return true;
5487 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005489 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07005490 protected ActivityIntentInfo[] newArray(int size) {
5491 return new ActivityIntentInfo[size];
5492 }
5493
5494 @Override
Amith Yamasani483f3b02012-03-13 16:08:00 -07005495 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005496 if (!sUserManager.exists(userId)) return true;
Dianne Hackborne7f97212011-02-24 14:40:20 -08005497 PackageParser.Package p = filter.activity.owner;
5498 if (p != null) {
5499 PackageSetting ps = (PackageSetting)p.mExtras;
5500 if (ps != null) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07005501 // System apps are never considered stopped for purposes of
5502 // filtering, because there may be no way for the user to
5503 // actually re-launch them.
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005504 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
5505 && ps.getStopped(userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08005506 }
5507 }
5508 return false;
5509 }
5510
5511 @Override
Ben Gruver4efe9402013-04-02 21:18:41 -07005512 protected boolean isPackageForFilter(String packageName,
5513 PackageParser.ActivityIntentInfo info) {
5514 return packageName.equals(info.activity.owner.packageName);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005515 }
5516
5517 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005518 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005519 int match, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005520 if (!sUserManager.exists(userId)) return null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005521 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005522 return null;
5523 }
5524 final PackageParser.Activity activity = info.activity;
5525 if (mSafeMode && (activity.info.applicationInfo.flags
5526 &ApplicationInfo.FLAG_SYSTEM) == 0) {
5527 return null;
5528 }
Amith Yamasani13593602012-03-22 16:16:17 -07005529 PackageSetting ps = (PackageSetting) activity.owner.mExtras;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005530 if (ps == null) {
5531 return null;
5532 }
5533 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
5534 ps.readUserState(userId), userId);
5535 if (ai == null) {
5536 return null;
5537 }
5538 final ResolveInfo res = new ResolveInfo();
5539 res.activityInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
5541 res.filter = info;
5542 }
5543 res.priority = info.getPriority();
5544 res.preferredOrder = activity.owner.mPreferredOrder;
5545 //System.out.println("Result: " + res.activityInfo.className +
5546 // " = " + res.priority);
5547 res.match = match;
5548 res.isDefault = info.hasDefault;
5549 res.labelRes = info.labelRes;
5550 res.nonLocalizedLabel = info.nonLocalizedLabel;
5551 res.icon = info.icon;
Dianne Hackbornd99b2932011-08-18 14:39:58 -07005552 res.system = isSystemApp(res.activityInfo.applicationInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005553 return res;
5554 }
5555
5556 @Override
5557 protected void sortResults(List<ResolveInfo> results) {
5558 Collections.sort(results, mResolvePrioritySorter);
5559 }
5560
5561 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005562 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005563 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005564 out.print(prefix); out.print(
5565 Integer.toHexString(System.identityHashCode(filter.activity)));
5566 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005567 out.print(filter.activity.getComponentShortName());
5568 out.print(" filter ");
5569 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005570 }
5571
5572// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
5573// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
5574// final List<ResolveInfo> retList = Lists.newArrayList();
5575// while (i.hasNext()) {
5576// final ResolveInfo resolveInfo = i.next();
5577// if (isEnabledLP(resolveInfo.activityInfo)) {
5578// retList.add(resolveInfo);
5579// }
5580// }
5581// return retList;
5582// }
5583
5584 // Keys are String (activity class name), values are Activity.
5585 private final HashMap<ComponentName, PackageParser.Activity> mActivities
5586 = new HashMap<ComponentName, PackageParser.Activity>();
5587 private int mFlags;
5588 }
5589
5590 private final class ServiceIntentResolver
5591 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Kenny Root60f7ad82011-03-22 12:49:06 -07005592 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005593 boolean defaultOnly, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005594 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005595 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596 }
5597
Amith Yamasani483f3b02012-03-13 16:08:00 -07005598 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
5599 int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005600 if (!sUserManager.exists(userId)) return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005601 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02005602 return super.queryIntent(intent, resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005603 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005604 }
5605
Kenny Root60f7ad82011-03-22 12:49:06 -07005606 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005607 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005608 if (!sUserManager.exists(userId)) return null;
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07005609 if (packageServices == null) {
5610 return null;
5611 }
5612 mFlags = flags;
5613 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
Kenny Root62cc6902011-02-23 16:49:21 -08005614 final int N = packageServices.size();
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07005615 ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
5616 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07005617
5618 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
5619 for (int i = 0; i < N; ++i) {
5620 intentFilters = packageServices.get(i).intents;
5621 if (intentFilters != null && intentFilters.size() > 0) {
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07005622 PackageParser.ServiceIntentInfo[] array =
5623 new PackageParser.ServiceIntentInfo[intentFilters.size()];
5624 intentFilters.toArray(array);
5625 listCut.add(array);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07005626 }
5627 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07005628 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07005629 }
5630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005631 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005632 mServices.put(s.getComponentName(), s);
Kenny Root9718cf52011-02-23 16:45:26 -08005633 if (DEBUG_SHOW_INFO) {
5634 Log.v(TAG, " "
5635 + (s.info.nonLocalizedLabel != null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005636 ? s.info.nonLocalizedLabel : s.info.name) + ":");
Kenny Root9718cf52011-02-23 16:45:26 -08005637 Log.v(TAG, " Class=" + s.info.name);
5638 }
5639 final int NI = s.intents.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005640 int j;
5641 for (j=0; j<NI; j++) {
5642 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
Kenny Root9718cf52011-02-23 16:45:26 -08005643 if (DEBUG_SHOW_INFO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005644 Log.v(TAG, " IntentFilter:");
5645 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
5646 }
5647 if (!intent.debugCheck()) {
5648 Log.w(TAG, "==> For Service " + s.info.name);
5649 }
5650 addFilter(intent);
5651 }
5652 }
5653
5654 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005655 mServices.remove(s.getComponentName());
Kenny Root9718cf52011-02-23 16:45:26 -08005656 if (DEBUG_SHOW_INFO) {
5657 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005658 ? s.info.nonLocalizedLabel : s.info.name) + ":");
Kenny Root9718cf52011-02-23 16:45:26 -08005659 Log.v(TAG, " Class=" + s.info.name);
5660 }
5661 final int NI = s.intents.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005662 int j;
5663 for (j=0; j<NI; j++) {
5664 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
Kenny Root9718cf52011-02-23 16:45:26 -08005665 if (DEBUG_SHOW_INFO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005666 Log.v(TAG, " IntentFilter:");
5667 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
5668 }
5669 removeFilter(intent);
5670 }
5671 }
5672
5673 @Override
5674 protected boolean allowFilterResult(
5675 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
5676 ServiceInfo filterSi = filter.service.info;
5677 for (int i=dest.size()-1; i>=0; i--) {
5678 ServiceInfo destAi = dest.get(i).serviceInfo;
5679 if (destAi.name == filterSi.name
5680 && destAi.packageName == filterSi.packageName) {
5681 return false;
5682 }
5683 }
5684 return true;
5685 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005687 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -07005688 protected PackageParser.ServiceIntentInfo[] newArray(int size) {
5689 return new PackageParser.ServiceIntentInfo[size];
5690 }
5691
5692 @Override
Amith Yamasani483f3b02012-03-13 16:08:00 -07005693 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005694 if (!sUserManager.exists(userId)) return true;
Dianne Hackborne7f97212011-02-24 14:40:20 -08005695 PackageParser.Package p = filter.service.owner;
5696 if (p != null) {
5697 PackageSetting ps = (PackageSetting)p.mExtras;
5698 if (ps != null) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07005699 // System apps are never considered stopped for purposes of
5700 // filtering, because there may be no way for the user to
5701 // actually re-launch them.
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005702 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
5703 && ps.getStopped(userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08005704 }
5705 }
5706 return false;
5707 }
5708
5709 @Override
Ben Gruver4efe9402013-04-02 21:18:41 -07005710 protected boolean isPackageForFilter(String packageName,
5711 PackageParser.ServiceIntentInfo info) {
5712 return packageName.equals(info.service.owner.packageName);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005713 }
5714
5715 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005716 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005717 int match, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07005718 if (!sUserManager.exists(userId)) return null;
Jason parksa3cdaa52011-01-13 14:15:43 -06005719 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005720 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721 return null;
5722 }
5723 final PackageParser.Service service = info.service;
5724 if (mSafeMode && (service.info.applicationInfo.flags
5725 &ApplicationInfo.FLAG_SYSTEM) == 0) {
5726 return null;
5727 }
Amith Yamasani13593602012-03-22 16:16:17 -07005728 PackageSetting ps = (PackageSetting) service.owner.mExtras;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005729 if (ps == null) {
5730 return null;
5731 }
5732 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
5733 ps.readUserState(userId), userId);
Dianne Hackborn4428e172012-08-24 17:43:05 -07005734 if (si == null) {
5735 return null;
5736 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005737 final ResolveInfo res = new ResolveInfo();
5738 res.serviceInfo = si;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005739 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
5740 res.filter = filter;
5741 }
5742 res.priority = info.getPriority();
5743 res.preferredOrder = service.owner.mPreferredOrder;
5744 //System.out.println("Result: " + res.activityInfo.className +
5745 // " = " + res.priority);
5746 res.match = match;
5747 res.isDefault = info.hasDefault;
5748 res.labelRes = info.labelRes;
5749 res.nonLocalizedLabel = info.nonLocalizedLabel;
5750 res.icon = info.icon;
Dianne Hackbornd99b2932011-08-18 14:39:58 -07005751 res.system = isSystemApp(res.serviceInfo.applicationInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005752 return res;
5753 }
5754
5755 @Override
5756 protected void sortResults(List<ResolveInfo> results) {
5757 Collections.sort(results, mResolvePrioritySorter);
5758 }
5759
5760 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005761 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005762 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005763 out.print(prefix); out.print(
5764 Integer.toHexString(System.identityHashCode(filter.service)));
5765 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005766 out.print(filter.service.getComponentShortName());
5767 out.print(" filter ");
5768 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005769 }
5770
5771// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
5772// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
5773// final List<ResolveInfo> retList = Lists.newArrayList();
5774// while (i.hasNext()) {
5775// final ResolveInfo resolveInfo = (ResolveInfo) i;
5776// if (isEnabledLP(resolveInfo.serviceInfo)) {
5777// retList.add(resolveInfo);
5778// }
5779// }
5780// return retList;
5781// }
5782
5783 // Keys are String (activity class name), values are Activity.
5784 private final HashMap<ComponentName, PackageParser.Service> mServices
5785 = new HashMap<ComponentName, PackageParser.Service>();
5786 private int mFlags;
5787 };
5788
5789 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
5790 new Comparator<ResolveInfo>() {
5791 public int compare(ResolveInfo r1, ResolveInfo r2) {
5792 int v1 = r1.priority;
5793 int v2 = r2.priority;
5794 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
5795 if (v1 != v2) {
5796 return (v1 > v2) ? -1 : 1;
5797 }
5798 v1 = r1.preferredOrder;
5799 v2 = r2.preferredOrder;
5800 if (v1 != v2) {
5801 return (v1 > v2) ? -1 : 1;
5802 }
5803 if (r1.isDefault != r2.isDefault) {
5804 return r1.isDefault ? -1 : 1;
5805 }
5806 v1 = r1.match;
5807 v2 = r2.match;
5808 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
Dianne Hackbornd99b2932011-08-18 14:39:58 -07005809 if (v1 != v2) {
5810 return (v1 > v2) ? -1 : 1;
5811 }
5812 if (r1.system != r2.system) {
5813 return r1.system ? -1 : 1;
5814 }
5815 return 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005816 }
5817 };
5818
5819 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
5820 new Comparator<ProviderInfo>() {
5821 public int compare(ProviderInfo p1, ProviderInfo p2) {
5822 final int v1 = p1.initOrder;
5823 final int v2 = p2.initOrder;
5824 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
5825 }
5826 };
5827
Kenny Root447106f2011-03-23 11:00:15 -07005828 static final void sendPackageBroadcast(String action, String pkg,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005829 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
5830 int[] userIds) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005831 IActivityManager am = ActivityManagerNative.getDefault();
5832 if (am != null) {
5833 try {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005834 if (userIds == null) {
Dianne Hackbornc72fc672012-09-20 13:12:03 -07005835 userIds = am.getRunningUserIds();
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005836 }
Amith Yamasani13593602012-03-22 16:16:17 -07005837 for (int id : userIds) {
5838 final Intent intent = new Intent(action,
5839 pkg != null ? Uri.fromParts("package", pkg, null) : null);
5840 if (extras != null) {
5841 intent.putExtras(extras);
5842 }
5843 if (targetPkg != null) {
5844 intent.setPackage(targetPkg);
5845 }
5846 // Modify the UID when posting to other users
5847 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005848 if (uid > 0 && UserHandle.getUserId(uid) != id) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005849 uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
Amith Yamasani13593602012-03-22 16:16:17 -07005850 intent.putExtra(Intent.EXTRA_UID, uid);
5851 }
Dianne Hackbornc72fc672012-09-20 13:12:03 -07005852 intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
Amith Yamasani13593602012-03-22 16:16:17 -07005853 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005854 if (DEBUG_BROADCASTS) {
5855 RuntimeException here = new RuntimeException("here");
5856 here.fillInStackTrace();
5857 Slog.d(TAG, "Sending to user " + id + ": "
5858 + intent.toShortString(false, true, false, false)
5859 + " " + intent.getExtras(), here);
5860 }
Amith Yamasani13593602012-03-22 16:16:17 -07005861 am.broadcastIntent(null, intent, null, finishedReceiver,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08005862 0, null, null, null, android.app.AppOpsManager.OP_NONE,
5863 finishedReceiver != null, false, id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005865 } catch (RemoteException ex) {
5866 }
5867 }
5868 }
Kenny Root300c13a2011-01-18 13:04:40 -08005869
5870 /**
5871 * Check if the external storage media is available. This is true if there
5872 * is a mounted external storage medium or if the external storage is
5873 * emulated.
5874 */
5875 private boolean isExternalMediaAvailable() {
5876 return mMediaMounted || Environment.isExternalStorageEmulated();
5877 }
5878
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005879 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
Kenny Root447106f2011-03-23 11:00:15 -07005880 // writer
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005881 synchronized (mPackages) {
Kenny Root300c13a2011-01-18 13:04:40 -08005882 if (!isExternalMediaAvailable()) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005883 // If the external storage is no longer mounted at this point,
5884 // the caller may not have been able to delete all of this
5885 // packages files and can not delete any more. Bail.
5886 return null;
5887 }
Jeff Sharkey752cd922012-09-23 16:25:12 -07005888 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
5889 if (lastPackage != null) {
5890 pkgs.remove(lastPackage);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005891 }
Jeff Sharkey752cd922012-09-23 16:25:12 -07005892 if (pkgs.size() > 0) {
5893 return pkgs.get(0);
5894 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005895 }
5896 return null;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005898
Dianne Hackborn7767eac2012-08-23 18:25:40 -07005899 void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
5900 if (false) {
5901 RuntimeException here = new RuntimeException("here");
5902 here.fillInStackTrace();
5903 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
5904 + " andCode=" + andCode, here);
5905 }
5906 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
5907 userId, andCode ? 1 : 0, packageName));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005908 }
5909
Jeff Sharkey752cd922012-09-23 16:25:12 -07005910 void startCleaningPackages() {
Kenny Root447106f2011-03-23 11:00:15 -07005911 // reader
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005912 synchronized (mPackages) {
Kenny Root300c13a2011-01-18 13:04:40 -08005913 if (!isExternalMediaAvailable()) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005914 return;
5915 }
Jeff Sharkey752cd922012-09-23 16:25:12 -07005916 if (mSettings.mPackagesToBeCleaned.isEmpty()) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005917 return;
5918 }
5919 }
5920 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
5921 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
5922 IActivityManager am = ActivityManagerNative.getDefault();
5923 if (am != null) {
5924 try {
Jeff Sharkey752cd922012-09-23 16:25:12 -07005925 am.startService(null, intent, null, UserHandle.USER_OWNER);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005926 } catch (RemoteException e) {
5927 }
5928 }
5929 }
5930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005931 private final class AppDirObserver extends FileObserver {
5932 public AppDirObserver(String path, int mask, boolean isrom) {
5933 super(path, mask);
5934 mRootDir = path;
5935 mIsRom = isrom;
5936 }
5937
5938 public void onEvent(int event, String path) {
5939 String removedPackage = null;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07005940 int removedAppId = -1;
Dianne Hackborn786b4402012-08-27 15:14:02 -07005941 int[] removedUsers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942 String addedPackage = null;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07005943 int addedAppId = -1;
Dianne Hackborn786b4402012-08-27 15:14:02 -07005944 int[] addedUsers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005945
Kenny Root447106f2011-03-23 11:00:15 -07005946 // TODO post a message to the handler to obtain serial ordering
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005947 synchronized (mInstallLock) {
5948 String fullPathStr = null;
5949 File fullPath = null;
5950 if (path != null) {
5951 fullPath = new File(mRootDir, path);
5952 fullPathStr = fullPath.getPath();
5953 }
5954
Kenny Root9718cf52011-02-23 16:45:26 -08005955 if (DEBUG_APP_DIR_OBSERVER)
5956 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005957
5958 if (!isPackageFilename(path)) {
Kenny Root9718cf52011-02-23 16:45:26 -08005959 if (DEBUG_APP_DIR_OBSERVER)
5960 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005961 return;
5962 }
5963
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005964 // Ignore packages that are being installed or
5965 // have just been installed.
5966 if (ignoreCodePath(fullPathStr)) {
5967 return;
5968 }
5969 PackageParser.Package p = null;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07005970 PackageSetting ps = null;
Kenny Root447106f2011-03-23 11:00:15 -07005971 // reader
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005972 synchronized (mPackages) {
5973 p = mAppDirs.get(fullPathStr);
Dianne Hackborn786b4402012-08-27 15:14:02 -07005974 if (p != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07005975 ps = mSettings.mPackages.get(p.applicationInfo.packageName);
Dianne Hackborn786b4402012-08-27 15:14:02 -07005976 if (ps != null) {
5977 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
5978 } else {
5979 removedUsers = sUserManager.getUserIds();
5980 }
5981 }
5982 addedUsers = sUserManager.getUserIds();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005984 if ((event&REMOVE_EVENTS) != 0) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07005985 if (ps != null) {
Dianne Hackbornc895be72013-03-11 17:48:43 -07005986 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07005987 removePackageLI(ps, true);
5988 removedPackage = ps.name;
5989 removedAppId = ps.appId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005990 }
5991 }
5992
5993 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005994 if (p == null) {
Dianne Hackbornc895be72013-03-11 17:48:43 -07005995 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005996 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07005997 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
5998 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005999 PackageParser.PARSE_CHATTY |
6000 PackageParser.PARSE_MUST_BE_APK,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006001 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
Dianne Hackborn786b4402012-08-27 15:14:02 -07006002 System.currentTimeMillis(), UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006003 if (p != null) {
Kenny Root447106f2011-03-23 11:00:15 -07006004 /*
6005 * TODO this seems dangerous as the package may have
6006 * changed since we last acquired the mPackages
6007 * lock.
6008 */
6009 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006010 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07006011 updatePermissionsLPw(p.packageName, p,
Dianne Hackborne639da72012-02-21 15:11:13 -08006012 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006013 }
6014 addedPackage = p.applicationInfo.packageName;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006015 addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006016 }
6017 }
6018 }
6019
Kenny Root447106f2011-03-23 11:00:15 -07006020 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006021 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07006022 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006023 }
6024 }
6025
6026 if (removedPackage != null) {
6027 Bundle extras = new Bundle(1);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006028 extras.putInt(Intent.EXTRA_UID, removedAppId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006029 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006030 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
Dianne Hackborn786b4402012-08-27 15:14:02 -07006031 extras, null, null, removedUsers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006032 }
6033 if (addedPackage != null) {
6034 Bundle extras = new Bundle(1);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006035 extras.putInt(Intent.EXTRA_UID, addedAppId);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006036 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
Dianne Hackborn786b4402012-08-27 15:14:02 -07006037 extras, null, null, addedUsers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006038 }
6039 }
6040
6041 private final String mRootDir;
6042 private final boolean mIsRom;
6043 }
Jacek Surazski65e13172009-04-28 15:26:38 +02006044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006045 /* Called when a downloaded package installation has been confirmed by the user */
6046 public void installPackage(
6047 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02006048 installPackage(packageURI, observer, flags, null);
6049 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006050
Jacek Surazski65e13172009-04-28 15:26:38 +02006051 /* Called when a downloaded package installation has been confirmed by the user */
6052 public void installPackage(
6053 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
6054 final String installerPackageName) {
Kenny Root5ab21572011-07-27 11:11:19 -07006055 installPackageWithVerification(packageURI, observer, flags, installerPackageName, null,
Rich Canningse1d7c712012-08-08 12:46:06 -07006056 null, null);
Kenny Root5ab21572011-07-27 11:11:19 -07006057 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006058
Kenny Root5ab21572011-07-27 11:11:19 -07006059 @Override
6060 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
6061 int flags, String installerPackageName, Uri verificationURI,
Rich Canningse1d7c712012-08-08 12:46:06 -07006062 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
rich cannings706e8ba2012-08-20 13:20:14 -07006063 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
Ben Gruver37d83a32012-09-27 13:02:06 -07006064 VerificationParams.NO_UID, manifestDigest);
rich cannings706e8ba2012-08-20 13:20:14 -07006065 installPackageWithVerificationAndEncryption(packageURI, observer, flags,
6066 installerPackageName, verificationParams, encryptionParams);
6067 }
6068
6069 public void installPackageWithVerificationAndEncryption(Uri packageURI,
6070 IPackageInstallObserver observer, int flags, String installerPackageName,
6071 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
6072 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
6073 null);
Kenny Root5ab21572011-07-27 11:11:19 -07006074
6075 final int uid = Binder.getCallingUid();
Amith Yamasani71e6c692013-03-24 17:39:28 -07006076 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
Amith Yamasanie4cf7342012-12-17 11:12:09 -08006077 try {
6078 observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
6079 } catch (RemoteException re) {
6080 }
6081 return;
6082 }
6083
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006084 UserHandle user;
6085 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
6086 user = UserHandle.ALL;
6087 } else {
Dianne Hackborn786b4402012-08-27 15:14:02 -07006088 user = new UserHandle(UserHandle.getUserId(uid));
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006089 }
Kenny Root5ab21572011-07-27 11:11:19 -07006090
6091 final int filteredFlags;
6092
6093 if (uid == Process.SHELL_UID || uid == 0) {
6094 if (DEBUG_INSTALL) {
6095 Slog.v(TAG, "Install from ADB");
6096 }
6097 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
6098 } else {
6099 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
6100 }
6101
rich cannings13d428e2012-09-13 13:43:07 -07006102 verificationParams.setInstallerUid(uid);
6103
Kenny Root5ab21572011-07-27 11:11:19 -07006104 final Message msg = mHandler.obtainMessage(INIT_COPY);
6105 msg.obj = new InstallParams(packageURI, observer, filteredFlags, installerPackageName,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006106 verificationParams, encryptionParams, user);
Kenny Root5ab21572011-07-27 11:11:19 -07006107 mHandler.sendMessage(msg);
6108 }
6109
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006110 /**
6111 * @hide
6112 */
6113 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08006114 public int installExistingPackageAsUser(String packageName, int userId) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006115 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
6116 null);
6117 PackageSetting pkgSetting;
6118 final int uid = Binder.getCallingUid();
Amith Yamasani67df64b2012-12-14 12:09:36 -08006119 if (UserHandle.getUserId(uid) != userId) {
6120 mContext.enforceCallingPermission(
6121 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6122 "installExistingPackage for user " + userId);
6123 }
Amith Yamasani71e6c692013-03-24 17:39:28 -07006124 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
Amith Yamasanie4cf7342012-12-17 11:12:09 -08006125 return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
6126 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006127
6128 long callingId = Binder.clearCallingIdentity();
6129 try {
6130 boolean sendAdded = false;
6131 Bundle extras = new Bundle(1);
6132
6133 // writer
6134 synchronized (mPackages) {
6135 pkgSetting = mSettings.mPackages.get(packageName);
6136 if (pkgSetting == null) {
6137 return PackageManager.INSTALL_FAILED_INVALID_URI;
6138 }
6139 if (!pkgSetting.getInstalled(userId)) {
6140 pkgSetting.setInstalled(true, userId);
6141 mSettings.writePackageRestrictionsLPr(userId);
6142 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
6143 sendAdded = true;
6144 }
6145 }
6146
6147 if (sendAdded) {
6148 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
6149 packageName, extras, null, null, new int[] {userId});
Christopher Tate33356442013-05-01 14:17:53 -07006150 try {
6151 IActivityManager am = ActivityManagerNative.getDefault();
6152 final boolean isSystem =
6153 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
6154 if (isSystem && am.isUserRunning(userId, false)) {
6155 // The just-installed/enabled app is bundled on the system, so presumed
6156 // to be able to run automatically without needing an explicit launch.
6157 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
6158 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
6159 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
6160 .setPackage(packageName);
Christopher Tate95a9bfe2013-04-30 17:40:32 -07006161 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
6162 android.app.AppOpsManager.OP_NONE, false, false, userId);
Christopher Tate95a9bfe2013-04-30 17:40:32 -07006163 }
Christopher Tate33356442013-05-01 14:17:53 -07006164 } catch (RemoteException e) {
6165 // shouldn't happen
6166 Slog.w(TAG, "Unable to bootstrap installed package", e);
Christopher Tate95a9bfe2013-04-30 17:40:32 -07006167 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006168 }
6169 } finally {
6170 Binder.restoreCallingIdentity(callingId);
6171 }
6172
6173 return PackageManager.INSTALL_SUCCEEDED;
6174 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08006175
Amith Yamasani71e6c692013-03-24 17:39:28 -07006176 private boolean isUserRestricted(int userId, String restrictionKey) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08006177 Bundle restrictions = sUserManager.getUserRestrictions(userId);
Amith Yamasani71e6c692013-03-24 17:39:28 -07006178 if (restrictions.getBoolean(restrictionKey, false)) {
6179 Log.w(TAG, "User is restricted: " + restrictionKey);
6180 return true;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08006181 }
Amith Yamasani71e6c692013-03-24 17:39:28 -07006182 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08006183 }
6184
Kenny Root5ab21572011-07-27 11:11:19 -07006185 @Override
Kenny Root05ca4c92011-09-15 10:36:25 -07006186 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
rich cannings7e671512012-08-27 14:44:16 -07006187 mContext.enforceCallingOrSelfPermission(
6188 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
6189 "Only package verification agents can verify applications");
6190
Kenny Root5ab21572011-07-27 11:11:19 -07006191 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
Kenny Root05ca4c92011-09-15 10:36:25 -07006192 final PackageVerificationResponse response = new PackageVerificationResponse(
6193 verificationCode, Binder.getCallingUid());
Kenny Root5ab21572011-07-27 11:11:19 -07006194 msg.arg1 = id;
Kenny Root05ca4c92011-09-15 10:36:25 -07006195 msg.obj = response;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006196 mHandler.sendMessage(msg);
6197 }
6198
rich canningsd9ef3e52012-08-22 14:28:05 -07006199 @Override
6200 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
6201 long millisecondsToDelay) {
rich cannings7e671512012-08-27 14:44:16 -07006202 mContext.enforceCallingOrSelfPermission(
6203 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
6204 "Only package verification agents can extend verification timeouts");
6205
rich canningsd9ef3e52012-08-22 14:28:05 -07006206 final PackageVerificationState state = mPendingVerification.get(id);
6207 final PackageVerificationResponse response = new PackageVerificationResponse(
6208 verificationCodeAtTimeout, Binder.getCallingUid());
6209
rich canningsd1b5cfc2012-08-29 14:49:51 -07006210 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
6211 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
6212 }
6213 if (millisecondsToDelay < 0) {
6214 millisecondsToDelay = 0;
rich canningsd9ef3e52012-08-22 14:28:05 -07006215 }
6216 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
rich canningsd1b5cfc2012-08-29 14:49:51 -07006217 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
6218 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
rich canningsd9ef3e52012-08-22 14:28:05 -07006219 }
6220
6221 if ((state != null) && !state.timeoutExtended()) {
6222 state.extendTimeout();
6223
6224 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
6225 msg.arg1 = id;
6226 msg.obj = response;
6227 mHandler.sendMessageDelayed(msg, millisecondsToDelay);
6228 }
6229 }
6230
rich canningsd1b5cfc2012-08-29 14:49:51 -07006231 private void broadcastPackageVerified(int verificationId, Uri packageUri,
rich canningsd55deb02012-10-02 14:53:08 -07006232 int verificationCode, UserHandle user) {
rich canningsd1b5cfc2012-08-29 14:49:51 -07006233 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
6234 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
6235 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
6236 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
6237 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
6238
rich canningsd55deb02012-10-02 14:53:08 -07006239 mContext.sendBroadcastAsUser(intent, user,
6240 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
rich canningsd1b5cfc2012-08-29 14:49:51 -07006241 }
6242
Kenny Root05ca4c92011-09-15 10:36:25 -07006243 private ComponentName matchComponentForVerifier(String packageName,
6244 List<ResolveInfo> receivers) {
6245 ActivityInfo targetReceiver = null;
6246
6247 final int NR = receivers.size();
6248 for (int i = 0; i < NR; i++) {
6249 final ResolveInfo info = receivers.get(i);
6250 if (info.activityInfo == null) {
6251 continue;
6252 }
6253
6254 if (packageName.equals(info.activityInfo.packageName)) {
6255 targetReceiver = info.activityInfo;
6256 break;
6257 }
6258 }
6259
6260 if (targetReceiver == null) {
6261 return null;
6262 }
6263
6264 return new ComponentName(targetReceiver.packageName, targetReceiver.name);
6265 }
6266
6267 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
6268 List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
6269 if (pkgInfo.verifiers.length == 0) {
6270 return null;
6271 }
6272
6273 final int N = pkgInfo.verifiers.length;
6274 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
6275 for (int i = 0; i < N; i++) {
6276 final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
6277
6278 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
6279 receivers);
6280 if (comp == null) {
6281 continue;
6282 }
6283
6284 final int verifierUid = getUidForVerifier(verifierInfo);
6285 if (verifierUid == -1) {
6286 continue;
6287 }
6288
6289 if (DEBUG_VERIFY) {
6290 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
6291 + " with the correct signature");
6292 }
6293 sufficientVerifiers.add(comp);
6294 verificationState.addSufficientVerifier(verifierUid);
6295 }
6296
6297 return sufficientVerifiers;
6298 }
6299
6300 private int getUidForVerifier(VerifierInfo verifierInfo) {
6301 synchronized (mPackages) {
6302 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
6303 if (pkg == null) {
6304 return -1;
6305 } else if (pkg.mSignatures.length != 1) {
6306 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
6307 + " has more than one signature; ignoring");
6308 return -1;
6309 }
6310
6311 /*
6312 * If the public key of the package's signature does not match
6313 * our expected public key, then this is a different package and
6314 * we should skip.
6315 */
6316
6317 final byte[] expectedPublicKey;
6318 try {
6319 final Signature verifierSig = pkg.mSignatures[0];
6320 final PublicKey publicKey = verifierSig.getPublicKey();
6321 expectedPublicKey = publicKey.getEncoded();
6322 } catch (CertificateException e) {
6323 return -1;
6324 }
6325
6326 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
6327
6328 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
6329 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
6330 + " does not have the expected public key; ignoring");
6331 return -1;
6332 }
6333
6334 return pkg.applicationInfo.uid;
6335 }
6336 }
6337
Christopher Tate1bb69062010-02-19 17:02:12 -08006338 public void finishPackageInstall(int token) {
Kenny Root461ff1f2011-08-09 09:43:03 -07006339 enforceSystemOrRoot("Only the system is allowed to finish installs");
6340
6341 if (DEBUG_INSTALL) {
6342 Slog.v(TAG, "BM finishing package install for " + token);
6343 }
6344
6345 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
Christopher Tate1bb69062010-02-19 17:02:12 -08006346 mHandler.sendMessage(msg);
6347 }
6348
Kenny Root5ab21572011-07-27 11:11:19 -07006349 /**
6350 * Get the verification agent timeout.
6351 *
6352 * @return verification timeout in milliseconds
6353 */
6354 private long getVerificationTimeout() {
rich cannings4d8fc792012-09-07 14:43:43 -07006355 return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
6356 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
Kenny Root5ab21572011-07-27 11:11:19 -07006357 DEFAULT_VERIFICATION_TIMEOUT);
6358 }
6359
6360 /**
rich canningsa6cfe522012-05-21 15:50:56 -07006361 * Get the default verification agent response code.
6362 *
6363 * @return default verification response code
6364 */
6365 private int getDefaultVerificationResponse() {
rich cannings4d8fc792012-09-07 14:43:43 -07006366 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
6367 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
rich canningsa6cfe522012-05-21 15:50:56 -07006368 DEFAULT_VERIFICATION_RESPONSE);
6369 }
6370
6371 /**
Kenny Root5ab21572011-07-27 11:11:19 -07006372 * Check whether or not package verification has been enabled.
6373 *
6374 * @return true if verification should be performed
6375 */
rich cannings4e5753f2012-09-19 16:03:56 -07006376 private boolean isVerificationEnabled(int flags) {
rich canningse4bf0ea2012-09-14 13:18:55 -07006377 if (!DEFAULT_VERIFY_ENABLE) {
6378 return false;
6379 }
6380
rich cannings4e5753f2012-09-19 16:03:56 -07006381 // Check if installing from ADB
6382 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
rich canningsa2064df2012-09-30 14:52:41 -07006383 // Do not run verification in a test harness environment
6384 if (ActivityManager.isRunningInTestHarness()) {
6385 return false;
6386 }
rich cannings4e5753f2012-09-19 16:03:56 -07006387 // Check if the developer does not want package verification for ADB installs
6388 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
6389 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
6390 return false;
6391 }
6392 }
6393
rich cannings4d8fc792012-09-07 14:43:43 -07006394 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
rich canningse4bf0ea2012-09-14 13:18:55 -07006395 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
Kenny Root5ab21572011-07-27 11:11:19 -07006396 }
6397
Matt Finifterf8a98ed2012-05-14 15:43:34 -07006398 /**
6399 * Get the "allow unknown sources" setting.
6400 *
6401 * @return the current "allow unknown sources" setting
6402 */
6403 private int getUnknownSourcesSettings() {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07006404 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
6405 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
Matt Finifterf8a98ed2012-05-14 15:43:34 -07006406 -1);
6407 }
6408
Kenny Rootf03b45f2011-02-23 17:25:45 -08006409 public void setInstallerPackageName(String targetPackage, String installerPackageName) {
Dianne Hackborn880119b2010-11-18 22:26:40 -08006410 final int uid = Binder.getCallingUid();
Kenny Root447106f2011-03-23 11:00:15 -07006411 // writer
Dianne Hackborn880119b2010-11-18 22:26:40 -08006412 synchronized (mPackages) {
6413 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
6414 if (targetPackageSetting == null) {
6415 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
6416 }
6417
6418 PackageSetting installerPackageSetting;
6419 if (installerPackageName != null) {
6420 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
6421 if (installerPackageSetting == null) {
6422 throw new IllegalArgumentException("Unknown installer package: "
6423 + installerPackageName);
6424 }
6425 } else {
6426 installerPackageSetting = null;
6427 }
6428
6429 Signature[] callerSignature;
Kenny Root447106f2011-03-23 11:00:15 -07006430 Object obj = mSettings.getUserIdLPr(uid);
Dianne Hackborn880119b2010-11-18 22:26:40 -08006431 if (obj != null) {
6432 if (obj instanceof SharedUserSetting) {
6433 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
6434 } else if (obj instanceof PackageSetting) {
6435 callerSignature = ((PackageSetting)obj).signatures.mSignatures;
6436 } else {
6437 throw new SecurityException("Bad object " + obj + " for uid " + uid);
6438 }
6439 } else {
6440 throw new SecurityException("Unknown calling uid " + uid);
6441 }
6442
6443 // Verify: can't set installerPackageName to a package that is
6444 // not signed with the same cert as the caller.
6445 if (installerPackageSetting != null) {
Kenny Root447106f2011-03-23 11:00:15 -07006446 if (compareSignatures(callerSignature,
Dianne Hackborn880119b2010-11-18 22:26:40 -08006447 installerPackageSetting.signatures.mSignatures)
6448 != PackageManager.SIGNATURE_MATCH) {
6449 throw new SecurityException(
6450 "Caller does not have same cert as new installer package "
6451 + installerPackageName);
6452 }
6453 }
6454
6455 // Verify: if target already has an installer package, it must
6456 // be signed with the same cert as the caller.
6457 if (targetPackageSetting.installerPackageName != null) {
6458 PackageSetting setting = mSettings.mPackages.get(
6459 targetPackageSetting.installerPackageName);
6460 // If the currently set package isn't valid, then it's always
6461 // okay to change it.
6462 if (setting != null) {
Kenny Root447106f2011-03-23 11:00:15 -07006463 if (compareSignatures(callerSignature,
Dianne Hackborn880119b2010-11-18 22:26:40 -08006464 setting.signatures.mSignatures)
6465 != PackageManager.SIGNATURE_MATCH) {
6466 throw new SecurityException(
6467 "Caller does not have same cert as old installer package "
6468 + targetPackageSetting.installerPackageName);
6469 }
6470 }
6471 }
6472
6473 // Okay!
6474 targetPackageSetting.installerPackageName = installerPackageName;
6475 scheduleWriteSettingsLocked();
6476 }
6477 }
6478
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006479 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006480 // Queue up an async operation since the package installation may take a little while.
6481 mHandler.post(new Runnable() {
6482 public void run() {
6483 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07006484 // Result object to be returned
6485 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006486 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07006487 res.uid = -1;
6488 res.pkg = null;
6489 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006490 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07006491 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07006492 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006493 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07006494 }
Kenny Root6dceb882012-04-12 14:23:49 -07006495 args.doPostInstall(res.returnCode, res.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006496 }
Christopher Tate1bb69062010-02-19 17:02:12 -08006497
6498 // A restore should be performed at this point if (a) the install
6499 // succeeded, (b) the operation is not an update, and (c) the new
6500 // package has a backupAgent defined.
6501 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08006502 boolean doRestore = (!update
6503 && res.pkg != null
6504 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08006505
6506 // Set up the post-install work request bookkeeping. This will be used
6507 // and cleaned up by the post-install event handling regardless of whether
6508 // there's a restore pass performed. Token values are >= 1.
6509 int token;
6510 if (mNextInstallToken < 0) mNextInstallToken = 1;
6511 token = mNextInstallToken++;
6512
6513 PostInstallData data = new PostInstallData(args, res);
6514 mRunningInstalls.put(token, data);
6515 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
6516
6517 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
6518 // Pass responsibility to the Backup Manager. It will perform a
6519 // restore if appropriate, then pass responsibility back to the
6520 // Package Manager to run the post-install observer callbacks
6521 // and broadcasts.
6522 IBackupManager bm = IBackupManager.Stub.asInterface(
6523 ServiceManager.getService(Context.BACKUP_SERVICE));
6524 if (bm != null) {
6525 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
6526 + " to BM for possible restore");
6527 try {
6528 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
6529 } catch (RemoteException e) {
6530 // can't happen; the backup manager is local
6531 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006532 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08006533 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006534 }
Christopher Tate1bb69062010-02-19 17:02:12 -08006535 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006536 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08006537 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006539 }
Christopher Tate1bb69062010-02-19 17:02:12 -08006540
6541 if (!doRestore) {
6542 // No restore possible, or the Backup Manager was mysteriously not
6543 // available -- just fire the post-install work request directly.
6544 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
6545 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
6546 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006547 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006548 }
6549 });
6550 }
6551
Kenny Root5ab21572011-07-27 11:11:19 -07006552 private abstract class HandlerParams {
6553 private static final int MAX_RETRIES = 4;
6554
6555 /**
6556 * Number of times startCopy() has been attempted and had a non-fatal
6557 * error.
6558 */
6559 private int mRetries = 0;
6560
Amith Yamasani6ec10122012-08-23 13:49:25 -07006561 /** User handle for the user requesting the information or installation. */
6562 private final UserHandle mUser;
6563
6564 HandlerParams(UserHandle user) {
6565 mUser = user;
6566 }
6567
6568 UserHandle getUser() {
6569 return mUser;
6570 }
6571
Dianne Hackborn7d608422011-08-07 16:24:18 -07006572 final boolean startCopy() {
6573 boolean res;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006574 try {
Dianne Hackbornc895be72013-03-11 17:48:43 -07006575 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
Kenny Root5ab21572011-07-27 11:11:19 -07006576
6577 if (++mRetries > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006578 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006579 mHandler.sendEmptyMessage(MCS_GIVE_UP);
6580 handleServiceError();
Dianne Hackborn7d608422011-08-07 16:24:18 -07006581 return false;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006582 } else {
6583 handleStartCopy();
Dianne Hackborn7d608422011-08-07 16:24:18 -07006584 res = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006585 }
6586 } catch (RemoteException e) {
Kenny Root5ab21572011-07-27 11:11:19 -07006587 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006588 mHandler.sendEmptyMessage(MCS_RECONNECT);
Dianne Hackborn7d608422011-08-07 16:24:18 -07006589 res = false;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006590 }
6591 handleReturnCode();
Dianne Hackborn7d608422011-08-07 16:24:18 -07006592 return res;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006593 }
6594
6595 final void serviceError() {
Kenny Root5ab21572011-07-27 11:11:19 -07006596 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006597 handleServiceError();
6598 handleReturnCode();
6599 }
Kenny Root5ab21572011-07-27 11:11:19 -07006600
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006601 abstract void handleStartCopy() throws RemoteException;
6602 abstract void handleServiceError();
6603 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006604 }
6605
Kenny Root366949c2011-01-14 17:18:14 -08006606 class MeasureParams extends HandlerParams {
6607 private final PackageStats mStats;
6608 private boolean mSuccess;
6609
6610 private final IPackageStatsObserver mObserver;
6611
Kenny Roota69b7eb2012-05-14 14:47:06 -07006612 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
Amith Yamasani6ec10122012-08-23 13:49:25 -07006613 super(new UserHandle(stats.userHandle));
Kenny Root366949c2011-01-14 17:18:14 -08006614 mObserver = observer;
6615 mStats = stats;
Kenny Root366949c2011-01-14 17:18:14 -08006616 }
6617
6618 @Override
Dianne Hackbornc895be72013-03-11 17:48:43 -07006619 public String toString() {
6620 return "MeasureParams{"
6621 + Integer.toHexString(System.identityHashCode(this))
6622 + " " + mStats.packageName + "}";
6623 }
6624
6625 @Override
Kenny Root366949c2011-01-14 17:18:14 -08006626 void handleStartCopy() throws RemoteException {
Kenny Roota69b7eb2012-05-14 14:47:06 -07006627 synchronized (mInstallLock) {
Dianne Hackborn0c380492012-08-20 17:23:30 -07006628 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
Kenny Roota69b7eb2012-05-14 14:47:06 -07006629 }
Kenny Root366949c2011-01-14 17:18:14 -08006630
Kenny Roota69b7eb2012-05-14 14:47:06 -07006631 final boolean mounted;
Kenny Root366949c2011-01-14 17:18:14 -08006632 if (Environment.isExternalStorageEmulated()) {
6633 mounted = true;
6634 } else {
6635 final String status = Environment.getExternalStorageState();
Jeff Sharkeyb049e212012-09-07 23:16:01 -07006636 mounted = (Environment.MEDIA_MOUNTED.equals(status)
6637 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
Kenny Root366949c2011-01-14 17:18:14 -08006638 }
6639
6640 if (mounted) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07006641 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
6642
6643 final File externalCacheDir = userEnv
Kenny Root366949c2011-01-14 17:18:14 -08006644 .getExternalStorageAppCacheDirectory(mStats.packageName);
6645 final long externalCacheSize = mContainerService
6646 .calculateDirectorySize(externalCacheDir.getPath());
6647 mStats.externalCacheSize = externalCacheSize;
6648
Jeff Sharkeyb049e212012-09-07 23:16:01 -07006649 final File externalDataDir = userEnv
Kenny Root366949c2011-01-14 17:18:14 -08006650 .getExternalStorageAppDataDirectory(mStats.packageName);
6651 long externalDataSize = mContainerService.calculateDirectorySize(externalDataDir
6652 .getPath());
6653
6654 if (externalCacheDir.getParentFile().equals(externalDataDir)) {
6655 externalDataSize -= externalCacheSize;
6656 }
6657 mStats.externalDataSize = externalDataSize;
6658
Jeff Sharkeyb049e212012-09-07 23:16:01 -07006659 final File externalMediaDir = userEnv
Kenny Root366949c2011-01-14 17:18:14 -08006660 .getExternalStorageAppMediaDirectory(mStats.packageName);
6661 mStats.externalMediaSize = mContainerService
Kenny Rootc7624d92011-02-23 16:25:25 -08006662 .calculateDirectorySize(externalMediaDir.getPath());
Kenny Rootbcd6c962011-01-17 11:21:49 -08006663
Jeff Sharkeyb049e212012-09-07 23:16:01 -07006664 final File externalObbDir = userEnv
Kenny Rootbcd6c962011-01-17 11:21:49 -08006665 .getExternalStorageAppObbDirectory(mStats.packageName);
6666 mStats.externalObbSize = mContainerService.calculateDirectorySize(externalObbDir
6667 .getPath());
Kenny Root366949c2011-01-14 17:18:14 -08006668 }
6669 }
6670
6671 @Override
6672 void handleReturnCode() {
6673 if (mObserver != null) {
6674 try {
6675 mObserver.onGetStatsCompleted(mStats, mSuccess);
6676 } catch (RemoteException e) {
6677 Slog.i(TAG, "Observer no longer exists.");
6678 }
6679 }
6680 }
6681
6682 @Override
6683 void handleServiceError() {
6684 Slog.e(TAG, "Could not measure application " + mStats.packageName
6685 + " external storage");
6686 }
6687 }
6688
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006689 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006690 final IPackageInstallObserver observer;
6691 int flags;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006692
6693 private final Uri mPackageURI;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006694 final String installerPackageName;
rich cannings706e8ba2012-08-20 13:20:14 -07006695 final VerificationParams verificationParams;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006696 private InstallArgs mArgs;
6697 private int mRet;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006698 private File mTempPackage;
6699 final ContainerEncryptionParams encryptionParams;
Kenny Root5ab21572011-07-27 11:11:19 -07006700
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006701 InstallParams(Uri packageURI,
6702 IPackageInstallObserver observer, int flags,
rich cannings706e8ba2012-08-20 13:20:14 -07006703 String installerPackageName, VerificationParams verificationParams,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006704 ContainerEncryptionParams encryptionParams, UserHandle user) {
Amith Yamasani6ec10122012-08-23 13:49:25 -07006705 super(user);
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006706 this.mPackageURI = packageURI;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006707 this.flags = flags;
6708 this.observer = observer;
6709 this.installerPackageName = installerPackageName;
rich cannings706e8ba2012-08-20 13:20:14 -07006710 this.verificationParams = verificationParams;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006711 this.encryptionParams = encryptionParams;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006712 }
6713
Dianne Hackbornc895be72013-03-11 17:48:43 -07006714 @Override
6715 public String toString() {
6716 return "InstallParams{"
6717 + Integer.toHexString(System.identityHashCode(this))
6718 + " " + mPackageURI + "}";
6719 }
6720
rich cannings706e8ba2012-08-20 13:20:14 -07006721 public ManifestDigest getManifestDigest() {
6722 if (verificationParams == null) {
6723 return null;
6724 }
6725 return verificationParams.getManifestDigest();
6726 }
6727
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006728 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
6729 String packageName = pkgLite.packageName;
6730 int installLocation = pkgLite.installLocation;
6731 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Kenny Root447106f2011-03-23 11:00:15 -07006732 // reader
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006733 synchronized (mPackages) {
6734 PackageParser.Package pkg = mPackages.get(packageName);
6735 if (pkg != null) {
6736 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07006737 // Check for downgrading.
6738 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
6739 if (pkgLite.versionCode < pkg.mVersionCode) {
6740 Slog.w(TAG, "Can't install update of " + packageName
6741 + " update version " + pkgLite.versionCode
6742 + " is older than installed version "
6743 + pkg.mVersionCode);
6744 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
6745 }
6746 }
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006747 // Check for updated system application.
6748 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6749 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006750 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006751 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
6752 }
6753 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
6754 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006755 if (onSd) {
6756 // Install flag overrides everything.
6757 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
6758 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07006759 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006760 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
6761 // Application explicitly specified internal.
6762 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
6763 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
6764 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07006765 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006766 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07006767 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07006768 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
6769 }
6770 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006771 }
6772 }
6773 } else {
6774 // Invalid install. Return error code
6775 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
6776 }
6777 }
6778 }
6779 // All the special cases have been taken care of.
6780 // Return result based on recommended install location.
6781 if (onSd) {
6782 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
6783 }
6784 return pkgLite.recommendedInstallLocation;
6785 }
6786
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006787 /*
6788 * Invoke remote method to get package information and install
6789 * location values. Override install location based on default
6790 * policy if needed and then create install arguments based
6791 * on the install location.
6792 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006793 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08006794 int ret = PackageManager.INSTALL_SUCCEEDED;
Kenny Root05ca4c92011-09-15 10:36:25 -07006795 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
6796 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
6797 PackageInfoLite pkgLite = null;
6798
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07006799 if (onInt && onSd) {
6800 // Check if both bits are set.
6801 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
6802 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006803 } else {
Kenny Root62e1b4e2011-03-14 17:13:39 -07006804 final long lowThreshold;
6805
6806 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
6807 .getService(DeviceStorageMonitorService.SERVICE);
6808 if (dsm == null) {
6809 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
6810 lowThreshold = 0L;
6811 } else {
6812 lowThreshold = dsm.getMemoryLowThreshold();
6813 }
6814
Kenny Root11128572010-10-11 10:51:32 -07006815 try {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006816 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
Kenny Root11128572010-10-11 10:51:32 -07006817 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root11128572010-10-11 10:51:32 -07006818
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006819 final File packageFile;
6820 if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006821 mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
6822 if (mTempPackage != null) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08006823 ParcelFileDescriptor out;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006824 try {
6825 out = ParcelFileDescriptor.open(mTempPackage,
6826 ParcelFileDescriptor.MODE_READ_WRITE);
6827 } catch (FileNotFoundException e) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08006828 out = null;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006829 Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
6830 }
6831
6832 // Make a temporary file for decryption.
6833 ret = mContainerService
6834 .copyResource(mPackageURI, encryptionParams, out);
Dianne Hackborn40e9f292012-11-27 19:12:23 -08006835 IoUtils.closeQuietly(out);
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006836
6837 packageFile = mTempPackage;
6838
6839 FileUtils.setPermissions(packageFile.getAbsolutePath(),
Kenny Root0b2fa8c2012-09-14 10:26:16 -07006840 FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
6841 | FileUtils.S_IROTH,
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006842 -1, -1);
6843 } else {
6844 packageFile = null;
6845 }
6846 } else {
6847 packageFile = new File(mPackageURI.getPath());
6848 }
6849
6850 if (packageFile != null) {
6851 // Remote call to find out default install location
Kenny Rootcea37432012-10-18 14:57:33 -07006852 final String packageFilePath = packageFile.getAbsolutePath();
6853 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
6854 lowThreshold);
6855
6856 /*
6857 * If we have too little free space, try to free cache
6858 * before giving up.
6859 */
6860 if (pkgLite.recommendedInstallLocation
6861 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
6862 final long size = mContainerService.calculateInstalledSize(
6863 packageFilePath, isForwardLocked());
6864 if (mInstaller.freeCache(size + lowThreshold) >= 0) {
6865 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
6866 flags, lowThreshold);
6867 }
Kenny Root3f96d0e2012-12-11 12:48:08 -08006868 /*
6869 * The cache free must have deleted the file we
6870 * downloaded to install.
6871 *
6872 * TODO: fix the "freeCache" call to not delete
6873 * the file we care about.
6874 */
6875 if (pkgLite.recommendedInstallLocation
6876 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
6877 pkgLite.recommendedInstallLocation
6878 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
6879 }
Kenny Rootcea37432012-10-18 14:57:33 -07006880 }
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006881 }
6882 } finally {
6883 mContext.revokeUriPermission(mPackageURI,
6884 Intent.FLAG_GRANT_READ_URI_PERMISSION);
6885 }
6886 }
6887
6888 if (ret == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006889 int loc = pkgLite.recommendedInstallLocation;
Kenny Root1ebd74a2011-08-03 15:09:44 -07006890 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006891 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Kenny Root1ebd74a2011-08-03 15:09:44 -07006892 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08006893 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
Kenny Root1ebd74a2011-08-03 15:09:44 -07006894 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006895 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6896 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
6897 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Kenny Root1ebd74a2011-08-03 15:09:44 -07006898 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
6899 ret = PackageManager.INSTALL_FAILED_INVALID_URI;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006900 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
Kenny Root1ebd74a2011-08-03 15:09:44 -07006901 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006902 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006903 // Override with defaults if needed.
6904 loc = installLocationPolicy(pkgLite, flags);
Kenny Roota3e90792012-10-18 10:58:36 -07006905 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
6906 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
6907 } else if (!onSd && !onInt) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07006908 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006909 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
6910 // Set the flag to install on external media.
6911 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07006912 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006913 } else {
6914 // Make sure the flag for installing on external
6915 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07006916 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006917 flags &= ~PackageManager.INSTALL_EXTERNAL;
6918 }
6919 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006920 }
6921 }
Kenny Root5ab21572011-07-27 11:11:19 -07006922
6923 final InstallArgs args = createInstallArgs(this);
Kenny Root05ca4c92011-09-15 10:36:25 -07006924 mArgs = args;
6925
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006926 if (ret == PackageManager.INSTALL_SUCCEEDED) {
rich cannings36070b42012-10-09 11:50:15 -07006927 /*
6928 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
6929 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
6930 */
6931 int userIdentifier = getUser().getIdentifier();
6932 if (userIdentifier == UserHandle.USER_ALL
6933 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
6934 userIdentifier = UserHandle.USER_OWNER;
6935 }
6936
Kenny Root5ab21572011-07-27 11:11:19 -07006937 /*
6938 * Determine if we have any installed package verifiers. If we
6939 * do, then we'll defer to them to verify the packages.
6940 */
Kenny Root05ca4c92011-09-15 10:36:25 -07006941 final int requiredUid = mRequiredVerifierPackage == null ? -1
rich cannings36070b42012-10-09 11:50:15 -07006942 : getPackageUid(mRequiredVerifierPackage, userIdentifier);
rich cannings4e5753f2012-09-19 16:03:56 -07006943 if (requiredUid != -1 && isVerificationEnabled(flags)) {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07006944 final Intent verification = new Intent(
6945 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
6946 verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
Kenny Root05ca4c92011-09-15 10:36:25 -07006947 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root5ab21572011-07-27 11:11:19 -07006948
Andy Stadler250ce282012-08-24 16:09:03 -07006949 final List<ResolveInfo> receivers = queryIntentReceivers(verification,
6950 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
6951 0 /* TODO: Which userId? */);
Kenny Root05ca4c92011-09-15 10:36:25 -07006952
6953 if (DEBUG_VERIFY) {
Kenny Root5ab21572011-07-27 11:11:19 -07006954 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
Kenny Root05ca4c92011-09-15 10:36:25 -07006955 + verification.toString() + " with " + pkgLite.verifiers.length
6956 + " optional verifiers");
Kenny Root5ab21572011-07-27 11:11:19 -07006957 }
6958
6959 final int verificationId = mPendingVerificationToken++;
6960
6961 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
6962
6963 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
6964 installerPackageName);
6965
6966 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
6967
rich cannings13d428e2012-09-13 13:43:07 -07006968 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
6969 pkgLite.packageName);
6970
6971 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
6972 pkgLite.versionCode);
6973
rich cannings706e8ba2012-08-20 13:20:14 -07006974 if (verificationParams != null) {
6975 if (verificationParams.getVerificationURI() != null) {
6976 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
6977 verificationParams.getVerificationURI());
6978 }
6979 if (verificationParams.getOriginatingURI() != null) {
6980 verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
6981 verificationParams.getOriginatingURI());
6982 }
6983 if (verificationParams.getReferrer() != null) {
6984 verification.putExtra(Intent.EXTRA_REFERRER,
6985 verificationParams.getReferrer());
6986 }
Ben Gruver37d83a32012-09-27 13:02:06 -07006987 if (verificationParams.getOriginatingUid() >= 0) {
6988 verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
6989 verificationParams.getOriginatingUid());
6990 }
rich cannings13d428e2012-09-13 13:43:07 -07006991 if (verificationParams.getInstallerUid() >= 0) {
6992 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
6993 verificationParams.getInstallerUid());
6994 }
Kenny Root5ab21572011-07-27 11:11:19 -07006995 }
6996
Kenny Root05ca4c92011-09-15 10:36:25 -07006997 final PackageVerificationState verificationState = new PackageVerificationState(
6998 requiredUid, args);
6999
7000 mPendingVerification.append(verificationId, verificationState);
7001
7002 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
7003 receivers, verificationState);
Kenny Root5ab21572011-07-27 11:11:19 -07007004
7005 /*
Kenny Root05ca4c92011-09-15 10:36:25 -07007006 * If any sufficient verifiers were listed in the package
7007 * manifest, attempt to ask them.
Kenny Root5ab21572011-07-27 11:11:19 -07007008 */
Kenny Root05ca4c92011-09-15 10:36:25 -07007009 if (sufficientVerifiers != null) {
7010 final int N = sufficientVerifiers.size();
7011 if (N == 0) {
7012 Slog.i(TAG, "Additional verifiers required, but none installed.");
7013 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
7014 } else {
7015 for (int i = 0; i < N; i++) {
7016 final ComponentName verifierComponent = sufficientVerifiers.get(i);
7017
7018 final Intent sufficientIntent = new Intent(verification);
7019 sufficientIntent.setComponent(verifierComponent);
7020
rich canningsd55deb02012-10-02 14:53:08 -07007021 mContext.sendBroadcastAsUser(sufficientIntent, getUser());
Kenny Root05ca4c92011-09-15 10:36:25 -07007022 }
7023 }
7024 }
7025
7026 final ComponentName requiredVerifierComponent = matchComponentForVerifier(
7027 mRequiredVerifierPackage, receivers);
7028 if (ret == PackageManager.INSTALL_SUCCEEDED
7029 && mRequiredVerifierPackage != null) {
7030 /*
7031 * Send the intent to the required verification agent,
7032 * but only start the verification timeout after the
7033 * target BroadcastReceivers have run.
7034 */
7035 verification.setComponent(requiredVerifierComponent);
rich canningsd55deb02012-10-02 14:53:08 -07007036 mContext.sendOrderedBroadcastAsUser(verification, getUser(),
Kenny Root05ca4c92011-09-15 10:36:25 -07007037 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7038 new BroadcastReceiver() {
7039 @Override
7040 public void onReceive(Context context, Intent intent) {
7041 final Message msg = mHandler
7042 .obtainMessage(CHECK_PENDING_VERIFICATION);
7043 msg.arg1 = verificationId;
7044 mHandler.sendMessageDelayed(msg, getVerificationTimeout());
7045 }
7046 }, null, 0, null, null);
7047
7048 /*
7049 * We don't want the copy to proceed until verification
7050 * succeeds, so null out this field.
7051 */
7052 mArgs = null;
7053 }
Kenny Root5ab21572011-07-27 11:11:19 -07007054 } else {
Kenny Root05ca4c92011-09-15 10:36:25 -07007055 /*
7056 * No package verification is enabled, so immediately start
7057 * the remote call to initiate copy using temporary file.
7058 */
Kenny Root5ab21572011-07-27 11:11:19 -07007059 ret = args.copyApk(mContainerService, true);
7060 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007061 }
Kenny Root5ab21572011-07-27 11:11:19 -07007062
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007063 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007064 }
7065
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007066 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007067 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07007068 // If mArgs is null, then MCS couldn't be reached. When it
7069 // reconnects, it will try again to install. At that point, this
7070 // will succeed.
7071 if (mArgs != null) {
7072 processPendingInstall(mArgs, mRet);
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07007073
Kenny Root0b2fa8c2012-09-14 10:26:16 -07007074 if (mTempPackage != null) {
7075 if (!mTempPackage.delete()) {
7076 Slog.w(TAG, "Couldn't delete temporary file: " +
7077 mTempPackage.getAbsolutePath());
7078 }
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07007079 }
7080 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007081 }
7082
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007083 @Override
7084 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007085 mArgs = createInstallArgs(this);
7086 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007087 }
Kenny Root6dceb882012-04-12 14:23:49 -07007088
7089 public boolean isForwardLocked() {
7090 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
7091 }
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07007092
7093 public Uri getPackageUri() {
7094 if (mTempPackage != null) {
7095 return Uri.fromFile(mTempPackage);
7096 } else {
7097 return mPackageURI;
7098 }
7099 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007100 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007101
7102 /*
7103 * Utility class used in movePackage api.
7104 * srcArgs and targetArgs are not set for invalid flags and make
7105 * sure to do null checks when invoking methods on them.
7106 * We probably want to return ErrorPrams for both failed installs
7107 * and moves.
7108 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007109 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007110 final IPackageMoveObserver observer;
7111 final int flags;
7112 final String packageName;
7113 final InstallArgs srcArgs;
7114 final InstallArgs targetArgs;
Kenny Root6dceb882012-04-12 14:23:49 -07007115 int uid;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007116 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07007117
7118 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
Amith Yamasani6ec10122012-08-23 13:49:25 -07007119 String packageName, String dataDir, int uid, UserHandle user) {
7120 super(user);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007121 this.srcArgs = srcArgs;
7122 this.observer = observer;
7123 this.flags = flags;
7124 this.packageName = packageName;
Kenny Root6dceb882012-04-12 14:23:49 -07007125 this.uid = uid;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007126 if (srcArgs != null) {
7127 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07007128 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007129 } else {
7130 targetArgs = null;
7131 }
7132 }
7133
Dianne Hackbornc895be72013-03-11 17:48:43 -07007134 @Override
7135 public String toString() {
7136 return "MoveParams{"
7137 + Integer.toHexString(System.identityHashCode(this))
7138 + " " + packageName + "}";
7139 }
7140
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007141 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08007142 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7143 // Check for storage space on target medium
7144 if (!targetArgs.checkFreeStorage(mContainerService)) {
7145 Log.w(TAG, "Insufficient storage to install");
7146 return;
7147 }
Kenny Rootbf023582012-05-02 16:56:15 -07007148
7149 mRet = srcArgs.doPreCopy();
7150 if (mRet != PackageManager.INSTALL_SUCCEEDED) {
7151 return;
7152 }
7153
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007154 mRet = targetArgs.copyApk(mContainerService, false);
Kenny Rootbf023582012-05-02 16:56:15 -07007155 if (mRet != PackageManager.INSTALL_SUCCEEDED) {
7156 srcArgs.doPostCopy(uid);
7157 return;
7158 }
7159
7160 mRet = srcArgs.doPostCopy(uid);
7161 if (mRet != PackageManager.INSTALL_SUCCEEDED) {
7162 return;
7163 }
7164
7165 mRet = targetArgs.doPreInstall(mRet);
7166 if (mRet != PackageManager.INSTALL_SUCCEEDED) {
7167 return;
7168 }
7169
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007170 if (DEBUG_SD_INSTALL) {
7171 StringBuilder builder = new StringBuilder();
7172 if (srcArgs != null) {
7173 builder.append("src: ");
7174 builder.append(srcArgs.getCodePath());
7175 }
7176 if (targetArgs != null) {
7177 builder.append(" target : ");
7178 builder.append(targetArgs.getCodePath());
7179 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08007180 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007181 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007182 }
7183
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007184 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007185 void handleReturnCode() {
Kenny Root6dceb882012-04-12 14:23:49 -07007186 targetArgs.doPostInstall(mRet, uid);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08007187 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
7188 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
7189 currentStatus = PackageManager.MOVE_SUCCEEDED;
7190 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
7191 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
7192 }
7193 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007194 }
7195
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007196 @Override
7197 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007198 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007199 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007200 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08007201
Kenny Root6dceb882012-04-12 14:23:49 -07007202 /**
7203 * Used during creation of InstallArgs
7204 *
7205 * @param flags package installation flags
7206 * @return true if should be installed on external storage
7207 */
7208 private static boolean installOnSd(int flags) {
7209 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
7210 return false;
7211 }
7212 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
7213 return true;
7214 }
7215 return false;
7216 }
7217
7218 /**
7219 * Used during creation of InstallArgs
7220 *
7221 * @param flags package installation flags
7222 * @return true if should be installed as forward locked
7223 */
7224 private static boolean installForwardLocked(int flags) {
7225 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
7226 }
7227
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08007228 private InstallArgs createInstallArgs(InstallParams params) {
Kenny Root6dceb882012-04-12 14:23:49 -07007229 if (installOnSd(params.flags) || params.isForwardLocked()) {
7230 return new AsecInstallArgs(params);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08007231 } else {
7232 return new FileInstallArgs(params);
7233 }
7234 }
7235
Kenny Root85387d72010-08-26 10:13:11 -07007236 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
7237 String nativeLibraryPath) {
Kenny Root84e35ea2012-06-06 16:05:05 -07007238 final boolean isInAsec;
7239 if (installOnSd(flags)) {
7240 /* Apps on SD card are always in ASEC containers. */
7241 isInAsec = true;
7242 } else if (installForwardLocked(flags)
7243 && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
7244 /*
7245 * Forward-locked apps are only in ASEC containers if they're the
7246 * new style
7247 */
7248 isInAsec = true;
7249 } else {
7250 isInAsec = false;
7251 }
7252
7253 if (isInAsec) {
Kenny Root6dceb882012-04-12 14:23:49 -07007254 return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
Kenny Rootbf023582012-05-02 16:56:15 -07007255 installOnSd(flags), installForwardLocked(flags));
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08007256 } else {
Kenny Root85387d72010-08-26 10:13:11 -07007257 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08007258 }
7259 }
7260
Kenny Root85387d72010-08-26 10:13:11 -07007261 // Used by package mover
7262 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Kenny Root6dceb882012-04-12 14:23:49 -07007263 if (installOnSd(flags) || installForwardLocked(flags)) {
Kenny Rootbf023582012-05-02 16:56:15 -07007264 String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
7265 + AsecInstallArgs.RES_FILE_NAME);
7266 return new AsecInstallArgs(packageURI, cid, installOnSd(flags),
7267 installForwardLocked(flags));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007268 } else {
Kenny Root85387d72010-08-26 10:13:11 -07007269 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007270 }
7271 }
7272
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007273 static abstract class InstallArgs {
7274 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007275 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007276 final int flags;
7277 final Uri packageURI;
7278 final String installerPackageName;
Kenny Root5ab21572011-07-27 11:11:19 -07007279 final ManifestDigest manifestDigest;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007280 final UserHandle user;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007281
Kenny Root5ab21572011-07-27 11:11:19 -07007282 InstallArgs(Uri packageURI, IPackageInstallObserver observer, int flags,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007283 String installerPackageName, ManifestDigest manifestDigest,
7284 UserHandle user) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007285 this.packageURI = packageURI;
7286 this.flags = flags;
7287 this.observer = observer;
7288 this.installerPackageName = installerPackageName;
Kenny Root5ab21572011-07-27 11:11:19 -07007289 this.manifestDigest = manifestDigest;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007290 this.user = user;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007291 }
7292
7293 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007294 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007295 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007296 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Kenny Root6dceb882012-04-12 14:23:49 -07007297
7298 abstract int doPostInstall(int status, int uid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007299 abstract String getCodePath();
7300 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07007301 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007302 // Need installer lock especially for dex file removal.
7303 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007304 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08007305 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Kenny Root6dceb882012-04-12 14:23:49 -07007306
Kenny Rootbf023582012-05-02 16:56:15 -07007307 /**
7308 * Called before the source arguments are copied. This is used mostly
7309 * for MoveParams when it needs to read the source file to put it in the
7310 * destination.
7311 */
7312 int doPreCopy() {
7313 return PackageManager.INSTALL_SUCCEEDED;
7314 }
7315
7316 /**
7317 * Called after the source arguments are copied. This is used mostly for
7318 * MoveParams when it needs to read the source file to put it in the
7319 * destination.
7320 *
7321 * @return
7322 */
7323 int doPostCopy(int uid) {
7324 return PackageManager.INSTALL_SUCCEEDED;
7325 }
7326
Kenny Root6dceb882012-04-12 14:23:49 -07007327 protected boolean isFwdLocked() {
7328 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
7329 }
rich canningsd55deb02012-10-02 14:53:08 -07007330
7331 UserHandle getUser() {
7332 return user;
7333 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007334 }
7335
7336 class FileInstallArgs extends InstallArgs {
7337 File installDir;
7338 String codeFileName;
7339 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07007340 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007341 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007342
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08007343 FileInstallArgs(InstallParams params) {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07007344 super(params.getPackageUri(), params.observer, params.flags,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007345 params.installerPackageName, params.getManifestDigest(),
7346 params.getUser());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007347 }
7348
Kenny Root85387d72010-08-26 10:13:11 -07007349 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007350 super(null, null, 0, null, null, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007351 File codeFile = new File(fullCodePath);
7352 installDir = codeFile.getParentFile();
7353 codeFileName = fullCodePath;
7354 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07007355 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007356 }
7357
Kenny Root85387d72010-08-26 10:13:11 -07007358 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007359 super(packageURI, null, 0, null, null, null);
Kenny Root85387d72010-08-26 10:13:11 -07007360 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007361 String apkName = getNextCodePath(null, pkgName, ".apk");
7362 codeFileName = new File(installDir, apkName + ".apk").getPath();
7363 resourceFileName = getResourcePathFromCodePath();
Kenny Rootddbe50d2012-09-06 13:18:37 -07007364 libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007365 }
7366
Kenny Root11128572010-10-11 10:51:32 -07007367 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
Kenny Root62e1b4e2011-03-14 17:13:39 -07007368 final long lowThreshold;
7369
7370 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
7371 .getService(DeviceStorageMonitorService.SERVICE);
7372 if (dsm == null) {
7373 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
7374 lowThreshold = 0L;
7375 } else {
7376 if (dsm.isMemoryLow()) {
7377 Log.w(TAG, "Memory is reported as being too low; aborting package install");
7378 return false;
7379 }
7380
7381 lowThreshold = dsm.getMemoryLowThreshold();
7382 }
7383
Kenny Root11128572010-10-11 10:51:32 -07007384 try {
7385 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
7386 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root6dceb882012-04-12 14:23:49 -07007387 return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
Kenny Root11128572010-10-11 10:51:32 -07007388 } finally {
7389 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
7390 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08007391 }
7392
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08007393 String getCodePath() {
7394 return codeFileName;
7395 }
7396
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007397 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07007398 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007399 codeFileName = createTempPackageFile(installDir).getPath();
7400 resourceFileName = getResourcePathFromCodePath();
Kenny Rootddbe50d2012-09-06 13:18:37 -07007401 libraryPath = getLibraryPathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007402 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007403 }
7404
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007405 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007406 if (temp) {
7407 // Generate temp file name
7408 createCopyFile();
7409 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007410 // Get a ParcelFileDescriptor to write to the output file
7411 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007412 if (!created) {
7413 try {
7414 codeFile.createNewFile();
7415 // Set permissions
7416 if (!setPermissions()) {
7417 // Failed setting permissions.
7418 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7419 }
7420 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007421 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007422 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7423 }
7424 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007425 ParcelFileDescriptor out = null;
7426 try {
Kenny Root85387d72010-08-26 10:13:11 -07007427 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007428 } catch (FileNotFoundException e) {
Kenny Rootf5121a92011-08-10 16:23:32 -07007429 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007430 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7431 }
7432 // Copy the resource now
7433 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7434 try {
Kenny Root11128572010-10-11 10:51:32 -07007435 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
7436 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07007437 ret = imcs.copyResource(packageURI, null, out);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007438 } finally {
Kenny Root2782a472012-04-14 21:48:21 -07007439 IoUtils.closeQuietly(out);
Kenny Root11128572010-10-11 10:51:32 -07007440 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007441 }
Kenny Root85387d72010-08-26 10:13:11 -07007442
Kenny Root2782a472012-04-14 21:48:21 -07007443 if (isFwdLocked()) {
7444 final File destResourceFile = new File(getResourcePath());
7445
7446 // Copy the public files
7447 try {
7448 PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
7449 } catch (IOException e) {
7450 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
7451 + " forward-locked app.");
7452 destResourceFile.delete();
7453 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7454 }
7455 }
Kenny Rootddbe50d2012-09-06 13:18:37 -07007456
7457 final File nativeLibraryFile = new File(getNativeLibraryPath());
7458 Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
7459 if (nativeLibraryFile.exists()) {
7460 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
7461 nativeLibraryFile.delete();
7462 }
7463 try {
7464 int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile);
7465 if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
7466 return copyRet;
7467 }
7468 } catch (IOException e) {
7469 Slog.e(TAG, "Copying native libraries failed", e);
7470 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
7471 }
7472
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007473 return ret;
7474 }
7475
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007476 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007477 if (status != PackageManager.INSTALL_SUCCEEDED) {
7478 cleanUp();
7479 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007480 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007481 }
7482
7483 boolean doRename(int status, final String pkgName, String oldCodePath) {
7484 if (status != PackageManager.INSTALL_SUCCEEDED) {
7485 cleanUp();
7486 return false;
7487 } else {
Kenny Root2782a472012-04-14 21:48:21 -07007488 final File oldCodeFile = new File(getCodePath());
7489 final File oldResourceFile = new File(getResourcePath());
Kenny Rootddbe50d2012-09-06 13:18:37 -07007490 final File oldLibraryFile = new File(getNativeLibraryPath());
Kenny Root2782a472012-04-14 21:48:21 -07007491
7492 // Rename APK file based on packageName
7493 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
7494 final File newCodeFile = new File(installDir, apkName + ".apk");
7495 if (!oldCodeFile.renameTo(newCodeFile)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007496 return false;
7497 }
Kenny Root2782a472012-04-14 21:48:21 -07007498 codeFileName = newCodeFile.getPath();
7499
7500 // Rename public resource file if it's forward-locked.
7501 final File newResFile = new File(getResourcePathFromCodePath());
7502 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
7503 return false;
7504 }
Kenny Rootddbe50d2012-09-06 13:18:37 -07007505 resourceFileName = newResFile.getPath();
7506
7507 // Rename library path
7508 final File newLibraryFile = new File(getLibraryPathFromCodePath());
7509 if (newLibraryFile.exists()) {
7510 NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
7511 newLibraryFile.delete();
7512 }
7513 if (!oldLibraryFile.renameTo(newLibraryFile)) {
7514 Slog.e(TAG, "Cannot rename native library directory "
7515 + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
7516 return false;
7517 }
7518 libraryPath = newLibraryFile.getPath();
Kenny Root2782a472012-04-14 21:48:21 -07007519
7520 // Attempt to set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007521 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007522 return false;
7523 }
Kenny Root2782a472012-04-14 21:48:21 -07007524
rpcraig554cb0c2012-07-05 06:41:43 -04007525 if (!SELinux.restorecon(newCodeFile)) {
7526 return false;
7527 }
7528
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007529 return true;
7530 }
7531 }
7532
Kenny Root6dceb882012-04-12 14:23:49 -07007533 int doPostInstall(int status, int uid) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007534 if (status != PackageManager.INSTALL_SUCCEEDED) {
7535 cleanUp();
7536 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007537 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007538 }
7539
7540 String getResourcePath() {
7541 return resourceFileName;
7542 }
7543
Kenny Root2782a472012-04-14 21:48:21 -07007544 private String getResourcePathFromCodePath() {
7545 final String codePath = getCodePath();
7546 if (isFwdLocked()) {
7547 final StringBuilder sb = new StringBuilder();
7548
7549 sb.append(mAppInstallDir.getPath());
7550 sb.append('/');
7551 sb.append(getApkName(codePath));
7552 sb.append(".zip");
7553
7554 /*
7555 * If our APK is a temporary file, mark the resource as a
7556 * temporary file as well so it can be cleaned up after
7557 * catastrophic failure.
7558 */
7559 if (codePath.endsWith(".tmp")) {
7560 sb.append(".tmp");
7561 }
7562
7563 return sb.toString();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007564 } else {
7565 return codePath;
7566 }
7567 }
7568
Kenny Rootddbe50d2012-09-06 13:18:37 -07007569 private String getLibraryPathFromCodePath() {
7570 return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
7571 }
7572
Kenny Root85387d72010-08-26 10:13:11 -07007573 @Override
7574 String getNativeLibraryPath() {
Kenny Rootddbe50d2012-09-06 13:18:37 -07007575 if (libraryPath == null) {
7576 libraryPath = getLibraryPathFromCodePath();
7577 }
Kenny Root85387d72010-08-26 10:13:11 -07007578 return libraryPath;
7579 }
7580
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007581 private boolean cleanUp() {
7582 boolean ret = true;
7583 String sourceDir = getCodePath();
7584 String publicSourceDir = getResourcePath();
7585 if (sourceDir != null) {
7586 File sourceFile = new File(sourceDir);
7587 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007588 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007589 ret = false;
7590 }
7591 // Delete application's code and resources
7592 sourceFile.delete();
7593 }
7594 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
7595 final File publicSourceFile = new File(publicSourceDir);
7596 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007597 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007598 }
7599 if (publicSourceFile.exists()) {
7600 publicSourceFile.delete();
7601 }
7602 }
Kenny Rootddbe50d2012-09-06 13:18:37 -07007603
7604 if (libraryPath != null) {
7605 File nativeLibraryFile = new File(libraryPath);
7606 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
7607 if (!nativeLibraryFile.delete()) {
7608 Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
7609 }
7610 }
7611
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007612 return ret;
7613 }
7614
7615 void cleanUpResourcesLI() {
7616 String sourceDir = getCodePath();
Jeff Brown5d6d90f2011-07-11 13:04:53 -07007617 if (cleanUp()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007618 int retCode = mInstaller.rmdex(sourceDir);
7619 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007620 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007621 + " at location "
7622 + sourceDir + ", retcode=" + retCode);
7623 // we don't consider this to be a failure of the core package deletion
7624 }
7625 }
7626 }
7627
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007628 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007629 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07007630 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007631 final int filePermissions =
7632 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
7633 |FileUtils.S_IROTH;
7634 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
7635 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007636 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007637 getCodePath()
7638 + ". The return code was: " + retCode);
7639 // TODO Define new internal error
7640 return false;
7641 }
7642 return true;
7643 }
7644 return true;
7645 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007646
7647 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07007648 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007649 cleanUpResourcesLI();
7650 return true;
7651 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007652 }
7653
Kenny Root51a573c2012-05-17 13:30:28 -07007654 private boolean isAsecExternal(String cid) {
7655 final String asecPath = PackageHelper.getSdFilesystem(cid);
7656 return !asecPath.startsWith(mAsecInternalPath);
7657 }
7658
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07007659 /**
7660 * Extract the MountService "container ID" from the full code path of an
7661 * .apk.
7662 */
7663 static String cidFromCodePath(String fullCodePath) {
7664 int eidx = fullCodePath.lastIndexOf("/");
7665 String subStr1 = fullCodePath.substring(0, eidx);
7666 int sidx = subStr1.lastIndexOf("/");
7667 return subStr1.substring(sidx+1, eidx);
7668 }
7669
Kenny Root6dceb882012-04-12 14:23:49 -07007670 class AsecInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007671 static final String RES_FILE_NAME = "pkg.apk";
Kenny Root6dceb882012-04-12 14:23:49 -07007672 static final String PUBLIC_RES_FILE_NAME = "res.zip";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007673
Kenny Root85387d72010-08-26 10:13:11 -07007674 String cid;
7675 String packagePath;
Kenny Root6dceb882012-04-12 14:23:49 -07007676 String resourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07007677 String libraryPath;
7678
Kenny Root6dceb882012-04-12 14:23:49 -07007679 AsecInstallArgs(InstallParams params) {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -07007680 super(params.getPackageUri(), params.observer, params.flags,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007681 params.installerPackageName, params.getManifestDigest(),
7682 params.getUser());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007683 }
7684
Kenny Root6dceb882012-04-12 14:23:49 -07007685 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
Kenny Rootbf023582012-05-02 16:56:15 -07007686 boolean isExternal, boolean isForwardLocked) {
7687 super(null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007688 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
7689 null, null, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007690 // Extract cid from fullCodePath
7691 int eidx = fullCodePath.lastIndexOf("/");
7692 String subStr1 = fullCodePath.substring(0, eidx);
7693 int sidx = subStr1.lastIndexOf("/");
7694 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07007695 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007696 }
7697
Kenny Rootc7a89992012-06-05 15:13:17 -07007698 AsecInstallArgs(String cid, boolean isForwardLocked) {
7699 super(null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007700 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
7701 null, null, null);
Dianne Hackbornaa77de12010-05-14 22:33:54 -07007702 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07007703 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007704 }
7705
Kenny Rootbf023582012-05-02 16:56:15 -07007706 AsecInstallArgs(Uri packageURI, String cid, boolean isExternal, boolean isForwardLocked) {
7707 super(packageURI, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
Dianne Hackborn7767eac2012-08-23 18:25:40 -07007708 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
7709 null, null, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007710 this.cid = cid;
7711 }
7712
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007713 void createCopyFile() {
7714 cid = getTempContainerId();
7715 }
7716
Kenny Root11128572010-10-11 10:51:32 -07007717 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
7718 try {
7719 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
7720 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root6dceb882012-04-12 14:23:49 -07007721 return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
Kenny Root11128572010-10-11 10:51:32 -07007722 } finally {
7723 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
7724 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08007725 }
7726
Kenny Root6dceb882012-04-12 14:23:49 -07007727 private final boolean isExternal() {
7728 return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
7729 }
7730
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007731 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007732 if (temp) {
7733 createCopyFile();
Kenny Rootf5121a92011-08-10 16:23:32 -07007734 } else {
7735 /*
7736 * Pre-emptively destroy the container since it's destroyed if
7737 * copying fails due to it existing anyway.
7738 */
7739 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007740 }
Kenny Root11128572010-10-11 10:51:32 -07007741
7742 final String newCachePath;
7743 try {
7744 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
7745 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root6dceb882012-04-12 14:23:49 -07007746 newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
7747 RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
Kenny Root11128572010-10-11 10:51:32 -07007748 } finally {
7749 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
7750 }
7751
Kenny Root85387d72010-08-26 10:13:11 -07007752 if (newCachePath != null) {
7753 setCachePath(newCachePath);
7754 return PackageManager.INSTALL_SUCCEEDED;
7755 } else {
7756 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7757 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007758 }
7759
7760 @Override
7761 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07007762 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007763 }
7764
7765 @Override
7766 String getResourcePath() {
Kenny Root6dceb882012-04-12 14:23:49 -07007767 return resourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07007768 }
7769
7770 @Override
7771 String getNativeLibraryPath() {
7772 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007773 }
7774
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007775 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007776 if (status != PackageManager.INSTALL_SUCCEEDED) {
7777 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08007778 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007779 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08007780 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007781 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07007782 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
7783 Process.SYSTEM_UID);
7784 if (newCachePath != null) {
7785 setCachePath(newCachePath);
7786 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007787 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7788 }
7789 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007790 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007791 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007792 }
7793
7794 boolean doRename(int status, final String pkgName,
7795 String oldCodePath) {
7796 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007797 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007798 if (PackageHelper.isContainerMounted(cid)) {
7799 // Unmount the container
7800 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007801 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007802 return false;
7803 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007804 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007805 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07007806 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
7807 " which might be stale. Will try to clean up.");
7808 // Clean up the stale container and proceed to recreate.
7809 if (!PackageHelper.destroySdDir(newCacheId)) {
7810 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
7811 return false;
7812 }
7813 // Successfully cleaned up stale container. Try to rename again.
7814 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
7815 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
7816 + " inspite of cleaning it up.");
7817 return false;
7818 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007819 }
7820 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007821 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007822 newCachePath = PackageHelper.mountSdDir(newCacheId,
7823 getEncryptKey(), Process.SYSTEM_UID);
7824 } else {
7825 newCachePath = PackageHelper.getSdDir(newCacheId);
7826 }
7827 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007828 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007829 return false;
7830 }
7831 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07007832 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007833 " at new path: " + newCachePath);
7834 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07007835 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08007836 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007837 }
7838
Kenny Root85387d72010-08-26 10:13:11 -07007839 private void setCachePath(String newCachePath) {
7840 File cachePath = new File(newCachePath);
7841 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
7842 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
Kenny Root6dceb882012-04-12 14:23:49 -07007843
7844 if (isFwdLocked()) {
7845 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
7846 } else {
7847 resourcePath = packagePath;
7848 }
Kenny Root85387d72010-08-26 10:13:11 -07007849 }
7850
Kenny Root6dceb882012-04-12 14:23:49 -07007851 int doPostInstall(int status, int uid) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007852 if (status != PackageManager.INSTALL_SUCCEEDED) {
7853 cleanUp();
7854 } else {
Kenny Rootbf023582012-05-02 16:56:15 -07007855 final int groupOwner;
7856 final String protectedFile;
7857 if (isFwdLocked()) {
Kenny Roote091f222012-09-11 15:01:26 -07007858 groupOwner = UserHandle.getSharedAppGid(uid);
Kenny Rootbf023582012-05-02 16:56:15 -07007859 protectedFile = RES_FILE_NAME;
7860 } else {
7861 groupOwner = -1;
7862 protectedFile = null;
7863 }
7864
Kenny Root6dceb882012-04-12 14:23:49 -07007865 if (uid < Process.FIRST_APPLICATION_UID
Kenny Rootbf023582012-05-02 16:56:15 -07007866 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
Kenny Root6dceb882012-04-12 14:23:49 -07007867 Slog.e(TAG, "Failed to finalize " + cid);
7868 PackageHelper.destroySdDir(cid);
7869 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7870 }
7871
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08007872 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007873 if (!mounted) {
Kenny Root6dceb882012-04-12 14:23:49 -07007874 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007875 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007876 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007877 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007878 }
7879
7880 private void cleanUp() {
Kenny Root6dceb882012-04-12 14:23:49 -07007881 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
7882
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007883 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08007884 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007885 }
7886
7887 void cleanUpResourcesLI() {
7888 String sourceFile = getCodePath();
7889 // Remove dex file
Jeff Brown5d6d90f2011-07-11 13:04:53 -07007890 int retCode = mInstaller.rmdex(sourceFile);
7891 if (retCode < 0) {
7892 Slog.w(TAG, "Couldn't remove dex file for package: "
7893 + " at location "
7894 + sourceFile.toString() + ", retcode=" + retCode);
7895 // we don't consider this to be a failure of the core package deletion
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007896 }
7897 cleanUp();
7898 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007899
7900 boolean matchContainer(String app) {
7901 if (cid.startsWith(app)) {
7902 return true;
7903 }
7904 return false;
7905 }
7906
7907 String getPackageName() {
Kenny Rootc7a89992012-06-05 15:13:17 -07007908 return getAsecPackageName(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007909 }
7910
7911 boolean doPostDeleteLI(boolean delete) {
7912 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08007913 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007914 if (mounted) {
7915 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08007916 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007917 }
7918 if (ret && delete) {
7919 cleanUpResourcesLI();
7920 }
7921 return ret;
7922 }
Kenny Rootbf023582012-05-02 16:56:15 -07007923
7924 @Override
7925 int doPreCopy() {
7926 if (isFwdLocked()) {
7927 if (!PackageHelper.fixSdPermissions(cid,
7928 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
7929 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7930 }
7931 }
7932
7933 return PackageManager.INSTALL_SUCCEEDED;
7934 }
7935
7936 @Override
7937 int doPostCopy(int uid) {
7938 if (isFwdLocked()) {
Kenny Rootbf023582012-05-02 16:56:15 -07007939 if (uid < Process.FIRST_APPLICATION_UID
Kenny Roote091f222012-09-11 15:01:26 -07007940 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
7941 RES_FILE_NAME)) {
Kenny Rootbf023582012-05-02 16:56:15 -07007942 Slog.e(TAG, "Failed to finalize " + cid);
7943 PackageHelper.destroySdDir(cid);
7944 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7945 }
7946 }
7947
7948 return PackageManager.INSTALL_SUCCEEDED;
7949 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007950 };
7951
Kenny Rootc7a89992012-06-05 15:13:17 -07007952 static String getAsecPackageName(String packageCid) {
7953 int idx = packageCid.lastIndexOf("-");
7954 if (idx == -1) {
7955 return packageCid;
7956 }
7957 return packageCid.substring(0, idx);
7958 }
7959
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007960 // Utility method used to create code paths based on package name and available index.
7961 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
7962 String idxStr = "";
7963 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007964 // Fall back to default value of idx=1 if prefix is not
7965 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007966 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00007967 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007968 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00007969 if (subStr.endsWith(suffix)) {
7970 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007971 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007972 // If oldCodePath already contains prefix find out the
7973 // ending index to either increment or decrement.
7974 int sidx = subStr.lastIndexOf(prefix);
7975 if (sidx != -1) {
7976 subStr = subStr.substring(sidx + prefix.length());
7977 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007978 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
7979 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007980 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007981 try {
7982 idx = Integer.parseInt(subStr);
7983 if (idx <= 1) {
7984 idx++;
7985 } else {
7986 idx--;
7987 }
7988 } catch(NumberFormatException e) {
7989 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007990 }
7991 }
7992 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007993 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007994 return prefix + idxStr;
7995 }
7996
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007997 // Utility method used to ignore ADD/REMOVE events
7998 // by directory observer.
7999 private static boolean ignoreCodePath(String fullPathStr) {
8000 String apkName = getApkName(fullPathStr);
8001 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
8002 if (idx != -1 && ((idx+1) < apkName.length())) {
8003 // Make sure the package ends with a numeral
8004 String version = apkName.substring(idx+1);
8005 try {
8006 Integer.parseInt(version);
8007 return true;
8008 } catch (NumberFormatException e) {}
8009 }
8010 return false;
8011 }
8012
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008013 // Utility method that returns the relative package path with respect
8014 // to the installation directory. Like say for /data/data/com.test-1.apk
8015 // string com.test-1 is returned.
8016 static String getApkName(String codePath) {
8017 if (codePath == null) {
8018 return null;
8019 }
8020 int sidx = codePath.lastIndexOf("/");
8021 int eidx = codePath.lastIndexOf(".");
8022 if (eidx == -1) {
8023 eidx = codePath.length();
8024 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008025 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008026 return null;
8027 }
8028 return codePath.substring(sidx+1, eidx);
8029 }
8030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008031 class PackageInstalledInfo {
8032 String name;
8033 int uid;
Dianne Hackborn786b4402012-08-27 15:14:02 -07008034 // The set of users that originally had this package installed.
8035 int[] origUsers;
8036 // The set of users that now have this package installed.
8037 int[] newUsers;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008038 PackageParser.Package pkg;
8039 int returnCode;
8040 PackageRemovedInfo removedInfo;
8041 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008043 /*
8044 * Install a non-existing package.
8045 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008046 private void installNewPackageLI(PackageParser.Package pkg,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008047 int parseFlags, int scanMode, UserHandle user,
Jacek Surazski65e13172009-04-28 15:26:38 +02008048 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008049 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008050 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08008051
Dianne Hackbornc895be72013-03-11 17:48:43 -07008052 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
Dave Burke383fa182012-10-23 23:12:19 -07008053 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008054 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07008055 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
8056 // A package with the same name is already installed, though
8057 // it has been renamed to an older name. The package we
8058 // are trying to install should be installed as an update to
8059 // the existing one, but that has not been requested, so bail.
8060 Slog.w(TAG, "Attempt to re-install " + pkgName
8061 + " without first uninstalling package running as "
8062 + mSettings.mRenamedPackages.get(pkgName));
8063 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8064 return;
8065 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008066 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008067 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008068 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008069 + " without first uninstalling.");
8070 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8071 return;
8072 }
8073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008074 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008075 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008076 System.currentTimeMillis(), user);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008077 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008078 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008079 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
8080 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
8081 }
8082 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008083 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02008084 installerPackageName,
Christopher Tateacee6e92013-05-14 16:11:44 -07008085 null, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008086 res);
8087 // delete the partially installed application. the data directory will have to be
8088 // restored if it was already existing
8089 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
8090 // remove package from internal structures. Note that we want deletePackageX to
8091 // delete the package data and cache directories that it created in
8092 // scanPackageLocked, unless those directories existed before we even tried to
8093 // install.
Christopher Tateacee6e92013-05-14 16:11:44 -07008094 deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008095 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008096 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008097 }
8098 }
8099 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008100
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008101 private void replacePackageLI(PackageParser.Package pkg,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008102 int parseFlags, int scanMode, UserHandle user,
Jacek Surazski65e13172009-04-28 15:26:38 +02008103 String installerPackageName, PackageInstalledInfo res) {
8104
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008105 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008106 String pkgName = pkg.packageName;
Christopher Tateacee6e92013-05-14 16:11:44 -07008107 int[] allUsers;
8108 boolean[] perUserInstalled;
8109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008110 // First find the old package info and check signatures
8111 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008112 oldPackage = mPackages.get(pkgName);
Dianne Hackbornc895be72013-03-11 17:48:43 -07008113 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
Kenny Root447106f2011-03-23 11:00:15 -07008114 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07008115 != PackageManager.SIGNATURE_MATCH) {
Kenny Root8c11f1d2012-04-14 12:10:38 -07008116 Slog.w(TAG, "New package has a different signature: " + pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008117 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
8118 return;
8119 }
Christopher Tateacee6e92013-05-14 16:11:44 -07008120
8121 // In case of rollback, remember per-user/profile install state
8122 PackageSetting ps = mSettings.mPackages.get(pkgName);
8123 allUsers = sUserManager.getUserIds();
8124 perUserInstalled = new boolean[allUsers.length];
8125 for (int i = 0; i < allUsers.length; i++) {
Dianne Hackborn2c44c742013-05-17 12:07:21 -07008126 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
Christopher Tateacee6e92013-05-14 16:11:44 -07008127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008128 }
Kenny Root85387d72010-08-26 10:13:11 -07008129 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008130 if (sysPkg) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008131 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
Christopher Tateacee6e92013-05-14 16:11:44 -07008132 user, allUsers, perUserInstalled, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008133 } else {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008134 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
Christopher Tateacee6e92013-05-14 16:11:44 -07008135 user, allUsers, perUserInstalled, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008136 }
8137 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008139 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008140 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
Christopher Tateacee6e92013-05-14 16:11:44 -07008141 int[] allUsers, boolean[] perUserInstalled,
Jacek Surazski65e13172009-04-28 15:26:38 +02008142 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008143 PackageParser.Package newPackage = null;
8144 String pkgName = deletedPackage.packageName;
8145 boolean deletedPkg = true;
8146 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008147
Dianne Hackbornc895be72013-03-11 17:48:43 -07008148 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
8149 + deletedPackage);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008150 long origUpdateTime;
8151 if (pkg.mExtras != null) {
8152 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
8153 } else {
8154 origUpdateTime = 0;
8155 }
8156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008157 // First delete the existing package while retaining the data directory
Christopher Tateacee6e92013-05-14 16:11:44 -07008158 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008159 res.removedInfo, true)) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008160 // If the existing package wasn't successfully deleted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008161 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
8162 deletedPkg = false;
8163 } else {
8164 // Successfully deleted the old package. Now proceed with re-installation
8165 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008166 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008167 System.currentTimeMillis(), user);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008168 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008169 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008170 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
8171 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08008172 }
8173 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008174 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02008175 installerPackageName,
Christopher Tateacee6e92013-05-14 16:11:44 -07008176 allUsers, perUserInstalled,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008177 res);
8178 updatedSettings = true;
8179 }
8180 }
8181
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008182 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008183 // remove package from internal structures. Note that we want deletePackageX to
8184 // delete the package data and cache directories that it created in
8185 // scanPackageLocked, unless those directories existed before we even tried to
8186 // install.
8187 if(updatedSettings) {
Dianne Hackbornc895be72013-03-11 17:48:43 -07008188 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008189 deletePackageLI(
Christopher Tateacee6e92013-05-14 16:11:44 -07008190 pkgName, null, true, allUsers, perUserInstalled,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008191 PackageManager.DELETE_KEEP_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008192 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008193 }
8194 // Since we failed to install the new package we need to restore the old
8195 // package that we deleted.
8196 if(deletedPkg) {
Dianne Hackbornc895be72013-03-11 17:48:43 -07008197 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07008198 File restoreFile = new File(deletedPackage.mPath);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008199 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008200 boolean oldOnSd = isExternal(deletedPackage);
8201 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
8202 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
8203 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008204 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
8205 | SCAN_UPDATE_TIME;
8206 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
Dianne Hackborn786b4402012-08-27 15:14:02 -07008207 origUpdateTime, null) == null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008208 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
8209 return;
8210 }
8211 // Restore of old package succeeded. Update permissions.
Kenny Root447106f2011-03-23 11:00:15 -07008212 // writer
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008213 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07008214 updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
Dianne Hackborne639da72012-02-21 15:11:13 -08008215 UPDATE_PERMISSIONS_ALL);
Kenny Root447106f2011-03-23 11:00:15 -07008216 // can downgrade to reader
8217 mSettings.writeLPr();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008218 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008219 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008220 }
8221 }
8222 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008224 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008225 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
Christopher Tateacee6e92013-05-14 16:11:44 -07008226 int[] allUsers, boolean[] perUserInstalled,
Jacek Surazski65e13172009-04-28 15:26:38 +02008227 String installerPackageName, PackageInstalledInfo res) {
Dianne Hackbornc895be72013-03-11 17:48:43 -07008228 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
8229 + ", old=" + deletedPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008230 PackageParser.Package newPackage = null;
8231 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008232 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008233 PackageParser.PARSE_IS_SYSTEM;
8234 String packageName = deletedPackage.packageName;
8235 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
8236 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008237 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008238 return;
8239 }
8240 PackageParser.Package oldPkg;
8241 PackageSetting oldPkgSetting;
Kenny Root447106f2011-03-23 11:00:15 -07008242 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008243 synchronized (mPackages) {
8244 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008245 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008246 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
8247 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008248 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008249 return;
8250 }
8251 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008252
8253 killApplication(packageName, oldPkg.applicationInfo.uid);
8254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008255 res.removedInfo.uid = oldPkg.applicationInfo.uid;
8256 res.removedInfo.removedPackage = packageName;
8257 // Remove existing system package
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008258 removePackageLI(oldPkgSetting, true);
Kenny Root447106f2011-03-23 11:00:15 -07008259 // writer
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08008260 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07008261 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008262 // We didn't need to disable the .apk as a current system package,
8263 // which means we are replacing another update that is already
8264 // installed. We need to make sure to delete the older one's .apk.
Kenny Root6dceb882012-04-12 14:23:49 -07008265 res.removedInfo.args = createInstallArgs(0,
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008266 deletedPackage.applicationInfo.sourceDir,
8267 deletedPackage.applicationInfo.publicSourceDir,
8268 deletedPackage.applicationInfo.nativeLibraryDir);
8269 } else {
8270 res.removedInfo.args = null;
8271 }
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08008272 }
8273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008274 // Successfully disabled the old package. Now proceed with re-installation
8275 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
8276 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008277 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008278 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008279 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008280 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
8281 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
8282 }
8283 } else {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008284 if (newPackage.mExtras != null) {
8285 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
8286 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
8287 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
8288 }
Christopher Tateacee6e92013-05-14 16:11:44 -07008289 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008290 updatedSettings = true;
8291 }
8292
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008293 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008294 // Re installation failed. Restore old information
8295 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07008296 if (newPackage != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008297 removeInstalledPackageLI(newPackage, true);
Dianne Hackborn62da8462009-05-13 15:06:13 -07008298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008299 // Add back the old system package
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008300 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008301 // Restore the old system information in Settings
8302 synchronized(mPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008303 if (updatedSettings) {
Kenny Root447106f2011-03-23 11:00:15 -07008304 mSettings.enableSystemPackageLPw(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02008305 mSettings.setInstallerPackageName(packageName,
8306 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008307 }
Kenny Root447106f2011-03-23 11:00:15 -07008308 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008309 }
8310 }
8311 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008312
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08008313 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008314 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08008315 int retCode;
8316 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
8317 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
8318 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07008319 if (mNoDexOpt) {
8320 /*
8321 * If we're in an engineering build, programs are lazily run
8322 * through dexopt. If the .dex file doesn't exist yet, it
8323 * will be created when the program is run next.
8324 */
8325 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
8326 } else {
8327 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
8328 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8329 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08008330 }
8331 }
8332 return PackageManager.INSTALL_SUCCEEDED;
8333 }
8334
Christopher Tateacee6e92013-05-14 16:11:44 -07008335 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
8336 int[] allUsers, boolean[] perUserInstalled,
8337 PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008338 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008339 synchronized (mPackages) {
8340 //write settings. the installStatus will be incomplete at this stage.
8341 //note that the new package setting would have already been
8342 //added to mPackages. It hasn't been persisted yet.
Kenny Rootcf0b38c2011-03-22 14:17:59 -07008343 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
Kenny Root447106f2011-03-23 11:00:15 -07008344 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008345 }
8346
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008347 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08008348 != PackageManager.INSTALL_SUCCEEDED) {
8349 // Discontinue if moving dex files failed.
8350 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008351 }
Kenny Root6dceb882012-04-12 14:23:49 -07008352
Dianne Hackbornc895be72013-03-11 17:48:43 -07008353 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath);
Kenny Root6dceb882012-04-12 14:23:49 -07008354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008355 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07008356 updatePermissionsLPw(newPackage.packageName, newPackage,
Dianne Hackborne639da72012-02-21 15:11:13 -08008357 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
8358 ? UPDATE_PERMISSIONS_ALL : 0));
Christopher Tate32a019d2013-04-04 15:40:04 -07008359 // For system-bundled packages, we assume that installing an upgraded version
8360 // of the package implies that the user actually wants to run that new code,
8361 // so we enable the package.
8362 if (isSystemApp(newPackage)) {
8363 // NB: implicit assumption that system package upgrades apply to all users
8364 if (DEBUG_INSTALL) {
8365 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
8366 }
8367 PackageSetting ps = mSettings.mPackages.get(pkgName);
8368 if (ps != null) {
8369 if (res.origUsers != null) {
8370 for (int userHandle : res.origUsers) {
8371 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
8372 userHandle, installerPackageName);
8373 }
8374 }
Christopher Tateacee6e92013-05-14 16:11:44 -07008375 // Also convey the prior install/uninstall state
8376 if (allUsers != null && perUserInstalled != null) {
8377 for (int i = 0; i < allUsers.length; i++) {
8378 if (DEBUG_INSTALL) {
8379 Slog.d(TAG, " user " + allUsers[i]
8380 + " => " + perUserInstalled[i]);
8381 }
8382 ps.setInstalled(perUserInstalled[i], allUsers[i]);
8383 }
8384 // these install state changes will be persisted in the
8385 // upcoming call to mSettings.writeLPr().
8386 }
Christopher Tate32a019d2013-04-04 15:40:04 -07008387 }
8388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008389 res.name = pkgName;
8390 res.uid = newPackage.applicationInfo.uid;
8391 res.pkg = newPackage;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07008392 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02008393 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008394 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
8395 //to update install status
Kenny Root447106f2011-03-23 11:00:15 -07008396 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008397 }
8398 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008399
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008400 private void installPackageLI(InstallArgs args,
8401 boolean newInstall, PackageInstalledInfo res) {
8402 int pFlags = args.flags;
8403 String installerPackageName = args.installerPackageName;
8404 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008405 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08008406 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008407 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008408 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008409 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07008410 // Result object to be returned
8411 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
8412
Dianne Hackbornc895be72013-03-11 17:48:43 -07008413 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008414 // Retrieve PackageSettings and parse package
Kenny Root6dceb882012-04-12 14:23:49 -07008415 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
8416 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
8417 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008418 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
8419 pp.setSeparateProcesses(mSeparateProcesses);
8420 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
8421 null, mMetrics, parseFlags);
8422 if (pkg == null) {
8423 res.returnCode = pp.getParseError();
8424 return;
8425 }
8426 String pkgName = res.name = pkg.packageName;
8427 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
8428 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
8429 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
8430 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008431 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008432 }
8433 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
8434 res.returnCode = pp.getParseError();
8435 return;
8436 }
Kenny Root5ab21572011-07-27 11:11:19 -07008437
8438 /* If the installer passed in a manifest digest, compare it now. */
8439 if (args.manifestDigest != null) {
8440 if (DEBUG_INSTALL) {
8441 final String parsedManifest = pkg.manifestDigest == null ? "null"
8442 : pkg.manifestDigest.toString();
8443 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
8444 + parsedManifest);
8445 }
8446
8447 if (!args.manifestDigest.equals(pkg.manifestDigest)) {
8448 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
8449 return;
8450 }
8451 } else if (DEBUG_INSTALL) {
8452 final String parsedManifest = pkg.manifestDigest == null
8453 ? "null" : pkg.manifestDigest.toString();
8454 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
8455 }
8456
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008457 // Get rid of all references to package scan path via parser.
8458 pp = null;
8459 String oldCodePath = null;
8460 boolean systemApp = false;
8461 synchronized (mPackages) {
8462 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008463 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8464 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08008465 if (pkg.mOriginalPackages != null
8466 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008467 && mPackages.containsKey(oldName)) {
8468 // This package is derived from an original package,
8469 // and this device has been updating from that original
8470 // name. We must continue using the original name, so
8471 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08008472 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008473 pkgName = pkg.packageName;
8474 replace = true;
Dianne Hackbornc895be72013-03-11 17:48:43 -07008475 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
8476 + oldName + " pkgName=" + pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008477 } else if (mPackages.containsKey(pkgName)) {
8478 // This package, under its official name, already exists
8479 // on the device; we should replace it.
8480 replace = true;
Dianne Hackbornc895be72013-03-11 17:48:43 -07008481 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008482 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008483 }
8484 PackageSetting ps = mSettings.mPackages.get(pkgName);
8485 if (ps != null) {
Dianne Hackbornc895be72013-03-11 17:48:43 -07008486 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008487 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
8488 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8489 systemApp = (ps.pkg.applicationInfo.flags &
8490 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07008491 }
Dianne Hackborn786b4402012-08-27 15:14:02 -07008492 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
Dianne Hackbornade3eca2009-05-11 18:54:45 -07008493 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008494 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008495
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008496 if (systemApp && onSd) {
8497 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008498 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008499 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8500 return;
8501 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008502
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008503 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
8504 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8505 return;
8506 }
8507 // Set application objects path explicitly after the rename
8508 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07008509 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008510 if (replace) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008511 replacePackageLI(pkg, parseFlags, scanMode, args.user,
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008512 installerPackageName, res);
8513 } else {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008514 installNewPackageLI(pkg, parseFlags, scanMode, args.user,
Dianne Hackborn786b4402012-08-27 15:14:02 -07008515 installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008516 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008517 synchronized (mPackages) {
Dianne Hackborn786b4402012-08-27 15:14:02 -07008518 final PackageSetting ps = mSettings.mPackages.get(pkgName);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008519 if (ps != null) {
Dianne Hackborn786b4402012-08-27 15:14:02 -07008520 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008521 }
8522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008523 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008524
Kenny Root85387d72010-08-26 10:13:11 -07008525 private static boolean isForwardLocked(PackageParser.Package pkg) {
8526 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008527 }
8528
Kenny Root88670d82012-05-09 15:47:35 -07008529
8530 private boolean isForwardLocked(PackageSetting ps) {
8531 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
8532 }
8533
Kenny Root85387d72010-08-26 10:13:11 -07008534 private static boolean isExternal(PackageParser.Package pkg) {
8535 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
8536 }
8537
Kenny Root6dceb882012-04-12 14:23:49 -07008538 private static boolean isExternal(PackageSetting ps) {
8539 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
8540 }
8541
Kenny Root85387d72010-08-26 10:13:11 -07008542 private static boolean isSystemApp(PackageParser.Package pkg) {
8543 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
8544 }
8545
Kenny Root502e9a42011-01-10 13:48:15 -08008546 private static boolean isSystemApp(ApplicationInfo info) {
8547 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
8548 }
8549
Kenny Root208d3412012-05-07 19:42:35 -07008550 private static boolean isSystemApp(PackageSetting ps) {
8551 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
8552 }
8553
Nick Kralevich60792852013-04-03 14:12:24 -07008554 private static boolean isUpdatedSystemApp(PackageSetting ps) {
8555 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
8556 }
8557
Kenny Root85387d72010-08-26 10:13:11 -07008558 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
8559 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008560 }
8561
Kenny Root88670d82012-05-09 15:47:35 -07008562 private int packageFlagsToInstallFlags(PackageSetting ps) {
8563 int installFlags = 0;
8564 if (isExternal(ps)) {
8565 installFlags |= PackageManager.INSTALL_EXTERNAL;
8566 }
8567 if (isForwardLocked(ps)) {
8568 installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
8569 }
8570 return installFlags;
8571 }
8572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008573 private void deleteTempPackageFiles() {
Kenny Root0b2fa8c2012-09-14 10:26:16 -07008574 final FilenameFilter filter = new FilenameFilter() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008575 public boolean accept(File dir, String name) {
8576 return name.startsWith("vmdl") && name.endsWith(".tmp");
8577 }
8578 };
Kenny Root0b2fa8c2012-09-14 10:26:16 -07008579 deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
8580 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
8581 }
8582
8583 private static final void deleteTempPackageFilesInDirectory(File directory,
8584 FilenameFilter filter) {
8585 final String[] tmpFilesList = directory.list(filter);
8586 if (tmpFilesList == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008587 return;
8588 }
Kenny Root0b2fa8c2012-09-14 10:26:16 -07008589 for (int i = 0; i < tmpFilesList.length; i++) {
8590 final File tmpFile = new File(directory, tmpFilesList[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008591 tmpFile.delete();
8592 }
8593 }
8594
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008595 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008596 File tmpPackageFile;
8597 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008598 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008599 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008600 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008601 return null;
8602 }
8603 try {
8604 FileUtils.setPermissions(
8605 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
8606 -1, -1);
rpcraig554cb0c2012-07-05 06:41:43 -04008607 if (!SELinux.restorecon(tmpPackageFile)) {
8608 return null;
8609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008610 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008611 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008612 return null;
8613 }
8614 return tmpPackageFile;
8615 }
8616
Amith Yamasani67df64b2012-12-14 12:09:36 -08008617 @Override
8618 public void deletePackageAsUser(final String packageName,
8619 final IPackageDeleteObserver observer,
8620 final int userId, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008621 mContext.enforceCallingOrSelfPermission(
8622 android.Manifest.permission.DELETE_PACKAGES, null);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008623 final int uid = Binder.getCallingUid();
Amith Yamasani67df64b2012-12-14 12:09:36 -08008624 if (UserHandle.getUserId(uid) != userId) {
8625 mContext.enforceCallingPermission(
8626 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8627 "deletePackage for user " + userId);
8628 }
Amith Yamasani71e6c692013-03-24 17:39:28 -07008629 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
Amith Yamasanie4cf7342012-12-17 11:12:09 -08008630 try {
8631 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
8632 } catch (RemoteException re) {
8633 }
8634 return;
8635 }
8636
Dianne Hackbornc895be72013-03-11 17:48:43 -07008637 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -08008638 // Queue up an async operation since the package deletion may take a little while.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008639 mHandler.post(new Runnable() {
8640 public void run() {
8641 mHandler.removeCallbacks(this);
Amith Yamasani67df64b2012-12-14 12:09:36 -08008642 final int returnCode = deletePackageX(packageName, userId, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008643 if (observer != null) {
8644 try {
Kenny Rootc39bb4a2011-02-28 13:27:19 -08008645 observer.packageDeleted(packageName, returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008646 } catch (RemoteException e) {
8647 Log.i(TAG, "Observer no longer exists.");
8648 } //end catch
8649 } //end if
8650 } //end run
8651 });
8652 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008654 /**
8655 * This method is an internal method that could be get invoked either
8656 * to delete an installed package or to clean up a failed installation.
8657 * After deleting an installed package, a broadcast is sent to notify any
8658 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008659 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008660 * installation wouldn't have sent the initial broadcast either
8661 * The key steps in deleting a package are
8662 * deleting the package information in internal structures like mPackages,
8663 * deleting the packages base directories through installd
8664 * updating mSettings to reflect current status
8665 * persisting settings for later use
8666 * sending a broadcast if necessary
8667 */
Amith Yamasani67df64b2012-12-14 12:09:36 -08008668 private int deletePackageX(String packageName, int userId, int flags) {
Kenny Rootc39bb4a2011-02-28 13:27:19 -08008669 final PackageRemovedInfo info = new PackageRemovedInfo();
8670 final boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008671
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08008672 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
8673 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
8674 try {
Amith Yamasani71e6c692013-03-24 17:39:28 -07008675 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
8676 || dpm.isDeviceOwner(packageName))) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008677 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Kenny Rootc39bb4a2011-02-28 13:27:19 -08008678 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08008679 }
8680 } catch (RemoteException e) {
8681 }
Amith Yamasani599dd7c2012-09-14 23:20:08 -07008682
Dianne Hackbornc72fc672012-09-20 13:12:03 -07008683 boolean removedForAllUsers = false;
8684 boolean systemUpdate = false;
Christopher Tateacee6e92013-05-14 16:11:44 -07008685
8686 // for the uninstall-updates case and restricted profiles, remember the per-
8687 // userhandle installed state
8688 int[] allUsers;
8689 boolean[] perUserInstalled;
8690 synchronized (mPackages) {
8691 PackageSetting ps = mSettings.mPackages.get(packageName);
8692 allUsers = sUserManager.getUserIds();
8693 perUserInstalled = new boolean[allUsers.length];
8694 for (int i = 0; i < allUsers.length; i++) {
Dianne Hackborn2c44c742013-05-17 12:07:21 -07008695 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
Christopher Tateacee6e92013-05-14 16:11:44 -07008696 }
8697 }
8698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008699 synchronized (mInstallLock) {
Dianne Hackbornc895be72013-03-11 17:48:43 -07008700 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008701 res = deletePackageLI(packageName,
8702 (flags & PackageManager.DELETE_ALL_USERS) != 0
Amith Yamasani67df64b2012-12-14 12:09:36 -08008703 ? UserHandle.ALL : new UserHandle(userId),
Christopher Tateacee6e92013-05-14 16:11:44 -07008704 true, allUsers, perUserInstalled,
8705 flags | REMOVE_CHATTY, info, true);
Dianne Hackbornc72fc672012-09-20 13:12:03 -07008706 systemUpdate = info.isRemovedPackageSystemUpdate;
8707 if (res && !systemUpdate && mPackages.get(packageName) == null) {
8708 removedForAllUsers = true;
8709 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07008710 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
8711 + " removedForAllUsers=" + removedForAllUsers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008712 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008713
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008714 if (res) {
Dianne Hackbornc72fc672012-09-20 13:12:03 -07008715 info.sendBroadcast(true, systemUpdate, removedForAllUsers);
Romain Guy96f43572009-03-24 20:27:49 -07008716
Dianne Hackbornc72fc672012-09-20 13:12:03 -07008717 // If the removed package was a system update, the old system package
Romain Guy96f43572009-03-24 20:27:49 -07008718 // was re-enabled; we need to broadcast this information
8719 if (systemUpdate) {
8720 Bundle extras = new Bundle(1);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008721 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
8722 ? info.removedAppId : info.uid);
Romain Guy96f43572009-03-24 20:27:49 -07008723 extras.putBoolean(Intent.EXTRA_REPLACING, true);
8724
Dianne Hackborne7f97212011-02-24 14:40:20 -08008725 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008726 extras, null, null, null);
Dianne Hackborne7f97212011-02-24 14:40:20 -08008727 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008728 extras, null, null, null);
Dianne Hackborne7f97212011-02-24 14:40:20 -08008729 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008730 null, packageName, null, null);
Romain Guy96f43572009-03-24 20:27:49 -07008731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008732 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07008733 // Force a gc here.
8734 Runtime.getRuntime().gc();
8735 // Delete the resources here after sending the broadcast to let
8736 // other processes clean up before deleting resources.
8737 if (info.args != null) {
8738 synchronized (mInstallLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008739 info.args.doPostDeleteLI(true);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07008740 }
8741 }
Kenny Rootc39bb4a2011-02-28 13:27:19 -08008742
8743 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008744 }
8745
8746 static class PackageRemovedInfo {
8747 String removedPackage;
8748 int uid = -1;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008749 int removedAppId = -1;
8750 int[] removedUsers = null;
Romain Guy96f43572009-03-24 20:27:49 -07008751 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008752 // Clean up resources deleted packages.
8753 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07008754
Dianne Hackbornc72fc672012-09-20 13:12:03 -07008755 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008756 Bundle extras = new Bundle(1);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008757 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008758 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
8759 if (replacing) {
8760 extras.putBoolean(Intent.EXTRA_REPLACING, true);
8761 }
Dianne Hackbornc72fc672012-09-20 13:12:03 -07008762 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008763 if (removedPackage != null) {
Dianne Hackborne7f97212011-02-24 14:40:20 -08008764 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008765 extras, null, null, removedUsers);
Dianne Hackbornf9abb402011-08-10 15:00:59 -07008766 if (fullRemove && !replacing) {
8767 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008768 extras, null, null, removedUsers);
Dianne Hackbornf9abb402011-08-10 15:00:59 -07008769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008770 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008771 if (removedAppId >= 0) {
Amith Yamasani13593602012-03-22 16:16:17 -07008772 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008773 removedUsers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008774 }
8775 }
8776 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008778 /*
8779 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
8780 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008781 * 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 -08008782 * delete a partially installed application.
8783 */
Christopher Tateacee6e92013-05-14 16:11:44 -07008784 private void removePackageDataLI(PackageSetting ps,
8785 int[] allUserHandles, boolean[] perUserInstalled,
8786 PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008787 String packageName = ps.name;
Dianne Hackbornc895be72013-03-11 17:48:43 -07008788 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008789 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008790 // Retrieve object to delete permissions for shared user later on
Kenny Root447106f2011-03-23 11:00:15 -07008791 final PackageSetting deletedPs;
8792 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008793 synchronized (mPackages) {
8794 deletedPs = mSettings.mPackages.get(packageName);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008795 if (outInfo != null) {
8796 outInfo.removedPackage = packageName;
8797 outInfo.removedUsers = deletedPs != null
Dianne Hackborn786b4402012-08-27 15:14:02 -07008798 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
8799 : null;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008801 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008802 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07008803 removeDataDirsLI(packageName);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008804 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008805 }
Kenny Root447106f2011-03-23 11:00:15 -07008806 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008807 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008808 if (deletedPs != null) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008809 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008810 if (outInfo != null) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008811 outInfo.removedAppId = mSettings.removePackageLPw(packageName);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008812 }
8813 if (deletedPs != null) {
Dianne Hackborne639da72012-02-21 15:11:13 -08008814 updatePermissionsLPw(deletedPs.name, null, 0);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008815 if (deletedPs.sharedUser != null) {
8816 // remove permissions associated with package
Kenny Root447106f2011-03-23 11:00:15 -07008817 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008818 }
8819 }
Amith Yamasania3f133a2012-08-09 17:11:28 -07008820 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008821 }
Christopher Tateacee6e92013-05-14 16:11:44 -07008822 // make sure to preserve per-user disabled state if this removal was just
8823 // a downgrade of a system app to the factory package
8824 if (allUserHandles != null && perUserInstalled != null) {
8825 if (DEBUG_REMOVE) {
8826 Slog.d(TAG, "Propagating install state across downgrade");
8827 }
8828 for (int i = 0; i < allUserHandles.length; i++) {
8829 if (DEBUG_REMOVE) {
8830 Slog.d(TAG, " user " + allUserHandles[i]
8831 + " => " + perUserInstalled[i]);
8832 }
8833 ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
8834 }
8835 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008836 }
Kenny Root447106f2011-03-23 11:00:15 -07008837 // can downgrade to reader
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008838 if (writeSettings) {
8839 // Save settings now
Kenny Root447106f2011-03-23 11:00:15 -07008840 mSettings.writeLPr();
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008842 }
Kenny Root3b9933d2013-04-08 16:05:00 -07008843 if (outInfo != null) {
8844 // A user ID was deleted here. Go through all users and remove it
8845 // from KeyStore.
Kenny Root6fd1c85d2013-04-12 10:06:51 -07008846 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
Kenny Rootd72317a2013-04-01 15:59:59 -07008847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008848 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008850 /*
8851 * Tries to delete system package.
8852 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008853 private boolean deleteSystemPackageLI(PackageSetting newPs,
Christopher Tateacee6e92013-05-14 16:11:44 -07008854 int[] allUserHandles, boolean[] perUserInstalled,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008855 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
Christopher Tateacee6e92013-05-14 16:11:44 -07008856 final boolean applyUserRestrictions
8857 = (allUserHandles != null) && (perUserInstalled != null);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008858 PackageSetting disabledPs = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008859 // Confirm if the system package has been updated
8860 // An updated system app can be deleted. This will also have to restore
8861 // the system pkg from system partition
Kenny Root447106f2011-03-23 11:00:15 -07008862 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008863 synchronized (mPackages) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008864 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008865 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07008866 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
8867 + " disabledPs=" + disabledPs);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008868 if (disabledPs == null) {
8869 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008870 return false;
Dianne Hackbornc895be72013-03-11 17:48:43 -07008871 } else if (DEBUG_REMOVE) {
8872 Slog.d(TAG, "Deleting system pkg from data partition");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008873 }
Christopher Tateacee6e92013-05-14 16:11:44 -07008874 if (DEBUG_REMOVE) {
8875 if (applyUserRestrictions) {
8876 Slog.d(TAG, "Remembering install states:");
8877 for (int i = 0; i < allUserHandles.length; i++) {
8878 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
8879 }
8880 }
8881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008882 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07008883 outInfo.isRemovedPackageSystemUpdate = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008884 if (disabledPs.versionCode < newPs.versionCode) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008885 // Delete data for downgrades
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008886 flags &= ~PackageManager.DELETE_KEEP_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008887 } else {
8888 // Preserve data by setting flag
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008889 flags |= PackageManager.DELETE_KEEP_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008890 }
Christopher Tateacee6e92013-05-14 16:11:44 -07008891 boolean ret = deleteInstalledPackageLI(newPs, true, flags,
8892 allUserHandles, perUserInstalled, outInfo, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008893 if (!ret) {
8894 return false;
8895 }
Kenny Root447106f2011-03-23 11:00:15 -07008896 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008897 synchronized (mPackages) {
8898 // Reinstate the old system package
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008899 mSettings.enableSystemPackageLPw(newPs.name);
Kenny Root8f7cc022010-09-12 09:04:56 -07008900 // Remove any native libraries from the upgraded package.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008901 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008902 }
8903 // Install the system package
Dianne Hackbornc895be72013-03-11 17:48:43 -07008904 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008905 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008906 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008907 SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008909 if (newPkg == null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008910 Slog.w(TAG, "Failed to restore system package:" + newPs.name
8911 + " with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008912 return false;
8913 }
Kenny Root447106f2011-03-23 11:00:15 -07008914 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008915 synchronized (mPackages) {
Dianne Hackborne639da72012-02-21 15:11:13 -08008916 updatePermissionsLPw(newPkg.packageName, newPkg,
8917 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
Christopher Tateacee6e92013-05-14 16:11:44 -07008918 if (applyUserRestrictions) {
8919 if (DEBUG_REMOVE) {
8920 Slog.d(TAG, "Propagating install state across reinstall");
8921 }
8922 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
8923 for (int i = 0; i < allUserHandles.length; i++) {
8924 if (DEBUG_REMOVE) {
8925 Slog.d(TAG, " user " + allUserHandles[i]
8926 + " => " + perUserInstalled[i]);
8927 }
8928 ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
8929 }
8930 // Regardless of writeSettings we need to ensure that this restriction
8931 // state propagation is persisted
8932 mSettings.writeAllUsersPackageRestrictionsLPr();
8933 }
Kenny Root447106f2011-03-23 11:00:15 -07008934 // can downgrade to reader here
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008935 if (writeSettings) {
Kenny Root447106f2011-03-23 11:00:15 -07008936 mSettings.writeLPr();
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008938 }
8939 return true;
8940 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008941
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008942 private boolean deleteInstalledPackageLI(PackageSetting ps,
Christopher Tateacee6e92013-05-14 16:11:44 -07008943 boolean deleteCodeAndResources, int flags,
8944 int[] allUserHandles, boolean[] perUserInstalled,
8945 PackageRemovedInfo outInfo, boolean writeSettings) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008946 if (outInfo != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008947 outInfo.uid = ps.appId;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008949
8950 // Delete package data from internal structures and also remove data if flag is set
Christopher Tateacee6e92013-05-14 16:11:44 -07008951 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008952
8953 // Delete application code and resources
Kenny Root92bc9b32012-10-23 17:42:40 -07008954 if (deleteCodeAndResources && (outInfo != null)) {
Kenny Root5455f682012-09-09 14:52:10 -07008955 outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008956 ps.resourcePathString, ps.nativeLibraryPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008957 }
8958 return true;
8959 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008961 /*
8962 * This method handles package deletion in general
8963 */
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008964 private boolean deletePackageLI(String packageName, UserHandle user,
Christopher Tateacee6e92013-05-14 16:11:44 -07008965 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
8966 int flags, PackageRemovedInfo outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008967 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008968 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008969 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008970 return false;
8971 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07008972 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008973 PackageSetting ps;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008974 boolean dataOnly = false;
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008975 int removeUser = -1;
8976 int appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008977 synchronized (mPackages) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07008978 ps = mSettings.mPackages.get(packageName);
8979 if (ps == null) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008980 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
8981 return false;
8982 }
Dianne Hackbornc895be72013-03-11 17:48:43 -07008983 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008984 && user.getIdentifier() != UserHandle.USER_ALL) {
8985 // The caller is asking that the package only be deleted for a single
8986 // user. To do this, we just mark its uninstalled state and delete
Dianne Hackbornc895be72013-03-11 17:48:43 -07008987 // its data. If this is a system app, we only allow this to happen if
8988 // they have set the special DELETE_SYSTEM_APP which requests different
8989 // semantics than normal for uninstalling system apps.
8990 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
Dianne Hackborn7767eac2012-08-23 18:25:40 -07008991 ps.setUserState(user.getIdentifier(),
8992 COMPONENT_ENABLED_STATE_DEFAULT,
8993 false, //installed
8994 true, //stopped
8995 true, //notLaunched
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07008996 null, null, null);
Amith Yamasani67df64b2012-12-14 12:09:36 -08008997 if (!isSystemApp(ps)) {
8998 if (ps.isAnyInstalled(sUserManager.getUserIds())) {
8999 // Other user still have this package installed, so all
9000 // we need to do is clear this user's data and save that
9001 // it is uninstalled.
Dianne Hackbornc895be72013-03-11 17:48:43 -07009002 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
Amith Yamasani67df64b2012-12-14 12:09:36 -08009003 removeUser = user.getIdentifier();
9004 appId = ps.appId;
9005 mSettings.writePackageRestrictionsLPr(removeUser);
9006 } else {
9007 // We need to set it back to 'installed' so the uninstall
9008 // broadcasts will be sent correctly.
Dianne Hackbornc895be72013-03-11 17:48:43 -07009009 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
Amith Yamasani67df64b2012-12-14 12:09:36 -08009010 ps.setInstalled(true, user.getIdentifier());
9011 }
9012 } else {
9013 // This is a system app, so we assume that the
9014 // other users still have this package installed, so all
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009015 // we need to do is clear this user's data and save that
9016 // it is uninstalled.
Dianne Hackbornc895be72013-03-11 17:48:43 -07009017 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009018 removeUser = user.getIdentifier();
9019 appId = ps.appId;
9020 mSettings.writePackageRestrictionsLPr(removeUser);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009021 }
9022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009023 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009024
9025 if (removeUser >= 0) {
9026 // From above, we determined that we are deleting this only
9027 // for a single user. Continue the work here.
Dianne Hackbornc895be72013-03-11 17:48:43 -07009028 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009029 if (outInfo != null) {
9030 outInfo.removedPackage = packageName;
9031 outInfo.removedAppId = appId;
9032 outInfo.removedUsers = new int[] {removeUser};
9033 }
9034 mInstaller.clearUserData(packageName, removeUser);
Kenny Root6fd1c85d2013-04-12 10:06:51 -07009035 removeKeystoreDataIfNeeded(removeUser, appId);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009036 schedulePackageCleaning(packageName, removeUser, false);
9037 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009038 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009040 if (dataOnly) {
9041 // Delete application data first
Dianne Hackbornc895be72013-03-11 17:48:43 -07009042 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
Christopher Tateacee6e92013-05-14 16:11:44 -07009043 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009044 return true;
9045 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009046 boolean ret = false;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009047 if (isSystemApp(ps)) {
Dianne Hackbornc895be72013-03-11 17:48:43 -07009048 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009049 // When an updated system application is deleted we delete the existing resources as well and
9050 // fall back to existing code in system partition
Christopher Tateacee6e92013-05-14 16:11:44 -07009051 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
9052 flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009053 } else {
Dianne Hackbornc895be72013-03-11 17:48:43 -07009054 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009055 // Kill application pre-emptively especially for apps on sd.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009056 killApplication(packageName, ps.appId);
Christopher Tateacee6e92013-05-14 16:11:44 -07009057 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
9058 allUserHandles, perUserInstalled,
9059 outInfo, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009060 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009061 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009062 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009063
Dianne Hackborn183ce022012-06-29 15:00:21 -07009064 private final class ClearStorageConnection implements ServiceConnection {
9065 IMediaContainerService mContainerService;
9066
9067 @Override
9068 public void onServiceConnected(ComponentName name, IBinder service) {
9069 synchronized (this) {
9070 mContainerService = IMediaContainerService.Stub.asInterface(service);
9071 notifyAll();
9072 }
9073 }
9074
9075 @Override
9076 public void onServiceDisconnected(ComponentName name) {
9077 }
9078 }
9079
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009080 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
Dianne Hackborn183ce022012-06-29 15:00:21 -07009081 final boolean mounted;
9082 if (Environment.isExternalStorageEmulated()) {
9083 mounted = true;
9084 } else {
9085 final String status = Environment.getExternalStorageState();
9086
9087 mounted = status.equals(Environment.MEDIA_MOUNTED)
9088 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
9089 }
9090
9091 if (!mounted) {
9092 return;
9093 }
9094
9095 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009096 int[] users;
9097 if (userId == UserHandle.USER_ALL) {
9098 users = sUserManager.getUserIds();
9099 } else {
9100 users = new int[] { userId };
9101 }
Jeff Sharkey752cd922012-09-23 16:25:12 -07009102 final ClearStorageConnection conn = new ClearStorageConnection();
Amith Yamasani27b89e62013-01-16 12:30:11 -08009103 if (mContext.bindServiceAsUser(
9104 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
Jeff Sharkey752cd922012-09-23 16:25:12 -07009105 try {
9106 for (int curUser : users) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009107 long timeout = SystemClock.uptimeMillis() + 5000;
9108 synchronized (conn) {
9109 long now = SystemClock.uptimeMillis();
9110 while (conn.mContainerService == null && now < timeout) {
9111 try {
9112 conn.wait(timeout - now);
9113 } catch (InterruptedException e) {
9114 }
Dianne Hackborn183ce022012-06-29 15:00:21 -07009115 }
9116 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009117 if (conn.mContainerService == null) {
9118 return;
9119 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07009120
9121 final UserEnvironment userEnv = new UserEnvironment(curUser);
9122 final File externalCacheDir = userEnv
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009123 .getExternalStorageAppCacheDirectory(packageName);
Dianne Hackborn183ce022012-06-29 15:00:21 -07009124 try {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009125 conn.mContainerService.clearDirectory(externalCacheDir.toString());
Dianne Hackborn183ce022012-06-29 15:00:21 -07009126 } catch (RemoteException e) {
9127 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009128 if (allData) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07009129 final File externalDataDir = userEnv
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009130 .getExternalStorageAppDataDirectory(packageName);
9131 try {
9132 conn.mContainerService.clearDirectory(externalDataDir.toString());
9133 } catch (RemoteException e) {
9134 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07009135 final File externalMediaDir = userEnv
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009136 .getExternalStorageAppMediaDirectory(packageName);
9137 try {
9138 conn.mContainerService.clearDirectory(externalMediaDir.toString());
9139 } catch (RemoteException e) {
9140 }
Dianne Hackborn183ce022012-06-29 15:00:21 -07009141 }
9142 }
Jeff Sharkey752cd922012-09-23 16:25:12 -07009143 } finally {
9144 mContext.unbindService(conn);
Dianne Hackborn183ce022012-06-29 15:00:21 -07009145 }
9146 }
9147 }
9148
Amith Yamasani483f3b02012-03-13 16:08:00 -07009149 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009150 public void clearApplicationUserData(final String packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07009151 final IPackageDataObserver observer, final int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009152 mContext.enforceCallingOrSelfPermission(
9153 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
Amith Yamasanif203aee2012-08-29 18:41:53 -07009154 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009155 // Queue up an async operation since the package deletion may take a little while.
9156 mHandler.post(new Runnable() {
9157 public void run() {
9158 mHandler.removeCallbacks(this);
9159 final boolean succeeded;
9160 synchronized (mInstallLock) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07009161 succeeded = clearApplicationUserDataLI(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009162 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009163 clearExternalStorageDataSync(packageName, userId, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009164 if (succeeded) {
9165 // invoke DeviceStorageMonitor's update method to clear any notifications
9166 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
9167 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
9168 if (dsm != null) {
9169 dsm.updateMemory();
9170 }
9171 }
9172 if(observer != null) {
9173 try {
9174 observer.onRemoveCompleted(packageName, succeeded);
9175 } catch (RemoteException e) {
9176 Log.i(TAG, "Observer no longer exists.");
9177 }
9178 } //end if observer
9179 } //end run
9180 });
9181 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009182
Amith Yamasani483f3b02012-03-13 16:08:00 -07009183 private boolean clearApplicationUserDataLI(String packageName, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009184 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009185 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009186 return false;
9187 }
9188 PackageParser.Package p;
9189 boolean dataOnly = false;
Kenny Root6fd1c85d2013-04-12 10:06:51 -07009190 final int appId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009191 synchronized (mPackages) {
9192 p = mPackages.get(packageName);
Kenny Root6fd1c85d2013-04-12 10:06:51 -07009193 if (p == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009194 dataOnly = true;
9195 PackageSetting ps = mSettings.mPackages.get(packageName);
Kenny Root6fd1c85d2013-04-12 10:06:51 -07009196 if ((ps == null) || (ps.pkg == null)) {
9197 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009198 return false;
9199 }
9200 p = ps.pkg;
9201 }
Kenny Root6fd1c85d2013-04-12 10:06:51 -07009202 if (!dataOnly) {
9203 // need to check this only for fully installed applications
9204 if (p == null) {
9205 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
9206 return false;
9207 }
9208 final ApplicationInfo applicationInfo = p.applicationInfo;
9209 if (applicationInfo == null) {
9210 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
9211 return false;
9212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009213 }
Kenny Root6fd1c85d2013-04-12 10:06:51 -07009214 if (p != null && p.applicationInfo != null) {
9215 appId = p.applicationInfo.uid;
9216 } else {
9217 appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009218 }
9219 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07009220 int retCode = mInstaller.clearUserData(packageName, userId);
Jeff Brown5d6d90f2011-07-11 13:04:53 -07009221 if (retCode < 0) {
9222 Slog.w(TAG, "Couldn't remove cache files for package: "
9223 + packageName);
9224 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009225 }
Kenny Root6fd1c85d2013-04-12 10:06:51 -07009226 removeKeystoreDataIfNeeded(userId, appId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009227 return true;
9228 }
9229
Kenny Root6fd1c85d2013-04-12 10:06:51 -07009230 /**
9231 * Remove entries from the keystore daemon. Will only remove it if the
9232 * {@code appId} is valid.
9233 */
9234 private static void removeKeystoreDataIfNeeded(int userId, int appId) {
9235 if (appId < 0) {
9236 return;
9237 }
9238
9239 final KeyStore keyStore = KeyStore.getInstance();
9240 if (keyStore != null) {
9241 if (userId == UserHandle.USER_ALL) {
9242 for (final int individual : sUserManager.getUserIds()) {
9243 keyStore.clearUid(UserHandle.getUid(individual, appId));
9244 }
9245 } else {
9246 keyStore.clearUid(UserHandle.getUid(userId, appId));
9247 }
9248 } else {
9249 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
9250 }
9251 }
9252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009253 public void deleteApplicationCacheFiles(final String packageName,
9254 final IPackageDataObserver observer) {
9255 mContext.enforceCallingOrSelfPermission(
9256 android.Manifest.permission.DELETE_CACHE_FILES, null);
9257 // Queue up an async operation since the package deletion may take a little while.
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07009258 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009259 mHandler.post(new Runnable() {
9260 public void run() {
9261 mHandler.removeCallbacks(this);
9262 final boolean succeded;
9263 synchronized (mInstallLock) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07009264 succeded = deleteApplicationCacheFilesLI(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009265 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009266 clearExternalStorageDataSync(packageName, userId, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009267 if(observer != null) {
9268 try {
9269 observer.onRemoveCompleted(packageName, succeded);
9270 } catch (RemoteException e) {
9271 Log.i(TAG, "Observer no longer exists.");
9272 }
9273 } //end if observer
9274 } //end run
9275 });
9276 }
9277
Amith Yamasani483f3b02012-03-13 16:08:00 -07009278 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009279 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009280 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009281 return false;
9282 }
9283 PackageParser.Package p;
9284 synchronized (mPackages) {
9285 p = mPackages.get(packageName);
9286 }
9287 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009288 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009289 return false;
9290 }
9291 final ApplicationInfo applicationInfo = p.applicationInfo;
9292 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009293 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009294 return false;
9295 }
Amith Yamasani54289b82012-10-01 10:39:14 -07009296 int retCode = mInstaller.deleteCacheFiles(packageName, userId);
Jeff Brown5d6d90f2011-07-11 13:04:53 -07009297 if (retCode < 0) {
9298 Slog.w(TAG, "Couldn't remove cache files for package: "
Amith Yamasani54289b82012-10-01 10:39:14 -07009299 + packageName + " u" + userId);
Jeff Brown5d6d90f2011-07-11 13:04:53 -07009300 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009301 }
9302 return true;
9303 }
9304
Dianne Hackborn0c380492012-08-20 17:23:30 -07009305 public void getPackageSizeInfo(final String packageName, int userHandle,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009306 final IPackageStatsObserver observer) {
9307 mContext.enforceCallingOrSelfPermission(
9308 android.Manifest.permission.GET_PACKAGE_SIZE, null);
Kenny Root366949c2011-01-14 17:18:14 -08009309
Dianne Hackborn0c380492012-08-20 17:23:30 -07009310 PackageStats stats = new PackageStats(packageName, userHandle);
Kenny Root366949c2011-01-14 17:18:14 -08009311
Kenny Roota69b7eb2012-05-14 14:47:06 -07009312 /*
9313 * Queue up an async operation since the package measurement may take a
9314 * little while.
9315 */
9316 Message msg = mHandler.obtainMessage(INIT_COPY);
9317 msg.obj = new MeasureParams(stats, observer);
9318 mHandler.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009319 }
9320
Dianne Hackborn0c380492012-08-20 17:23:30 -07009321 private boolean getPackageSizeInfoLI(String packageName, int userHandle,
9322 PackageStats pStats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009323 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009324 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009325 return false;
9326 }
9327 PackageParser.Package p;
9328 boolean dataOnly = false;
Dianne Hackbornecc8d6f2013-05-01 18:54:11 -07009329 String libDirPath = null;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07009330 String asecPath = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009331 synchronized (mPackages) {
9332 p = mPackages.get(packageName);
Dianne Hackbornecc8d6f2013-05-01 18:54:11 -07009333 PackageSetting ps = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009334 if(p == null) {
9335 dataOnly = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009336 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009337 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009338 return false;
9339 }
9340 p = ps.pkg;
9341 }
Dianne Hackbornecc8d6f2013-05-01 18:54:11 -07009342 if (ps != null) {
9343 libDirPath = ps.nativeLibraryPathString;
9344 }
Kenny Root2afded12012-06-04 16:39:47 -07009345 if (p != null && (isExternal(p) || isForwardLocked(p))) {
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07009346 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
9347 if (secureContainerId != null) {
9348 asecPath = PackageHelper.getSdFilesystem(secureContainerId);
9349 }
9350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009351 }
9352 String publicSrcDir = null;
9353 if(!dataOnly) {
9354 final ApplicationInfo applicationInfo = p.applicationInfo;
9355 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009356 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009357 return false;
9358 }
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07009359 if (isForwardLocked(p)) {
9360 publicSrcDir = applicationInfo.publicSourceDir;
9361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009362 }
Dianne Hackbornecc8d6f2013-05-01 18:54:11 -07009363 int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath,
9364 publicSrcDir, asecPath, pStats);
Jeff Brown5d6d90f2011-07-11 13:04:53 -07009365 if (res < 0) {
9366 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009367 }
Kenny Root2afded12012-06-04 16:39:47 -07009368
9369 // Fix-up for forward-locked applications in ASEC containers.
9370 if (!isExternal(p)) {
9371 pStats.codeSize += pStats.externalCodeSize;
9372 pStats.externalCodeSize = 0L;
9373 }
9374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009375 return true;
9376 }
9377
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009379 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07009380 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009381 }
9382
9383 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07009384 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009385 }
9386
9387 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08009388 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009389 }
9390
Kenny Root447106f2011-03-23 11:00:15 -07009391 private int getUidTargetSdkVersionLockedLPr(int uid) {
9392 Object obj = mSettings.getUserIdLPr(uid);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009393 if (obj instanceof SharedUserSetting) {
Kenny Root60f7ad82011-03-22 12:49:06 -07009394 final SharedUserSetting sus = (SharedUserSetting) obj;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009395 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
Kenny Root60f7ad82011-03-22 12:49:06 -07009396 final Iterator<PackageSetting> it = sus.packages.iterator();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009397 while (it.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07009398 final PackageSetting ps = it.next();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009399 if (ps.pkg != null) {
9400 int v = ps.pkg.applicationInfo.targetSdkVersion;
9401 if (v < vers) vers = v;
9402 }
9403 }
9404 return vers;
9405 } else if (obj instanceof PackageSetting) {
Kenny Root60f7ad82011-03-22 12:49:06 -07009406 final PackageSetting ps = (PackageSetting) obj;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009407 if (ps.pkg != null) {
9408 return ps.pkg.applicationInfo.targetSdkVersion;
9409 }
9410 }
9411 return Build.VERSION_CODES.CUR_DEVELOPMENT;
9412 }
9413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009414 public void addPreferredActivity(IntentFilter filter, int match,
Amith Yamasania3f133a2012-08-09 17:11:28 -07009415 ComponentName[] set, ComponentName activity, int userId) {
Kenny Root447106f2011-03-23 11:00:15 -07009416 // writer
Amith Yamasania3f133a2012-08-09 17:11:28 -07009417 int callingUid = Binder.getCallingUid();
Amith Yamasanif203aee2012-08-29 18:41:53 -07009418 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009419 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009420 if (mContext.checkCallingOrSelfPermission(
9421 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
9422 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasania3f133a2012-08-09 17:11:28 -07009423 if (getUidTargetSdkVersionLockedLPr(callingUid)
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009424 < Build.VERSION_CODES.FROYO) {
9425 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
Amith Yamasania3f133a2012-08-09 17:11:28 -07009426 + callingUid);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009427 return;
9428 }
9429 mContext.enforceCallingOrSelfPermission(
9430 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9431 }
Amith Yamasania3f133a2012-08-09 17:11:28 -07009432
9433 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009434 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
Dianne Hackborn63092712012-10-07 14:45:35 -07009435 mSettings.editPreferredActivitiesLPw(userId).addFilter(
9436 new PreferredActivity(filter, match, set, activity));
9437 mSettings.writePackageRestrictionsLPr(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009438 }
9439 }
9440
Satish Sampath8dbe6122009-06-02 23:35:54 +01009441 public void replacePreferredActivity(IntentFilter filter, int match,
9442 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01009443 if (filter.countActions() != 1) {
9444 throw new IllegalArgumentException(
9445 "replacePreferredActivity expects filter to have only 1 action.");
9446 }
9447 if (filter.countCategories() != 1) {
9448 throw new IllegalArgumentException(
9449 "replacePreferredActivity expects filter to have only 1 category.");
9450 }
9451 if (filter.countDataAuthorities() != 0
9452 || filter.countDataPaths() != 0
9453 || filter.countDataSchemes() != 0
9454 || filter.countDataTypes() != 0) {
9455 throw new IllegalArgumentException(
9456 "replacePreferredActivity expects filter to have no data authorities, " +
9457 "paths, schemes or types.");
9458 }
9459 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009460 if (mContext.checkCallingOrSelfPermission(
9461 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
9462 != PackageManager.PERMISSION_GRANTED) {
Kenny Root447106f2011-03-23 11:00:15 -07009463 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009464 < Build.VERSION_CODES.FROYO) {
9465 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
9466 + Binder.getCallingUid());
9467 return;
9468 }
9469 mContext.enforceCallingOrSelfPermission(
9470 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9471 }
Amith Yamasania3f133a2012-08-09 17:11:28 -07009472
9473 final int callingUserId = UserHandle.getCallingUserId();
Dianne Hackborn04505102012-02-29 12:34:04 -08009474 ArrayList<PreferredActivity> removed = null;
Dianne Hackborn63092712012-10-07 14:45:35 -07009475 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
9476 if (pir != null) {
9477 Iterator<PreferredActivity> it = pir.filterIterator();
9478 String action = filter.getAction(0);
9479 String category = filter.getCategory(0);
9480 while (it.hasNext()) {
9481 PreferredActivity pa = it.next();
9482 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
9483 if (removed == null) {
9484 removed = new ArrayList<PreferredActivity>();
9485 }
9486 removed.add(pa);
9487 Log.i(TAG, "Removing preferred activity " + pa.mPref.mComponent + ":");
9488 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
Dianne Hackborn04505102012-02-29 12:34:04 -08009489 }
Satish Sampath8dbe6122009-06-02 23:35:54 +01009490 }
Dianne Hackborn63092712012-10-07 14:45:35 -07009491 if (removed != null) {
9492 for (int i=0; i<removed.size(); i++) {
9493 PreferredActivity pa = removed.get(i);
9494 pir.removeFilter(pa);
9495 }
Dianne Hackborn04505102012-02-29 12:34:04 -08009496 }
9497 }
Amith Yamasania3f133a2012-08-09 17:11:28 -07009498 addPreferredActivity(filter, match, set, activity, callingUserId);
Satish Sampath8dbe6122009-06-02 23:35:54 +01009499 }
9500 }
9501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009502 public void clearPackagePreferredActivities(String packageName) {
Kenny Root447106f2011-03-23 11:00:15 -07009503 final int uid = Binder.getCallingUid();
9504 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009505 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08009506 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009507 if (pkg == null || pkg.applicationInfo.uid != uid) {
9508 if (mContext.checkCallingOrSelfPermission(
9509 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
9510 != PackageManager.PERMISSION_GRANTED) {
Kenny Root447106f2011-03-23 11:00:15 -07009511 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009512 < Build.VERSION_CODES.FROYO) {
9513 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
9514 + Binder.getCallingUid());
9515 return;
9516 }
9517 mContext.enforceCallingOrSelfPermission(
9518 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9519 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08009520 }
9521
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08009522 int user = UserHandle.getCallingUserId();
9523 if (clearPackagePreferredActivitiesLPw(packageName, user)) {
9524 mSettings.writePackageRestrictionsLPr(user);
9525 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009526 }
9527 }
9528 }
9529
Amith Yamasania3f133a2012-08-09 17:11:28 -07009530 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
9531 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
Dianne Hackborn04505102012-02-29 12:34:04 -08009532 ArrayList<PreferredActivity> removed = null;
Dianne Hackborn63092712012-10-07 14:45:35 -07009533 boolean changed = false;
9534 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
9535 final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
9536 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
9537 if (userId != UserHandle.USER_ALL && userId != thisUserId) {
Amith Yamasania3f133a2012-08-09 17:11:28 -07009538 continue;
9539 }
Dianne Hackborn63092712012-10-07 14:45:35 -07009540 Iterator<PreferredActivity> it = pir.filterIterator();
9541 while (it.hasNext()) {
9542 PreferredActivity pa = it.next();
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08009543 if (packageName == null ||
9544 pa.mPref.mComponent.getPackageName().equals(packageName)) {
Dianne Hackborn63092712012-10-07 14:45:35 -07009545 if (removed == null) {
9546 removed = new ArrayList<PreferredActivity>();
9547 }
9548 removed.add(pa);
Dianne Hackborn04505102012-02-29 12:34:04 -08009549 }
Dianne Hackborn63092712012-10-07 14:45:35 -07009550 }
9551 if (removed != null) {
9552 for (int j=0; j<removed.size(); j++) {
9553 PreferredActivity pa = removed.get(j);
9554 pir.removeFilter(pa);
9555 }
9556 changed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009557 }
9558 }
Dianne Hackborn63092712012-10-07 14:45:35 -07009559 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009560 }
9561
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08009562 public void resetPreferredActivities(int userId) {
9563 mContext.enforceCallingOrSelfPermission(
9564 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9565 // writer
9566 synchronized (mPackages) {
9567 int user = UserHandle.getCallingUserId();
9568 clearPackagePreferredActivitiesLPw(null, user);
9569 mSettings.readDefaultPreferredAppsLPw(this, user);
9570 mSettings.writePackageRestrictionsLPr(user);
9571 scheduleWriteSettingsLocked();
9572 }
9573 }
9574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009575 public int getPreferredActivities(List<IntentFilter> outFilters,
9576 List<ComponentName> outActivities, String packageName) {
9577
9578 int num = 0;
Amith Yamasania3f133a2012-08-09 17:11:28 -07009579 final int userId = UserHandle.getCallingUserId();
Kenny Root447106f2011-03-23 11:00:15 -07009580 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009581 synchronized (mPackages) {
Dianne Hackborn63092712012-10-07 14:45:35 -07009582 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
9583 if (pir != null) {
9584 final Iterator<PreferredActivity> it = pir.filterIterator();
9585 while (it.hasNext()) {
9586 final PreferredActivity pa = it.next();
9587 if (packageName == null
9588 || pa.mPref.mComponent.getPackageName().equals(packageName)) {
9589 if (outFilters != null) {
9590 outFilters.add(new IntentFilter(pa));
9591 }
9592 if (outActivities != null) {
9593 outActivities.add(pa.mPref.mComponent);
9594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009595 }
9596 }
9597 }
9598 }
9599
9600 return num;
9601 }
9602
Amith Yamasani483f3b02012-03-13 16:08:00 -07009603 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009604 public void setApplicationEnabledSetting(String appPackageName,
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07009605 int newState, int flags, int userId, String callingPackage) {
Amith Yamasani13593602012-03-22 16:16:17 -07009606 if (!sUserManager.exists(userId)) return;
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07009607 if (callingPackage == null) {
9608 callingPackage = Integer.toString(Binder.getCallingUid());
9609 }
9610 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009611 }
9612
Amith Yamasani483f3b02012-03-13 16:08:00 -07009613 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009614 public void setComponentEnabledSetting(ComponentName componentName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07009615 int newState, int flags, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07009616 if (!sUserManager.exists(userId)) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009617 setEnabledSetting(componentName.getPackageName(),
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07009618 componentName.getClassName(), newState, flags, userId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009619 }
9620
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07009621 private void setEnabledSetting(final String packageName, String className, int newState,
9622 final int flags, int userId, String callingPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009623 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
9624 || newState == COMPONENT_ENABLED_STATE_ENABLED
Dianne Hackborn0ac30312011-06-17 14:49:23 -07009625 || newState == COMPONENT_ENABLED_STATE_DISABLED
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08009626 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
9627 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009628 throw new IllegalArgumentException("Invalid new component state: "
9629 + newState);
9630 }
9631 PackageSetting pkgSetting;
9632 final int uid = Binder.getCallingUid();
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08009633 final int permission = mContext.checkCallingOrSelfPermission(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009634 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
Amith Yamasanif203aee2012-08-29 18:41:53 -07009635 enforceCrossUserPermission(uid, userId, false, "set enabled");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009636 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009637 boolean sendNow = false;
9638 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08009639 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009640 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08009641 ArrayList<String> components;
Kenny Root447106f2011-03-23 11:00:15 -07009642
9643 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009644 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009645 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009646 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009647 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009648 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009649 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009650 }
9651 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009652 "Unknown component: " + packageName
9653 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009654 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07009655 // Allow root and verify that userId is not being specified by a different user
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07009656 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009657 throw new SecurityException(
9658 "Permission Denial: attempt to change component state from pid="
9659 + Binder.getCallingPid()
Amith Yamasani13593602012-03-22 16:16:17 -07009660 + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009661 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009662 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009663 // We're dealing with an application/package level state change
Amith Yamasani483f3b02012-03-13 16:08:00 -07009664 if (pkgSetting.getEnabled(userId) == newState) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07009665 // Nothing to do
9666 return;
9667 }
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07009668 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
9669 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
9670 // Don't care about who enables an app.
9671 callingPackage = null;
9672 }
9673 pkgSetting.setEnabled(newState, userId, callingPackage);
Amith Yamasani13593602012-03-22 16:16:17 -07009674 // pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009675 } else {
9676 // We're dealing with a component level state change
Dianne Hackborn65696252012-03-05 18:49:21 -08009677 // First, verify that this is a valid class name.
9678 PackageParser.Package pkg = pkgSetting.pkg;
9679 if (pkg == null || !pkg.hasComponentClassName(className)) {
9680 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
9681 throw new IllegalArgumentException("Component class " + className
9682 + " does not exist in " + packageName);
9683 } else {
9684 Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
9685 + className + " does not exist in " + packageName);
9686 }
9687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009688 switch (newState) {
9689 case COMPONENT_ENABLED_STATE_ENABLED:
Amith Yamasani483f3b02012-03-13 16:08:00 -07009690 if (!pkgSetting.enableComponentLPw(className, userId)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07009691 return;
9692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009693 break;
9694 case COMPONENT_ENABLED_STATE_DISABLED:
Amith Yamasani483f3b02012-03-13 16:08:00 -07009695 if (!pkgSetting.disableComponentLPw(className, userId)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07009696 return;
9697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009698 break;
9699 case COMPONENT_ENABLED_STATE_DEFAULT:
Amith Yamasani483f3b02012-03-13 16:08:00 -07009700 if (!pkgSetting.restoreComponentLPw(className, userId)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07009701 return;
9702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009703 break;
9704 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009705 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009706 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009707 }
9708 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07009709 mSettings.writePackageRestrictionsLPr(userId);
Christopher Tate1e08f5c2013-05-02 13:27:27 -07009710 components = mPendingBroadcasts.get(userId, packageName);
Kenny Root447106f2011-03-23 11:00:15 -07009711 final boolean newPackage = components == null;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08009712 if (newPackage) {
9713 components = new ArrayList<String>();
9714 }
9715 if (!components.contains(componentName)) {
9716 components.add(componentName);
9717 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009718 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
9719 sendNow = true;
9720 // Purge entry from pending broadcast list if another one exists already
9721 // since we are sending one right away.
Christopher Tate1e08f5c2013-05-02 13:27:27 -07009722 mPendingBroadcasts.remove(userId, packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009723 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08009724 if (newPackage) {
Christopher Tate1e08f5c2013-05-02 13:27:27 -07009725 mPendingBroadcasts.put(userId, packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009726 }
9727 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
9728 // Schedule a message
9729 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
9730 }
9731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009732 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009734 long callingId = Binder.clearCallingIdentity();
9735 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009736 if (sendNow) {
Christopher Tate1e08f5c2013-05-02 13:27:27 -07009737 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009738 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08009739 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009741 } finally {
9742 Binder.restoreCallingIdentity(callingId);
9743 }
9744 }
9745
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009746 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08009747 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
Kenny Root4dfe6ff2011-02-23 17:00:43 -08009748 if (DEBUG_INSTALL)
9749 Log.v(TAG, "Sending package changed: package=" + packageName + " components="
9750 + componentNames);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08009751 Bundle extras = new Bundle(4);
9752 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
9753 String nameList[] = new String[componentNames.size()];
9754 componentNames.toArray(nameList);
9755 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009756 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
9757 extras.putInt(Intent.EXTRA_UID, packageUid);
Amith Yamasani13593602012-03-22 16:16:17 -07009758 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07009759 new int[] {UserHandle.getUserId(packageUid)});
Dianne Hackborne7f97212011-02-24 14:40:20 -08009760 }
9761
Amith Yamasani483f3b02012-03-13 16:08:00 -07009762 public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07009763 if (!sUserManager.exists(userId)) return;
Dianne Hackborne7f97212011-02-24 14:40:20 -08009764 final int uid = Binder.getCallingUid();
9765 final int permission = mContext.checkCallingOrSelfPermission(
9766 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
9767 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Amith Yamasanif203aee2012-08-29 18:41:53 -07009768 enforceCrossUserPermission(uid, userId, true, "stop package");
Kenny Root447106f2011-03-23 11:00:15 -07009769 // writer
Dianne Hackborne7f97212011-02-24 14:40:20 -08009770 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07009771 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
Amith Yamasani483f3b02012-03-13 16:08:00 -07009772 uid, userId)) {
9773 scheduleWritePackageRestrictionsLocked(userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08009774 }
9775 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07009776 }
9777
Jacek Surazski65e13172009-04-28 15:26:38 +02009778 public String getInstallerPackageName(String packageName) {
Kenny Root447106f2011-03-23 11:00:15 -07009779 // reader
Jacek Surazski65e13172009-04-28 15:26:38 +02009780 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07009781 return mSettings.getInstallerPackageNameLPr(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02009782 }
9783 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009784
Amith Yamasani483f3b02012-03-13 16:08:00 -07009785 @Override
9786 public int getApplicationEnabledSetting(String packageName, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07009787 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
Amith Yamasani483f3b02012-03-13 16:08:00 -07009788 int uid = Binder.getCallingUid();
Amith Yamasanif203aee2012-08-29 18:41:53 -07009789 enforceCrossUserPermission(uid, userId, false, "get enabled");
Kenny Root447106f2011-03-23 11:00:15 -07009790 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009791 synchronized (mPackages) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07009792 return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009793 }
9794 }
9795
Amith Yamasani483f3b02012-03-13 16:08:00 -07009796 @Override
9797 public int getComponentEnabledSetting(ComponentName componentName, int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07009798 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
Amith Yamasani483f3b02012-03-13 16:08:00 -07009799 int uid = Binder.getCallingUid();
Amith Yamasanif203aee2012-08-29 18:41:53 -07009800 enforceCrossUserPermission(uid, userId, false, "get component enabled");
Kenny Root447106f2011-03-23 11:00:15 -07009801 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009802 synchronized (mPackages) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07009803 return mSettings.getComponentEnabledSettingLPr(componentName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009804 }
9805 }
9806
9807 public void enterSafeMode() {
Kenny Root461ff1f2011-08-09 09:43:03 -07009808 enforceSystemOrRoot("Only the system can request entering safe mode");
9809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009810 if (!mSystemReady) {
9811 mSafeMode = true;
9812 }
9813 }
9814
9815 public void systemReady() {
9816 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07009817
9818 // Read the compatibilty setting when the system is ready.
Jeff Sharkey6e2bee72012-10-01 13:39:08 -07009819 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07009820 mContext.getContentResolver(),
Jeff Sharkey6e2bee72012-10-01 13:39:08 -07009821 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07009822 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07009823 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07009824 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07009825 }
Dianne Hackborn63092712012-10-07 14:45:35 -07009826
9827 synchronized (mPackages) {
9828 // Verify that all of the preferred activity components actually
9829 // exist. It is possible for applications to be updated and at
9830 // that point remove a previously declared activity component that
9831 // had been set as a preferred activity. We try to clean this up
9832 // the next time we encounter that preferred activity, but it is
9833 // possible for the user flow to never be able to return to that
9834 // situation so here we do a sanity check to make sure we haven't
9835 // left any junk around.
9836 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
9837 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
9838 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
9839 removed.clear();
9840 for (PreferredActivity pa : pir.filterSet()) {
9841 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
9842 removed.add(pa);
9843 }
9844 }
9845 if (removed.size() > 0) {
9846 for (int j=0; j<removed.size(); j++) {
9847 PreferredActivity pa = removed.get(i);
Dianne Hackborn63092712012-10-07 14:45:35 -07009848 Slog.w(TAG, "Removing dangling preferred activity: "
Dianne Hackborn40e9f292012-11-27 19:12:23 -08009849 + pa.mPref.mComponent);
Dianne Hackborn63092712012-10-07 14:45:35 -07009850 pir.removeFilter(pa);
9851 }
9852 mSettings.writePackageRestrictionsLPr(
9853 mSettings.mPreferredActivities.keyAt(i));
9854 }
9855 }
9856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009857 }
9858
9859 public boolean isSafeMode() {
9860 return mSafeMode;
9861 }
9862
9863 public boolean hasSystemUidErrors() {
9864 return mHasSystemUidErrors;
9865 }
9866
9867 static String arrayToString(int[] array) {
9868 StringBuffer buf = new StringBuffer(128);
9869 buf.append('[');
9870 if (array != null) {
9871 for (int i=0; i<array.length; i++) {
9872 if (i > 0) buf.append(", ");
9873 buf.append(array[i]);
9874 }
9875 }
9876 buf.append(']');
9877 return buf.toString();
9878 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009879
Kenny Root447106f2011-03-23 11:00:15 -07009880 static class DumpState {
9881 public static final int DUMP_LIBS = 1 << 0;
9882
9883 public static final int DUMP_FEATURES = 1 << 1;
9884
9885 public static final int DUMP_RESOLVERS = 1 << 2;
9886
9887 public static final int DUMP_PERMISSIONS = 1 << 3;
9888
9889 public static final int DUMP_PACKAGES = 1 << 4;
9890
9891 public static final int DUMP_SHARED_USERS = 1 << 5;
9892
9893 public static final int DUMP_MESSAGES = 1 << 6;
9894
9895 public static final int DUMP_PROVIDERS = 1 << 7;
9896
Kenny Root05ca4c92011-09-15 10:36:25 -07009897 public static final int DUMP_VERIFIERS = 1 << 8;
9898
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07009899 public static final int DUMP_PREFERRED = 1 << 9;
9900
9901 public static final int DUMP_PREFERRED_XML = 1 << 10;
9902
Kenny Root447106f2011-03-23 11:00:15 -07009903 public static final int OPTION_SHOW_FILTERS = 1 << 0;
9904
9905 private int mTypes;
9906
9907 private int mOptions;
9908
9909 private boolean mTitlePrinted;
9910
9911 private SharedUserSetting mSharedUser;
9912
9913 public boolean isDumping(int type) {
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07009914 if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
Kenny Root447106f2011-03-23 11:00:15 -07009915 return true;
9916 }
9917
9918 return (mTypes & type) != 0;
9919 }
9920
9921 public void setDump(int type) {
9922 mTypes |= type;
9923 }
9924
9925 public boolean isOptionEnabled(int option) {
9926 return (mOptions & option) != 0;
9927 }
9928
9929 public void setOptionEnabled(int option) {
9930 mOptions |= option;
9931 }
9932
9933 public boolean onTitlePrinted() {
9934 final boolean printed = mTitlePrinted;
9935 mTitlePrinted = true;
9936 return printed;
9937 }
9938
9939 public boolean getTitlePrinted() {
9940 return mTitlePrinted;
9941 }
9942
9943 public void setTitlePrinted(boolean enabled) {
9944 mTitlePrinted = enabled;
9945 }
9946
9947 public SharedUserSetting getSharedUser() {
9948 return mSharedUser;
9949 }
9950
9951 public void setSharedUser(SharedUserSetting user) {
9952 mSharedUser = user;
9953 }
9954 }
9955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009956 @Override
9957 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
9958 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
9959 != PackageManager.PERMISSION_GRANTED) {
9960 pw.println("Permission Denial: can't dump ActivityManager from from pid="
9961 + Binder.getCallingPid()
9962 + ", uid=" + Binder.getCallingUid()
9963 + " without permission "
9964 + android.Manifest.permission.DUMP);
9965 return;
9966 }
9967
Kenny Root447106f2011-03-23 11:00:15 -07009968 DumpState dumpState = new DumpState();
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08009969 boolean fullPreferred = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009970
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009971 String packageName = null;
9972
9973 int opti = 0;
9974 while (opti < args.length) {
9975 String opt = args[opti];
9976 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9977 break;
9978 }
9979 opti++;
9980 if ("-a".equals(opt)) {
9981 // Right now we only know how to print all.
9982 } else if ("-h".equals(opt)) {
9983 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009984 pw.println(" [-h] [-f] [cmd] ...");
9985 pw.println(" -f: print details of intent filters");
9986 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009987 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009988 pw.println(" l[ibraries]: list known shared libraries");
9989 pw.println(" f[ibraries]: list device features");
9990 pw.println(" r[esolvers]: dump intent resolvers");
9991 pw.println(" perm[issions]: dump permissions");
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -07009992 pw.println(" pref[erred]: print preferred package settings");
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -08009993 pw.println(" preferred-xml [--full]: print preferred package settings as xml");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009994 pw.println(" prov[iders]: dump content providers");
9995 pw.println(" p[ackages]: dump installed packages");
9996 pw.println(" s[hared-users]: dump shared user IDs");
9997 pw.println(" m[essages]: print collected runtime messages");
Kenny Root05ca4c92011-09-15 10:36:25 -07009998 pw.println(" v[erifiers]: print package verifier info");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07009999 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -070010000 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010001 } else if ("-f".equals(opt)) {
Kenny Root447106f2011-03-23 11:00:15 -070010002 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -070010003 } else {
10004 pw.println("Unknown argument: " + opt + "; use -h for help");
10005 }
10006 }
10007
10008 // Is the caller requesting to dump a particular piece of data?
10009 if (opti < args.length) {
10010 String cmd = args[opti];
10011 opti++;
10012 // Is this a package name?
10013 if ("android".equals(cmd) || cmd.contains(".")) {
10014 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010015 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -070010016 dumpState.setDump(DumpState.DUMP_LIBS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010017 } else if ("f".equals(cmd) || "features".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -070010018 dumpState.setDump(DumpState.DUMP_FEATURES);
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010019 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -070010020 dumpState.setDump(DumpState.DUMP_RESOLVERS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010021 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -070010022 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -070010023 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
10024 dumpState.setDump(DumpState.DUMP_PREFERRED);
10025 } else if ("preferred-xml".equals(cmd)) {
10026 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080010027 if (opti < args.length && "--full".equals(args[opti])) {
10028 fullPreferred = true;
Dianne Hackbornd4d93642013-01-29 16:12:48 -080010029 opti++;
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080010030 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010031 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -070010032 dumpState.setDump(DumpState.DUMP_PACKAGES);
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010033 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -070010034 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010035 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -070010036 dumpState.setDump(DumpState.DUMP_PROVIDERS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010037 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -070010038 dumpState.setDump(DumpState.DUMP_MESSAGES);
Kenny Root05ca4c92011-09-15 10:36:25 -070010039 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
10040 dumpState.setDump(DumpState.DUMP_VERIFIERS);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -070010041 }
10042 }
Kenny Root447106f2011-03-23 11:00:15 -070010043
10044 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010045 synchronized (mPackages) {
Kenny Root05ca4c92011-09-15 10:36:25 -070010046 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
10047 if (dumpState.onTitlePrinted())
10048 pw.println(" ");
10049 pw.println("Verifiers:");
10050 pw.print(" Required: ");
10051 pw.print(mRequiredVerifierPackage);
10052 pw.print(" (uid=");
Amith Yamasani483f3b02012-03-13 16:08:00 -070010053 pw.print(getPackageUid(mRequiredVerifierPackage, 0));
Kenny Root05ca4c92011-09-15 10:36:25 -070010054 pw.println(")");
10055 }
10056
Kenny Root447106f2011-03-23 11:00:15 -070010057 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
10058 if (dumpState.onTitlePrinted())
10059 pw.println(" ");
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010060 pw.println("Libraries:");
Kenny Root447106f2011-03-23 11:00:15 -070010061 final Iterator<String> it = mSharedLibraries.keySet().iterator();
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010062 while (it.hasNext()) {
10063 String name = it.next();
10064 pw.print(" ");
10065 pw.print(name);
10066 pw.print(" -> ");
Dianne Hackbornc895be72013-03-11 17:48:43 -070010067 SharedLibraryEntry ent = mSharedLibraries.get(name);
10068 if (ent.path != null) {
10069 pw.print("(jar) ");
10070 pw.print(ent.path);
10071 } else {
10072 pw.print("(apk) ");
10073 pw.print(ent.apk);
10074 }
10075 pw.println();
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010076 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -070010077 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010078
Kenny Root447106f2011-03-23 11:00:15 -070010079 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
10080 if (dumpState.onTitlePrinted())
10081 pw.println(" ");
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010082 pw.println("Features:");
10083 Iterator<String> it = mAvailableFeatures.keySet().iterator();
10084 while (it.hasNext()) {
10085 String name = it.next();
10086 pw.print(" ");
10087 pw.println(name);
10088 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -070010089 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010090
Kenny Root447106f2011-03-23 11:00:15 -070010091 if (dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
10092 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
10093 : "Activity Resolver Table:", " ", packageName,
10094 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
10095 dumpState.setTitlePrinted(true);
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010096 }
Kenny Root447106f2011-03-23 11:00:15 -070010097 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
10098 : "Receiver Resolver Table:", " ", packageName,
10099 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
10100 dumpState.setTitlePrinted(true);
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010101 }
Kenny Root447106f2011-03-23 11:00:15 -070010102 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
10103 : "Service Resolver Table:", " ", packageName,
10104 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
10105 dumpState.setTitlePrinted(true);
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010106 }
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -070010107 }
10108
10109 if (dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
Dianne Hackborn63092712012-10-07 14:45:35 -070010110 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
10111 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
10112 int user = mSettings.mPreferredActivities.keyAt(i);
10113 if (pir.dump(pw,
10114 dumpState.getTitlePrinted()
10115 ? "\nPreferred Activities User " + user + ":"
10116 : "Preferred Activities User " + user + ":", " ",
10117 packageName, dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
10118 dumpState.setTitlePrinted(true);
10119 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010120 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -070010121 }
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -070010122
10123 if (dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
10124 pw.flush();
10125 FileOutputStream fout = new FileOutputStream(fd);
10126 BufferedOutputStream str = new BufferedOutputStream(fout);
10127 XmlSerializer serializer = new FastXmlSerializer();
10128 try {
10129 serializer.setOutput(str, "utf-8");
10130 serializer.startDocument(null, true);
10131 serializer.setFeature(
10132 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080010133 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
Dianne Hackbornfc8b7fe2012-06-18 15:38:12 -070010134 serializer.endDocument();
10135 serializer.flush();
10136 } catch (IllegalArgumentException e) {
10137 pw.println("Failed writing: " + e);
10138 } catch (IllegalStateException e) {
10139 pw.println("Failed writing: " + e);
10140 } catch (IOException e) {
10141 pw.println("Failed writing: " + e);
10142 }
10143 }
10144
Kenny Root447106f2011-03-23 11:00:15 -070010145 if (dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
10146 mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010147 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010148
Kenny Root447106f2011-03-23 11:00:15 -070010149 if (dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
10150 boolean printedSomething = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010151 for (PackageParser.Provider p : mProvidersByComponent.values()) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010152 if (packageName != null && !packageName.equals(p.info.packageName)) {
10153 continue;
10154 }
10155 if (!printedSomething) {
Kenny Root447106f2011-03-23 11:00:15 -070010156 if (dumpState.onTitlePrinted())
10157 pw.println(" ");
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010158 pw.println("Registered ContentProviders:");
10159 printedSomething = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010160 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010161 pw.print(" "); pw.print(p.getComponentShortName()); pw.println(":");
10162 pw.print(" "); pw.println(p.toString());
10163 }
10164 printedSomething = false;
10165 for (Map.Entry<String, PackageParser.Provider> entry : mProviders.entrySet()) {
10166 PackageParser.Provider p = entry.getValue();
10167 if (packageName != null && !packageName.equals(p.info.packageName)) {
10168 continue;
10169 }
10170 if (!printedSomething) {
10171 if (dumpState.onTitlePrinted())
10172 pw.println(" ");
10173 pw.println("ContentProvider Authorities:");
10174 printedSomething = true;
10175 }
10176 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:");
10177 pw.print(" "); pw.println(p.toString());
Kenny Rooteca64b32012-06-25 16:37:32 -070010178 if (p.info != null && p.info.applicationInfo != null) {
10179 final String appInfo = p.info.applicationInfo.toString();
10180 pw.print(" applicationInfo="); pw.println(appInfo);
10181 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010182 }
10183 }
10184
Kenny Root447106f2011-03-23 11:00:15 -070010185 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
10186 mSettings.dumpPackagesLPr(pw, packageName, dumpState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010187 }
Kenny Root447106f2011-03-23 11:00:15 -070010188
10189 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
10190 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -080010191 }
Kenny Root447106f2011-03-23 11:00:15 -070010192
10193 if (dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
10194 if (dumpState.onTitlePrinted())
10195 pw.println(" ");
10196 mSettings.dumpReadMessagesLPr(pw, dumpState);
10197
Dianne Hackbornd4310ac2010-03-16 22:55:08 -070010198 pw.println(" ");
10199 pw.println("Package warning messages:");
Kenny Root447106f2011-03-23 11:00:15 -070010200 final File fname = getSettingsProblemFile();
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -080010201 FileInputStream in = null;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -070010202 try {
10203 in = new FileInputStream(fname);
Kenny Root447106f2011-03-23 11:00:15 -070010204 final int avail = in.available();
10205 final byte[] data = new byte[avail];
Dianne Hackbornd4310ac2010-03-16 22:55:08 -070010206 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -070010207 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -070010208 } catch (FileNotFoundException e) {
10209 } catch (IOException e) {
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -080010210 } finally {
10211 if (in != null) {
10212 try {
10213 in.close();
Kenny Root447106f2011-03-23 11:00:15 -070010214 } catch (IOException e) {
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -080010215 }
10216 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -070010217 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -080010218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010219 }
10220 }
10221
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -080010222 // ------- apps on sdcard specific code -------
10223 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root447106f2011-03-23 11:00:15 -070010224
Kenny Root305bcbf2010-09-03 07:56:38 -070010225 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
Kenny Root447106f2011-03-23 11:00:15 -070010226
Kenny Root305bcbf2010-09-03 07:56:38 -070010227 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
Kenny Root447106f2011-03-23 11:00:15 -070010228
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080010229 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -080010230
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080010231 private String getEncryptKey() {
10232 try {
Kenny Root305bcbf2010-09-03 07:56:38 -070010233 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
10234 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080010235 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -070010236 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
10237 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080010238 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -080010239 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080010240 return null;
10241 }
10242 }
10243 return sdEncKey;
10244 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -080010245 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080010246 return null;
Rich Cannings8d578832010-09-09 15:12:40 -070010247 } catch (IOException ioe) {
Kenny Root447106f2011-03-23 11:00:15 -070010248 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
Rich Cannings8d578832010-09-09 15:12:40 -070010249 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080010250 }
Rich Cannings8d578832010-09-09 15:12:40 -070010251
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080010252 }
10253
Kenny Root447106f2011-03-23 11:00:15 -070010254 /* package */static String getTempContainerId() {
Kenny Rootc78a8072010-07-27 15:18:38 -070010255 int tmpIdx = 1;
10256 String list[] = PackageHelper.getSecureContainerList();
10257 if (list != null) {
10258 for (final String name : list) {
10259 // Ignore null and non-temporary container entries
10260 if (name == null || !name.startsWith(mTempContainerPrefix)) {
10261 continue;
10262 }
10263
10264 String subStr = name.substring(mTempContainerPrefix.length());
10265 try {
10266 int cid = Integer.parseInt(subStr);
10267 if (cid >= tmpIdx) {
10268 tmpIdx = cid + 1;
10269 }
10270 } catch (NumberFormatException e) {
10271 }
10272 }
10273 }
10274 return mTempContainerPrefix + tmpIdx;
10275 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -080010276
Kenny Root447106f2011-03-23 11:00:15 -070010277 /*
10278 * Update media status on PackageManager.
10279 */
10280 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
10281 int callingUid = Binder.getCallingUid();
10282 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
10283 throw new SecurityException("Media status can only be updated by the system");
10284 }
10285 // reader; this apparently protects mMediaMounted, but should probably
10286 // be a different lock in that case.
10287 synchronized (mPackages) {
10288 Log.i(TAG, "Updating external media status from "
10289 + (mMediaMounted ? "mounted" : "unmounted") + " to "
10290 + (mediaStatus ? "mounted" : "unmounted"));
10291 if (DEBUG_SD_INSTALL)
10292 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
10293 + ", mMediaMounted=" + mMediaMounted);
10294 if (mediaStatus == mMediaMounted) {
10295 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
10296 : 0, -1);
10297 mHandler.sendMessage(msg);
10298 return;
10299 }
10300 mMediaMounted = mediaStatus;
10301 }
10302 // Queue up an async operation since the package installation may take a
10303 // little while.
10304 mHandler.post(new Runnable() {
10305 public void run() {
Kenny Root438a0ef2012-08-09 13:36:16 -070010306 updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
Kenny Root447106f2011-03-23 11:00:15 -070010307 }
10308 });
10309 }
10310
Kenny Root51a573c2012-05-17 13:30:28 -070010311 /**
10312 * Called by MountService when the initial ASECs to scan are available.
10313 * Should block until all the ASEC containers are finished being scanned.
10314 */
10315 public void scanAvailableAsecs() {
Kenny Root438a0ef2012-08-09 13:36:16 -070010316 updateExternalMediaStatusInner(true, false, false);
Kenny Root51a573c2012-05-17 13:30:28 -070010317 }
10318
Kenny Root447106f2011-03-23 11:00:15 -070010319 /*
10320 * Collect information of applications on external media, map them against
10321 * existing containers and update information based on current mount status.
10322 * Please note that we always have to report status if reportStatus has been
10323 * set to true especially when unloading packages.
10324 */
Kenny Root438a0ef2012-08-09 13:36:16 -070010325 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
10326 boolean externalStorage) {
Kenny Root447106f2011-03-23 11:00:15 -070010327 // Collection of uids
10328 int uidArr[] = null;
10329 // Collection of stale containers
10330 HashSet<String> removeCids = new HashSet<String>();
10331 // Collection of packages on external media with valid containers.
Kenny Root6dceb882012-04-12 14:23:49 -070010332 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
Kenny Root447106f2011-03-23 11:00:15 -070010333 // Get list of secure containers.
10334 final String list[] = PackageHelper.getSecureContainerList();
10335 if (list == null || list.length == 0) {
10336 Log.i(TAG, "No secure containers on sdcard");
10337 } else {
10338 // Process list of secure containers and categorize them
10339 // as active or stale based on their package internal state.
10340 int uidList[] = new int[list.length];
10341 int num = 0;
10342 // reader
10343 synchronized (mPackages) {
10344 for (String cid : list) {
Kenny Root447106f2011-03-23 11:00:15 -070010345 if (DEBUG_SD_INSTALL)
10346 Log.i(TAG, "Processing container " + cid);
Kenny Rootc7a89992012-06-05 15:13:17 -070010347 String pkgName = getAsecPackageName(cid);
Kenny Root447106f2011-03-23 11:00:15 -070010348 if (pkgName == null) {
10349 if (DEBUG_SD_INSTALL)
10350 Log.i(TAG, "Container : " + cid + " stale");
10351 removeCids.add(cid);
10352 continue;
10353 }
10354 if (DEBUG_SD_INSTALL)
10355 Log.i(TAG, "Looking for pkg : " + pkgName);
Kenny Rootc7a89992012-06-05 15:13:17 -070010356
10357 final PackageSetting ps = mSettings.mPackages.get(pkgName);
10358 if (ps == null) {
10359 Log.i(TAG, "Deleting container with no matching settings " + cid);
10360 removeCids.add(cid);
10361 continue;
10362 }
10363
Kenny Root438a0ef2012-08-09 13:36:16 -070010364 /*
10365 * Skip packages that are not external if we're unmounting
10366 * external storage.
10367 */
10368 if (externalStorage && !isMounted && !isExternal(ps)) {
10369 continue;
10370 }
10371
Kenny Rootc7a89992012-06-05 15:13:17 -070010372 final AsecInstallArgs args = new AsecInstallArgs(cid, isForwardLocked(ps));
Kenny Root447106f2011-03-23 11:00:15 -070010373 // The package status is changed only if the code path
10374 // matches between settings and the container id.
Kenny Rootc7a89992012-06-05 15:13:17 -070010375 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
10376 if (DEBUG_SD_INSTALL) {
Kenny Root447106f2011-03-23 11:00:15 -070010377 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
10378 + " at code path: " + ps.codePathString);
Kenny Rootc7a89992012-06-05 15:13:17 -070010379 }
10380
Kenny Root447106f2011-03-23 11:00:15 -070010381 // We do have a valid package installed on sdcard
10382 processCids.put(args, ps.codePathString);
Kenny Rootc7a89992012-06-05 15:13:17 -070010383 final int uid = ps.appId;
Kenny Root447106f2011-03-23 11:00:15 -070010384 if (uid != -1) {
10385 uidList[num++] = uid;
10386 }
10387 } else {
Kenny Rootc7a89992012-06-05 15:13:17 -070010388 Log.i(TAG, "Deleting stale container for " + cid);
Kenny Root447106f2011-03-23 11:00:15 -070010389 removeCids.add(cid);
10390 }
10391 }
10392 }
10393
10394 if (num > 0) {
10395 // Sort uid list
10396 Arrays.sort(uidList, 0, num);
10397 // Throw away duplicates
10398 uidArr = new int[num];
10399 uidArr[0] = uidList[0];
10400 int di = 0;
10401 for (int i = 1; i < num; i++) {
10402 if (uidList[i - 1] != uidList[i]) {
10403 uidArr[di++] = uidList[i];
10404 }
10405 }
10406 }
10407 }
10408 // Process packages with valid entries.
Kenny Root6dceb882012-04-12 14:23:49 -070010409 if (isMounted) {
Kenny Root447106f2011-03-23 11:00:15 -070010410 if (DEBUG_SD_INSTALL)
10411 Log.i(TAG, "Loading packages");
10412 loadMediaPackages(processCids, uidArr, removeCids);
Jeff Sharkey752cd922012-09-23 16:25:12 -070010413 startCleaningPackages();
Kenny Root447106f2011-03-23 11:00:15 -070010414 } else {
10415 if (DEBUG_SD_INSTALL)
10416 Log.i(TAG, "Unloading packages");
10417 unloadMediaPackages(processCids, uidArr, reportStatus);
10418 }
10419 }
10420
10421 private void sendResourcesChangedBroadcast(boolean mediaStatus, ArrayList<String> pkgList,
10422 int uidArr[], IIntentReceiver finishedReceiver) {
10423 int size = pkgList.size();
10424 if (size > 0) {
10425 // Send broadcasts here
10426 Bundle extras = new Bundle();
10427 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
10428 .toArray(new String[size]));
10429 if (uidArr != null) {
10430 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
10431 }
10432 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
10433 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010434 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
Kenny Root447106f2011-03-23 11:00:15 -070010435 }
10436 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010437
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010438 /*
Kenny Root447106f2011-03-23 11:00:15 -070010439 * Look at potentially valid container ids from processCids If package
10440 * information doesn't match the one on record or package scanning fails,
10441 * the cid is added to list of removeCids. We currently don't delete stale
10442 * containers.
10443 */
Kenny Root6dceb882012-04-12 14:23:49 -070010444 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
Kenny Root447106f2011-03-23 11:00:15 -070010445 HashSet<String> removeCids) {
10446 ArrayList<String> pkgList = new ArrayList<String>();
Kenny Root6dceb882012-04-12 14:23:49 -070010447 Set<AsecInstallArgs> keys = processCids.keySet();
Kenny Root447106f2011-03-23 11:00:15 -070010448 boolean doGc = false;
Kenny Root6dceb882012-04-12 14:23:49 -070010449 for (AsecInstallArgs args : keys) {
Kenny Root447106f2011-03-23 11:00:15 -070010450 String codePath = processCids.get(args);
10451 if (DEBUG_SD_INSTALL)
10452 Log.i(TAG, "Loading container : " + args.cid);
10453 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10454 try {
10455 // Make sure there are no container errors first.
10456 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
10457 Slog.e(TAG, "Failed to mount cid : " + args.cid
10458 + " when installing from sdcard");
10459 continue;
10460 }
10461 // Check code path here.
10462 if (codePath == null || !codePath.equals(args.getCodePath())) {
10463 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
10464 + " does not match one in settings " + codePath);
10465 continue;
10466 }
10467 // Parse package
Kenny Root51a573c2012-05-17 13:30:28 -070010468 int parseFlags = mDefParseFlags;
10469 if (args.isExternal()) {
10470 parseFlags |= PackageParser.PARSE_ON_SDCARD;
10471 }
Kenny Rootc7a89992012-06-05 15:13:17 -070010472 if (args.isFwdLocked()) {
10473 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
10474 }
Kenny Root51a573c2012-05-17 13:30:28 -070010475
Kenny Root447106f2011-03-23 11:00:15 -070010476 doGc = true;
10477 synchronized (mInstallLock) {
10478 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010479 0, 0, null);
Kenny Root447106f2011-03-23 11:00:15 -070010480 // Scan the package
10481 if (pkg != null) {
10482 /*
10483 * TODO why is the lock being held? doPostInstall is
10484 * called in other places without the lock. This needs
10485 * to be straightened out.
10486 */
10487 // writer
10488 synchronized (mPackages) {
10489 retCode = PackageManager.INSTALL_SUCCEEDED;
10490 pkgList.add(pkg.packageName);
10491 // Post process args
Kenny Root6dceb882012-04-12 14:23:49 -070010492 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
10493 pkg.applicationInfo.uid);
Kenny Root447106f2011-03-23 11:00:15 -070010494 }
10495 } else {
10496 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard");
10497 }
10498 }
10499
10500 } finally {
10501 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
10502 // Don't destroy container here. Wait till gc clears things
10503 // up.
10504 removeCids.add(args.cid);
10505 }
10506 }
10507 }
10508 // writer
10509 synchronized (mPackages) {
10510 // If the platform SDK has changed since the last time we booted,
10511 // we need to re-grant app permission to catch any new ones that
10512 // appear. This is really a hack, and means that apps can in some
10513 // cases get permissions that the user didn't initially explicitly
10514 // allow... it would be nice to have some better way to handle
10515 // this situation.
10516 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
10517 if (regrantPermissions)
10518 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
10519 + mSdkVersion + "; regranting permissions for external storage");
10520 mSettings.mExternalSdkPlatform = mSdkVersion;
10521
10522 // Make sure group IDs have been assigned, and any permission
10523 // changes in other apps are accounted for
Dianne Hackborne639da72012-02-21 15:11:13 -080010524 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
10525 | (regrantPermissions
10526 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
10527 : 0));
Kenny Root447106f2011-03-23 11:00:15 -070010528 // can downgrade to reader
10529 // Persist settings
10530 mSettings.writeLPr();
10531 }
10532 // Send a broadcast to let everyone know we are done processing
10533 if (pkgList.size() > 0) {
10534 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
10535 }
10536 // Force gc to avoid any stale parser references that we might have.
10537 if (doGc) {
10538 Runtime.getRuntime().gc();
10539 }
10540 // List stale containers and destroy stale temporary containers.
10541 if (removeCids != null) {
10542 for (String cid : removeCids) {
10543 if (cid.startsWith(mTempContainerPrefix)) {
10544 Log.i(TAG, "Destroying stale temporary container " + cid);
10545 PackageHelper.destroySdDir(cid);
10546 } else {
10547 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080010548 }
10549 }
Kenny Root447106f2011-03-23 11:00:15 -070010550 }
10551 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010552
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010553 /*
Kenny Root447106f2011-03-23 11:00:15 -070010554 * Utility method to unload a list of specified containers
10555 */
Kenny Root6dceb882012-04-12 14:23:49 -070010556 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
Kenny Root447106f2011-03-23 11:00:15 -070010557 // Just unmount all valid containers.
Kenny Root6dceb882012-04-12 14:23:49 -070010558 for (AsecInstallArgs arg : cidArgs) {
Kenny Root447106f2011-03-23 11:00:15 -070010559 synchronized (mInstallLock) {
10560 arg.doPostDeleteLI(false);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010561 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010562 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010563 }
10564
Kenny Root447106f2011-03-23 11:00:15 -070010565 /*
10566 * Unload packages mounted on external media. This involves deleting package
10567 * data from internal structures, sending broadcasts about diabled packages,
10568 * gc'ing to free up references, unmounting all secure containers
10569 * corresponding to packages on external media, and posting a
10570 * UPDATED_MEDIA_STATUS message if status has been requested. Please note
10571 * that we always have to post this message if status has been requested no
10572 * matter what.
10573 */
Kenny Root6dceb882012-04-12 14:23:49 -070010574 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
Kenny Root447106f2011-03-23 11:00:15 -070010575 final boolean reportStatus) {
10576 if (DEBUG_SD_INSTALL)
10577 Log.i(TAG, "unloading media packages");
10578 ArrayList<String> pkgList = new ArrayList<String>();
Kenny Root6dceb882012-04-12 14:23:49 -070010579 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
10580 final Set<AsecInstallArgs> keys = processCids.keySet();
10581 for (AsecInstallArgs args : keys) {
Kenny Root447106f2011-03-23 11:00:15 -070010582 String pkgName = args.getPackageName();
10583 if (DEBUG_SD_INSTALL)
10584 Log.i(TAG, "Trying to unload pkg : " + pkgName);
10585 // Delete package internally
10586 PackageRemovedInfo outInfo = new PackageRemovedInfo();
10587 synchronized (mInstallLock) {
Christopher Tateacee6e92013-05-14 16:11:44 -070010588 boolean res = deletePackageLI(pkgName, null, false, null, null,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010589 PackageManager.DELETE_KEEP_DATA, outInfo, false);
Kenny Root447106f2011-03-23 11:00:15 -070010590 if (res) {
10591 pkgList.add(pkgName);
10592 } else {
10593 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
10594 failedList.add(args);
10595 }
10596 }
10597 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010598
Kenny Root447106f2011-03-23 11:00:15 -070010599 // reader
10600 synchronized (mPackages) {
10601 // We didn't update the settings after removing each package;
10602 // write them now for all packages.
10603 mSettings.writeLPr();
10604 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -070010605
Kenny Root447106f2011-03-23 11:00:15 -070010606 // We have to absolutely send UPDATED_MEDIA_STATUS only
10607 // after confirming that all the receivers processed the ordered
10608 // broadcast when packages get disabled, force a gc to clean things up.
10609 // and unload all the containers.
10610 if (pkgList.size() > 0) {
10611 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
10612 public void performReceive(Intent intent, int resultCode, String data,
Dianne Hackborn20e80982012-08-31 19:00:44 -070010613 Bundle extras, boolean ordered, boolean sticky,
10614 int sendingUser) throws RemoteException {
Kenny Root447106f2011-03-23 11:00:15 -070010615 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
10616 reportStatus ? 1 : 0, 1, keys);
10617 mHandler.sendMessage(msg);
10618 }
10619 });
10620 } else {
10621 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
10622 keys);
10623 mHandler.sendMessage(msg);
10624 }
10625 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -070010626
Amith Yamasani6ec10122012-08-23 13:49:25 -070010627 /** Binder call */
10628 @Override
Kenny Root447106f2011-03-23 11:00:15 -070010629 public void movePackage(final String packageName, final IPackageMoveObserver observer,
10630 final int flags) {
10631 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
Amith Yamasani6ec10122012-08-23 13:49:25 -070010632 UserHandle user = new UserHandle(UserHandle.getCallingUserId());
Kenny Root447106f2011-03-23 11:00:15 -070010633 int returnCode = PackageManager.MOVE_SUCCEEDED;
10634 int currFlags = 0;
10635 int newFlags = 0;
10636 // reader
10637 synchronized (mPackages) {
10638 PackageParser.Package pkg = mPackages.get(packageName);
10639 if (pkg == null) {
10640 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
10641 } else {
10642 // Disable moving fwd locked apps and system packages
10643 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
10644 Slog.w(TAG, "Cannot move system application");
10645 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root447106f2011-03-23 11:00:15 -070010646 } else if (pkg.mOperationPending) {
10647 Slog.w(TAG, "Attempt to move package which has pending operations");
10648 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
10649 } else {
10650 // Find install location first
10651 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
10652 && (flags & PackageManager.MOVE_INTERNAL) != 0) {
10653 Slog.w(TAG, "Ambigous flags specified for move location.");
10654 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
10655 } else {
10656 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
10657 : PackageManager.INSTALL_INTERNAL;
10658 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
10659 : PackageManager.INSTALL_INTERNAL;
Kenny Rootbf023582012-05-02 16:56:15 -070010660
Kenny Root447106f2011-03-23 11:00:15 -070010661 if (newFlags == currFlags) {
10662 Slog.w(TAG, "No move required. Trying to move to same location");
10663 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Kenny Rootbf023582012-05-02 16:56:15 -070010664 } else {
10665 if (isForwardLocked(pkg)) {
10666 currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10667 newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10668 }
Kenny Root447106f2011-03-23 11:00:15 -070010669 }
10670 }
10671 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10672 pkg.mOperationPending = true;
10673 }
10674 }
10675 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010676
Kenny Root447106f2011-03-23 11:00:15 -070010677 /*
10678 * TODO this next block probably shouldn't be inside the lock. We
10679 * can't guarantee these won't change after this is fired off
10680 * anyway.
10681 */
10682 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Amith Yamasani6ec10122012-08-23 13:49:25 -070010683 processPendingMove(new MoveParams(null, observer, 0, packageName,
10684 null, -1, user),
Kenny Root6dceb882012-04-12 14:23:49 -070010685 returnCode);
Kenny Root447106f2011-03-23 11:00:15 -070010686 } else {
10687 Message msg = mHandler.obtainMessage(INIT_COPY);
10688 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -070010689 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
Kenny Root447106f2011-03-23 11:00:15 -070010690 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
Amith Yamasani6ec10122012-08-23 13:49:25 -070010691 pkg.applicationInfo.dataDir, pkg.applicationInfo.uid, user);
Kenny Root447106f2011-03-23 11:00:15 -070010692 msg.obj = mp;
10693 mHandler.sendMessage(msg);
10694 }
10695 }
10696 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010697
Kenny Root447106f2011-03-23 11:00:15 -070010698 private void processPendingMove(final MoveParams mp, final int currentStatus) {
10699 // Queue up an async operation since the package deletion may take a
10700 // little while.
10701 mHandler.post(new Runnable() {
10702 public void run() {
10703 // TODO fix this; this does nothing.
10704 mHandler.removeCallbacks(this);
10705 int returnCode = currentStatus;
10706 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
10707 int uidArr[] = null;
10708 ArrayList<String> pkgList = null;
10709 synchronized (mPackages) {
10710 PackageParser.Package pkg = mPackages.get(mp.packageName);
10711 if (pkg == null) {
10712 Slog.w(TAG, " Package " + mp.packageName
10713 + " doesn't exist. Aborting move");
10714 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
10715 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10716 Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
10717 + mp.srcArgs.getCodePath() + " to "
10718 + pkg.applicationInfo.sourceDir
10719 + " Aborting move and returning error");
10720 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10721 } else {
10722 uidArr = new int[] {
10723 pkg.applicationInfo.uid
10724 };
10725 pkgList = new ArrayList<String>();
10726 pkgList.add(mp.packageName);
10727 }
10728 }
10729 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10730 // Send resources unavailable broadcast
10731 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
10732 // Update package code and resource paths
10733 synchronized (mInstallLock) {
10734 synchronized (mPackages) {
10735 PackageParser.Package pkg = mPackages.get(mp.packageName);
10736 // Recheck for package again.
Kenny Root6a6b0072010-10-07 16:46:10 -070010737 if (pkg == null) {
10738 Slog.w(TAG, " Package " + mp.packageName
10739 + " doesn't exist. Aborting move");
10740 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Kenny Root447106f2011-03-23 11:00:15 -070010741 } else if (!mp.srcArgs.getCodePath().equals(
10742 pkg.applicationInfo.sourceDir)) {
10743 Slog.w(TAG, "Package " + mp.packageName
10744 + " code path changed from " + mp.srcArgs.getCodePath()
10745 + " to " + pkg.applicationInfo.sourceDir
10746 + " Aborting move and returning error");
10747 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10748 } else {
10749 final String oldCodePath = pkg.mPath;
10750 final String newCodePath = mp.targetArgs.getCodePath();
10751 final String newResPath = mp.targetArgs.getResourcePath();
10752 final String newNativePath = mp.targetArgs
10753 .getNativeLibraryPath();
Kenny Root6a6b0072010-10-07 16:46:10 -070010754
Kenny Rootddbe50d2012-09-06 13:18:37 -070010755 final File newNativeDir = new File(newNativePath);
Kenny Rootbf023582012-05-02 16:56:15 -070010756
Kenny Rootddbe50d2012-09-06 13:18:37 -070010757 if (!isForwardLocked(pkg) && !isExternal(pkg)) {
Kenny Roota3e90792012-10-18 10:58:36 -070010758 NativeLibraryHelper.copyNativeBinariesIfNeededLI(
10759 new File(newCodePath), newNativeDir);
10760 }
10761 final int[] users = sUserManager.getUserIds();
10762 for (int user : users) {
10763 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
10764 newNativePath, user) < 0) {
10765 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
Kenny Rootddbe50d2012-09-06 13:18:37 -070010766 }
Kenny Root6a6b0072010-10-07 16:46:10 -070010767 }
10768
10769 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10770 pkg.mPath = newCodePath;
10771 // Move dex files around
10772 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
10773 // Moving of dex files failed. Set
10774 // error code and abort move.
10775 pkg.mPath = pkg.mScanPath;
10776 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10777 }
10778 }
10779
10780 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
Kenny Root447106f2011-03-23 11:00:15 -070010781 pkg.mScanPath = newCodePath;
10782 pkg.applicationInfo.sourceDir = newCodePath;
10783 pkg.applicationInfo.publicSourceDir = newResPath;
10784 pkg.applicationInfo.nativeLibraryDir = newNativePath;
10785 PackageSetting ps = (PackageSetting) pkg.mExtras;
10786 ps.codePath = new File(pkg.applicationInfo.sourceDir);
10787 ps.codePathString = ps.codePath.getPath();
10788 ps.resourcePath = new File(
10789 pkg.applicationInfo.publicSourceDir);
10790 ps.resourcePathString = ps.resourcePath.getPath();
10791 ps.nativeLibraryPathString = newNativePath;
10792 // Set the application info flag
10793 // correctly.
10794 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
10795 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10796 } else {
10797 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10798 }
10799 ps.setFlags(pkg.applicationInfo.flags);
10800 mAppDirs.remove(oldCodePath);
10801 mAppDirs.put(newCodePath, pkg);
10802 // Persist settings
10803 mSettings.writeLPr();
10804 }
10805 }
10806 }
10807 }
10808 // Send resources available broadcast
10809 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
10810 }
10811 }
10812 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
10813 // Clean up failed installation
10814 if (mp.targetArgs != null) {
Kenny Root6dceb882012-04-12 14:23:49 -070010815 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
10816 -1);
Kenny Root447106f2011-03-23 11:00:15 -070010817 }
10818 } else {
10819 // Force a gc to clear things up.
10820 Runtime.getRuntime().gc();
10821 // Delete older code
10822 synchronized (mInstallLock) {
10823 mp.srcArgs.doPostDeleteLI(true);
10824 }
10825 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010826
Kenny Root447106f2011-03-23 11:00:15 -070010827 // Allow more operations on this file if we didn't fail because
10828 // an operation was already pending for this package.
10829 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
10830 synchronized (mPackages) {
10831 PackageParser.Package pkg = mPackages.get(mp.packageName);
10832 if (pkg != null) {
10833 pkg.mOperationPending = false;
Kenny Rootdeb11262010-08-02 11:36:21 -070010834 }
10835 }
Kenny Root447106f2011-03-23 11:00:15 -070010836 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010837
Kenny Root447106f2011-03-23 11:00:15 -070010838 IPackageMoveObserver observer = mp.observer;
10839 if (observer != null) {
10840 try {
10841 observer.packageMoved(mp.packageName, returnCode);
10842 } catch (RemoteException e) {
10843 Log.i(TAG, "Observer no longer exists.");
10844 }
10845 }
10846 }
10847 });
10848 }
10849
10850 public boolean setInstallLocation(int loc) {
10851 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
10852 null);
10853 if (getInstallLocation() == loc) {
10854 return true;
10855 }
10856 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
10857 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
Jeff Sharkey625239a2012-09-26 22:03:49 -070010858 android.provider.Settings.Global.putInt(mContext.getContentResolver(),
10859 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
Kenny Root447106f2011-03-23 11:00:15 -070010860 return true;
10861 }
10862 return false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010863 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070010864
Kenny Root447106f2011-03-23 11:00:15 -070010865 public int getInstallLocation() {
Jeff Sharkey625239a2012-09-26 22:03:49 -070010866 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10867 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
Kenny Root447106f2011-03-23 11:00:15 -070010868 PackageHelper.APP_INSTALL_AUTO);
10869 }
Amith Yamasani0b285492011-04-14 17:35:23 -070010870
Amith Yamasani258848d2012-08-10 17:06:33 -070010871 /** Called by UserManagerService */
Dianne Hackborn4428e172012-08-24 17:43:05 -070010872 void cleanUpUserLILPw(int userHandle) {
Christopher Tate1e08f5c2013-05-02 13:27:27 -070010873 mDirtyUsers.remove(userHandle);
Dianne Hackborn4428e172012-08-24 17:43:05 -070010874 mSettings.removeUserLPr(userHandle);
Christopher Tate1e08f5c2013-05-02 13:27:27 -070010875 mPendingBroadcasts.remove(userHandle);
Dianne Hackborn4428e172012-08-24 17:43:05 -070010876 if (mInstaller != null) {
10877 // Technically, we shouldn't be doing this with the package lock
10878 // held. However, this is very rare, and there is already so much
10879 // other disk I/O going on, that we'll let it slide for now.
10880 mInstaller.removeUserDataDirs(userHandle);
10881 }
10882 }
10883
10884 /** Called by UserManagerService */
10885 void createNewUserLILPw(int userHandle, File path) {
10886 if (mInstaller != null) {
Dianne Hackborn8a2ed1d2013-01-29 15:18:29 -080010887 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
Amith Yamasani13593602012-03-22 16:16:17 -070010888 }
10889 }
10890
Kenny Root0aaa0d92011-09-12 16:42:55 -070010891 @Override
10892 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
10893 mContext.enforceCallingOrSelfPermission(
10894 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10895 "Only package verification agents can read the verifier device identity");
10896
10897 synchronized (mPackages) {
10898 return mSettings.getVerifierDeviceIdentityLPw();
10899 }
10900 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010901
Amith Yamasani13593602012-03-22 16:16:17 -070010902 @Override
Jeff Sharkey5d32e772012-04-12 15:59:23 -070010903 public void setPermissionEnforced(String permission, boolean enforced) {
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -070010904 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
10905 if (READ_EXTERNAL_STORAGE.equals(permission)) {
10906 synchronized (mPackages) {
Jeff Sharkeyf5385772012-05-11 14:04:41 -070010907 if (mSettings.mReadExternalStorageEnforced == null
10908 || mSettings.mReadExternalStorageEnforced != enforced) {
Jeff Sharkey5d32e772012-04-12 15:59:23 -070010909 mSettings.mReadExternalStorageEnforced = enforced;
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -070010910 mSettings.writeLPr();
Dianne Hackbornf1b78242013-04-08 22:28:59 -070010911 }
10912 }
10913 // kill any non-foreground processes so we restart them and
10914 // grant/revoke the GID.
10915 final IActivityManager am = ActivityManagerNative.getDefault();
10916 if (am != null) {
10917 final long token = Binder.clearCallingIdentity();
10918 try {
10919 am.killProcessesBelowForeground("setPermissionEnforcement");
10920 } catch (RemoteException e) {
10921 } finally {
10922 Binder.restoreCallingIdentity(token);
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -070010923 }
10924 }
10925 } else {
10926 throw new IllegalArgumentException("No selective enforcement for " + permission);
10927 }
10928 }
10929
10930 @Override
Jeff Sharkey5d32e772012-04-12 15:59:23 -070010931 public boolean isPermissionEnforced(String permission) {
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -070010932 final boolean enforcedDefault = isPermissionEnforcedDefault(permission);
Jeff Sharkey5d32e772012-04-12 15:59:23 -070010933 synchronized (mPackages) {
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -070010934 return isPermissionEnforcedLocked(permission, enforcedDefault);
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -070010935 }
10936 }
10937
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -070010938 /**
10939 * Check if given permission should be enforced by default. Should always be
10940 * called outside of {@link #mPackages} lock.
10941 */
10942 private boolean isPermissionEnforcedDefault(String permission) {
10943 if (READ_EXTERNAL_STORAGE.equals(permission)) {
Jeff Sharkey625239a2012-09-26 22:03:49 -070010944 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10945 android.provider.Settings.Global.READ_EXTERNAL_STORAGE_ENFORCED_DEFAULT, 0)
10946 != 0;
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -070010947 } else {
10948 return true;
10949 }
10950 }
10951
10952 /**
10953 * Check if user has requested that given permission be enforced, using
10954 * given default if undefined.
10955 */
10956 private boolean isPermissionEnforcedLocked(String permission, boolean enforcedDefault) {
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -070010957 if (READ_EXTERNAL_STORAGE.equals(permission)) {
Jeff Sharkeyf5385772012-05-11 14:04:41 -070010958 if (mSettings.mReadExternalStorageEnforced != null) {
10959 return mSettings.mReadExternalStorageEnforced;
10960 } else {
Jeff Sharkeyc50f31d2012-09-22 17:14:02 -070010961 // User hasn't defined; fall back to secure default
10962 return enforcedDefault;
Jeff Sharkeyf5385772012-05-11 14:04:41 -070010963 }
Jeff Sharkey5d32e772012-04-12 15:59:23 -070010964 } else {
10965 return true;
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -070010966 }
Jeff Sharkeyedc84ee82012-03-19 16:52:26 -070010967 }
Jeff Sharkeyf6f7f1d2012-06-12 17:12:08 -070010968
10969 public boolean isStorageLow() {
10970 final long token = Binder.clearCallingIdentity();
10971 try {
10972 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
10973 .getService(DeviceStorageMonitorService.SERVICE);
10974 return dsm.isMemoryLow();
10975 } finally {
10976 Binder.restoreCallingIdentity(token);
10977 }
10978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010979}