blob: 9f45effc8c6618945b315f8a87271e29e937d249 [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
Kenny Root27989422011-02-23 16:28:26 -080019import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
20import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
Dianne Hackborn0ac30312011-06-17 14:49:23 -070021import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
Kenny Root27989422011-02-23 16:28:26 -080022import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
Kenny Root66269ea2011-07-12 14:14:01 -070023import static libcore.io.OsConstants.S_ISLNK;
Kenny Root27989422011-02-23 16:28:26 -080024
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080025import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import com.android.internal.app.ResolverActivity;
Kenny Root85387d72010-08-26 10:13:11 -070027import com.android.internal.content.NativeLibraryHelper;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080028import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080029import com.android.internal.util.XmlUtils;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070030import com.android.server.DeviceStorageMonitorService;
31import com.android.server.EventLogTags;
32import com.android.server.IntentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033
Jason parksa3cdaa52011-01-13 14:15:43 -060034import org.xmlpull.v1.XmlPullParser;
35import org.xmlpull.v1.XmlPullParserException;
Jason parksa3cdaa52011-01-13 14:15:43 -060036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.app.ActivityManagerNative;
38import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080039import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080040import android.app.backup.IBackupManager;
Kenny Root5ab21572011-07-27 11:11:19 -070041import android.content.BroadcastReceiver;
Jason parksa3cdaa52011-01-13 14:15:43 -060042import android.content.ComponentName;
Kenny Root27989422011-02-23 16:28:26 -080043import android.content.Context;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070044import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.Intent;
46import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070047import android.content.IntentSender;
Jason parks1125d782011-01-12 09:47:26 -060048import android.content.ServiceConnection;
Jason parksa3cdaa52011-01-13 14:15:43 -060049import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.content.pm.ActivityInfo;
51import android.content.pm.ApplicationInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070052import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.content.pm.IPackageDataObserver;
54import android.content.pm.IPackageDeleteObserver;
55import android.content.pm.IPackageInstallObserver;
56import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080057import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.content.pm.IPackageStatsObserver;
59import android.content.pm.InstrumentationInfo;
60import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080061import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.content.pm.PackageManager;
Jason parksa3cdaa52011-01-13 14:15:43 -060063import android.content.pm.PackageParser;
Kenny Root27989422011-02-23 16:28:26 -080064import android.content.pm.PackageStats;
Kenny Root0e2c0f32011-04-15 17:50:10 -070065import android.content.pm.ParceledListSlice;
Jason parksa3cdaa52011-01-13 14:15:43 -060066import android.content.pm.PermissionGroupInfo;
Kenny Root27989422011-02-23 16:28:26 -080067import android.content.pm.PermissionInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.content.pm.ProviderInfo;
69import android.content.pm.ResolveInfo;
70import android.content.pm.ServiceInfo;
71import android.content.pm.Signature;
Amith Yamasani0b285492011-04-14 17:35:23 -070072import android.content.pm.UserInfo;
Kenny Root5ab21572011-07-27 11:11:19 -070073import android.content.pm.ManifestDigest;
Kenny Root0aaa0d92011-09-12 16:42:55 -070074import android.content.pm.VerifierDeviceIdentity;
Kenny Root05ca4c92011-09-15 10:36:25 -070075import android.content.pm.VerifierInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.net.Uri;
77import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070078import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.os.Bundle;
Kenny Root27989422011-02-23 16:28:26 -080080import android.os.Environment;
81import android.os.FileObserver;
82import android.os.FileUtils;
83import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080085import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070086import android.os.Looper;
87import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.os.Parcel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.os.ParcelFileDescriptor;
90import android.os.Process;
Kenny Root27989422011-02-23 16:28:26 -080091import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.os.ServiceManager;
93import android.os.SystemClock;
94import android.os.SystemProperties;
Amith Yamasani742a6712011-05-04 14:49:28 -070095import android.os.UserId;
Oscar Montemayord02546b2010-01-14 16:38:40 -080096import android.security.SystemKeyStore;
Kenny Root27989422011-02-23 16:28:26 -080097import android.util.DisplayMetrics;
98import android.util.EventLog;
99import android.util.Log;
100import android.util.LogPrinter;
101import android.util.Slog;
102import android.util.SparseArray;
103import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import android.view.Display;
105import android.view.WindowManager;
106
107import java.io.File;
108import java.io.FileDescriptor;
109import java.io.FileInputStream;
110import java.io.FileNotFoundException;
111import java.io.FileOutputStream;
112import java.io.FileReader;
113import java.io.FilenameFilter;
114import java.io.IOException;
115import java.io.InputStream;
116import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800117import java.security.NoSuchAlgorithmException;
Kenny Root05ca4c92011-09-15 10:36:25 -0700118import java.security.PublicKey;
119import java.security.cert.CertificateException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800120import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121import java.util.ArrayList;
122import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700123import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import java.util.Collections;
125import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800126import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127import java.util.Enumeration;
128import java.util.HashMap;
129import java.util.HashSet;
130import java.util.Iterator;
131import java.util.List;
132import java.util.Map;
133import java.util.Set;
134import java.util.zip.ZipEntry;
135import java.util.zip.ZipFile;
136import java.util.zip.ZipOutputStream;
137
Kenny Root66269ea2011-07-12 14:14:01 -0700138import libcore.io.ErrnoException;
139import libcore.io.Libcore;
140
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700141/**
142 * Keep track of all those .apks everywhere.
143 *
144 * This is very central to the platform's security; please run the unit
145 * tests whenever making modifications here:
146 *
147mmm frameworks/base/tests/AndroidTests
148adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
149adb 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 -0700150 *
151 * {@hide}
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700152 */
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700153public class PackageManagerService extends IPackageManager.Stub {
154 static final String TAG = "PackageManager";
155 static final boolean DEBUG_SETTINGS = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156 private static final boolean DEBUG_PREFERRED = false;
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700157 static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800158 private static final boolean DEBUG_INSTALL = false;
Kenny Root9718cf52011-02-23 16:45:26 -0800159 private static final boolean DEBUG_REMOVE = false;
160 private static final boolean DEBUG_SHOW_INFO = false;
161 private static final boolean DEBUG_PACKAGE_INFO = false;
162 private static final boolean DEBUG_INTENT_MATCHING = false;
163 private static final boolean DEBUG_PACKAGE_SCANNING = false;
164 private static final boolean DEBUG_APP_DIR_OBSERVER = false;
Kenny Root05ca4c92011-09-15 10:36:25 -0700165 private static final boolean DEBUG_VERIFY = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400168 private static final int LOG_UID = Process.LOG_UID;
Nick Pellycd0e8392010-10-13 17:25:24 -0700169 private static final int NFC_UID = Process.NFC_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 private static final boolean GET_CERTIFICATES = true;
172
173 private static final int REMOVE_EVENTS =
174 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
175 private static final int ADD_EVENTS =
176 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
177
178 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800179 // Suffix used during package installation when copying/moving
180 // package apks to install directory.
181 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182
183 static final int SCAN_MONITOR = 1<<0;
184 static final int SCAN_NO_DEX = 1<<1;
185 static final int SCAN_FORCE_DEX = 1<<2;
186 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800187 static final int SCAN_NEW_INSTALL = 1<<4;
188 static final int SCAN_NO_PATHS = 1<<5;
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700189 static final int SCAN_UPDATE_TIME = 1<<6;
Dianne Hackborn661cd522011-08-22 00:26:20 -0700190 static final int SCAN_DEFER_DEX = 1<<7;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700192 static final int REMOVE_CHATTY = 1<<16;
Kenny Root11128572010-10-11 10:51:32 -0700193
Kenny Root5ab21572011-07-27 11:11:19 -0700194 /**
195 * Whether verification is enabled by default.
196 */
Brett Chabotae05e862011-08-24 18:38:26 -0700197 // STOPSHIP: change this to true
198 private static final boolean DEFAULT_VERIFY_ENABLE = false;
Kenny Root5ab21572011-07-27 11:11:19 -0700199
200 /**
201 * The default maximum time to wait for the verification agent to return in
202 * milliseconds.
203 */
204 private static final long DEFAULT_VERIFICATION_TIMEOUT = 60 * 1000;
205
Kenny Root11128572010-10-11 10:51:32 -0700206 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
207
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800208 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
Kenny Root11128572010-10-11 10:51:32 -0700209 DEFAULT_CONTAINER_PACKAGE,
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800210 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700211
Kenny Root05ca4c92011-09-15 10:36:25 -0700212 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
213
Kenny Root85387d72010-08-26 10:13:11 -0700214 private static final String LIB_DIR_NAME = "lib";
215
Kenny Rootc78a8072010-07-27 15:18:38 -0700216 static final String mTempContainerPrefix = "smdl2tmp";
217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
219 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700220 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221
Dianne Hackborn851a5412009-05-08 12:06:44 -0700222 final int mSdkVersion = Build.VERSION.SDK_INT;
223 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
224 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 final Context mContext;
227 final boolean mFactoryTest;
Dianne Hackbornd2509fd2011-09-12 12:29:43 -0700228 final boolean mOnlyCore;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700229 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 final DisplayMetrics mMetrics;
231 final int mDefParseFlags;
232 final String[] mSeparateProcesses;
233
234 // This is where all application persistent data goes.
235 final File mAppDataDir;
236
Amith Yamasani0b285492011-04-14 17:35:23 -0700237 // This is where all application persistent data goes for secondary users.
238 final File mUserAppDataDir;
239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 // This is the object monitoring the framework dir.
241 final FileObserver mFrameworkInstallObserver;
242
243 // This is the object monitoring the system app dir.
244 final FileObserver mSystemInstallObserver;
245
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700246 // This is the object monitoring the system app dir.
247 final FileObserver mVendorInstallObserver;
248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 // This is the object monitoring mAppInstallDir.
250 final FileObserver mAppInstallObserver;
251
252 // This is the object monitoring mDrmAppPrivateInstallDir.
253 final FileObserver mDrmAppInstallObserver;
254
255 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
256 // LOCK HELD. Can be called with mInstallLock held.
257 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 final File mFrameworkDir;
260 final File mSystemAppDir;
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700261 final File mVendorAppDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700263 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264
265 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
266 // apps.
267 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271 // Lock for state used when installing and doing other long running
272 // operations. Methods that must be called with this lock held have
273 // the prefix "LI".
274 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 // These are the directories in the 3rd party applications installed dir
277 // that we have currently loaded packages from. Keys are the application's
278 // installed zip file (absolute codePath), and values are Package.
279 final HashMap<String, PackageParser.Package> mAppDirs =
280 new HashMap<String, PackageParser.Package>();
281
282 // Information for the parser to write more useful error messages.
283 File mScanningPath;
284 int mLastScanError;
285
286 final int[] mOutPermissions = new int[3];
287
288 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290 // Keys are String (package name), values are Package. This also serves
291 // as the lock for the global state. Methods that must be called with
292 // this lock held have the prefix "LP".
293 final HashMap<String, PackageParser.Package> mPackages =
294 new HashMap<String, PackageParser.Package>();
295
296 final Settings mSettings;
297 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298
299 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
300 int[] mGlobalGids;
301
302 // These are the built-in uid -> permission mappings that were read from the
303 // etc/permissions.xml file.
304 final SparseArray<HashSet<String>> mSystemPermissions =
305 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307 // These are the built-in shared libraries that were read from the
308 // etc/permissions.xml file.
309 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800310
Dianne Hackborn49237342009-08-27 20:08:01 -0700311 // Temporary for building the final shared libraries for an .apk.
312 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800313
Dianne Hackborn49237342009-08-27 20:08:01 -0700314 // These are the features this devices supports that were read from the
315 // etc/permissions.xml file.
316 final HashMap<String, FeatureInfo> mAvailableFeatures =
317 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 // All available activities, for your resolving pleasure.
320 final ActivityIntentResolver mActivities =
321 new ActivityIntentResolver();
322
323 // All available receivers, for your resolving pleasure.
324 final ActivityIntentResolver mReceivers =
325 new ActivityIntentResolver();
326
327 // All available services, for your resolving pleasure.
328 final ServiceIntentResolver mServices = new ServiceIntentResolver();
329
330 // Keys are String (provider class name), values are Provider.
331 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
332 new HashMap<ComponentName, PackageParser.Provider>();
333
334 // Mapping from provider base names (first directory in content URI codePath)
335 // to the provider information.
336 final HashMap<String, PackageParser.Provider> mProviders =
337 new HashMap<String, PackageParser.Provider>();
338
339 // Mapping from instrumentation class names to info about them.
340 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
341 new HashMap<ComponentName, PackageParser.Instrumentation>();
342
343 // Mapping from permission names to info about them.
344 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
345 new HashMap<String, PackageParser.PermissionGroup>();
346
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800347 // Packages whose data we have transfered into another package, thus
348 // should no longer exist.
349 final HashSet<String> mTransferedPackages = new HashSet<String>();
350
Dianne Hackborn854060af2009-07-09 18:14:31 -0700351 // Broadcast actions that are only available to the system.
352 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800353
Kenny Root5ab21572011-07-27 11:11:19 -0700354 /** List of packages waiting for verification. */
Kenny Root05ca4c92011-09-15 10:36:25 -0700355 final SparseArray<PackageVerificationState> mPendingVerification
356 = new SparseArray<PackageVerificationState>();
Kenny Root5ab21572011-07-27 11:11:19 -0700357
Dianne Hackborn661cd522011-08-22 00:26:20 -0700358 final ArrayList<PackageParser.Package> mDeferredDexOpt =
359 new ArrayList<PackageParser.Package>();
360
Kenny Root5ab21572011-07-27 11:11:19 -0700361 /** Token for keys in mPendingVerification. */
362 private int mPendingVerificationToken = 0;
363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 boolean mSystemReady;
365 boolean mSafeMode;
366 boolean mHasSystemUidErrors;
367
368 ApplicationInfo mAndroidApplication;
369 final ActivityInfo mResolveActivity = new ActivityInfo();
370 final ResolveInfo mResolveInfo = new ResolveInfo();
371 ComponentName mResolveComponentName;
372 PackageParser.Package mPlatformPackage;
373
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700374 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800375 final HashMap<String, ArrayList<String>> mPendingBroadcasts
376 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800377 // Service Connection to remote media container service to copy
378 // package uri's from external media onto secure containers
379 // or internal storage.
380 private IMediaContainerService mContainerService = null;
381
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700382 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800383 static final int MCS_BOUND = 3;
384 static final int END_COPY = 4;
385 static final int INIT_COPY = 5;
386 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800387 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800388 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800389 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800390 static final int MCS_RECONNECT = 10;
391 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700392 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700393 static final int WRITE_SETTINGS = 13;
Dianne Hackborne7f97212011-02-24 14:40:20 -0800394 static final int WRITE_STOPPED_PACKAGES = 14;
Kenny Root5ab21572011-07-27 11:11:19 -0700395 static final int PACKAGE_VERIFIED = 15;
396 static final int CHECK_PENDING_VERIFICATION = 16;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700397
398 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800399
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700400 // Delay time in millisecs
401 static final int BROADCAST_DELAY = 10 * 1000;
Kenny Root9718cf52011-02-23 16:45:26 -0800402
Amith Yamasani0b285492011-04-14 17:35:23 -0700403 final UserManager mUserManager;
404
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800405 final private DefaultContainerConnection mDefContainerConn =
406 new DefaultContainerConnection();
407 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800408 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800409 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800410 IMediaContainerService imcs =
411 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800412 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800413 }
414
415 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800416 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800417 }
418 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700419
Christopher Tate1bb69062010-02-19 17:02:12 -0800420 // Recordkeeping of restore-after-install operations that are currently in flight
421 // between the Package Manager and the Backup Manager
422 class PostInstallData {
423 public InstallArgs args;
424 public PackageInstalledInfo res;
425
426 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
427 args = _a;
428 res = _r;
429 }
430 };
431 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
432 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
433
Kenny Root05ca4c92011-09-15 10:36:25 -0700434 private final String mRequiredVerifierPackage;
435
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700436 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800437 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800438 final ArrayList<HandlerParams> mPendingInstalls =
439 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800440
441 private boolean connectToService() {
442 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
443 " DefaultContainerService");
444 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700445 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800446 if (mContext.bindService(service, mDefContainerConn,
447 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700448 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800449 mBound = true;
450 return true;
451 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700452 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800453 return false;
454 }
455
456 private void disconnectService() {
457 mContainerService = null;
458 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700459 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800460 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700461 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800462 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800463
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700464 PackageHandler(Looper looper) {
465 super(looper);
466 }
Dianne Hackborn7d608422011-08-07 16:24:18 -0700467
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700468 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700469 try {
470 doHandleMessage(msg);
471 } finally {
472 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
473 }
474 }
475
476 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700477 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800478 case INIT_COPY: {
Kenny Root5ab21572011-07-27 11:11:19 -0700479 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800480 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800481 int idx = mPendingInstalls.size();
Kenny Root5ab21572011-07-27 11:11:19 -0700482 if (DEBUG_INSTALL) Slog.i(TAG, "idx=" + idx);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800483 // If a bind was already initiated we dont really
484 // need to do anything. The pending install
485 // will be processed later on.
486 if (!mBound) {
487 // If this is the only one pending we might
488 // have to bind to the service again.
489 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800490 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800491 params.serviceError();
492 return;
493 } else {
494 // Once we bind to the service, the first
495 // pending request will be processed.
496 mPendingInstalls.add(idx, params);
497 }
498 } else {
499 mPendingInstalls.add(idx, params);
500 // Already bound to the service. Just make
501 // sure we trigger off processing the first request.
502 if (idx == 0) {
503 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800504 }
505 }
506 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800507 }
508 case MCS_BOUND: {
Kenny Root5ab21572011-07-27 11:11:19 -0700509 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800510 if (msg.obj != null) {
511 mContainerService = (IMediaContainerService) msg.obj;
512 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800513 if (mContainerService == null) {
514 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800515 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800516 for (HandlerParams params : mPendingInstalls) {
517 mPendingInstalls.remove(0);
518 // Indicate service bind error
519 params.serviceError();
520 }
521 mPendingInstalls.clear();
522 } else if (mPendingInstalls.size() > 0) {
523 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800524 if (params != null) {
Dianne Hackborn7d608422011-08-07 16:24:18 -0700525 if (params.startCopy()) {
526 // We are done... look for more work or to
527 // go idle.
528 if (DEBUG_SD_INSTALL) Log.i(TAG,
529 "Checking for more work or unbind...");
530 // Delete pending install
531 if (mPendingInstalls.size() > 0) {
532 mPendingInstalls.remove(0);
533 }
534 if (mPendingInstalls.size() == 0) {
535 if (mBound) {
536 if (DEBUG_SD_INSTALL) Log.i(TAG,
537 "Posting delayed MCS_UNBIND");
538 removeMessages(MCS_UNBIND);
539 Message ubmsg = obtainMessage(MCS_UNBIND);
540 // Unbind after a little delay, to avoid
541 // continual thrashing.
542 sendMessageDelayed(ubmsg, 10000);
543 }
544 } else {
545 // There are more pending requests in queue.
546 // Just post MCS_BOUND message to trigger processing
547 // of next pending install.
548 if (DEBUG_SD_INSTALL) Log.i(TAG,
549 "Posting MCS_BOUND for next woek");
550 mHandler.sendEmptyMessage(MCS_BOUND);
551 }
552 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800553 }
554 } else {
555 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800556 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800557 }
558 break;
559 }
Kenny Root5ab21572011-07-27 11:11:19 -0700560 case MCS_RECONNECT: {
561 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800562 if (mPendingInstalls.size() > 0) {
563 if (mBound) {
564 disconnectService();
565 }
566 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800567 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800568 for (HandlerParams params : mPendingInstalls) {
569 mPendingInstalls.remove(0);
570 // Indicate service bind error
571 params.serviceError();
572 }
573 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800574 }
575 }
576 break;
577 }
Kenny Root5ab21572011-07-27 11:11:19 -0700578 case MCS_UNBIND: {
Dianne Hackborn7d608422011-08-07 16:24:18 -0700579 // If there is no actual work left, then time to unbind.
Kenny Root5ab21572011-07-27 11:11:19 -0700580 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
581
582 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800583 if (mBound) {
Kenny Root5ab21572011-07-27 11:11:19 -0700584 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
585
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800586 disconnectService();
587 }
Kenny Root5ab21572011-07-27 11:11:19 -0700588 } else if (mPendingInstalls.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800589 // There are more pending requests in queue.
590 // Just post MCS_BOUND message to trigger processing
591 // of next pending install.
592 mHandler.sendEmptyMessage(MCS_BOUND);
593 }
Kenny Root5ab21572011-07-27 11:11:19 -0700594
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800595 break;
596 }
597 case MCS_GIVE_UP: {
Kenny Root5ab21572011-07-27 11:11:19 -0700598 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
Kenny Root60f7ad82011-03-22 12:49:06 -0700599 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800600 break;
601 }
Kenny Root5ab21572011-07-27 11:11:19 -0700602 case SEND_PENDING_BROADCAST: {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800603 String packages[];
Kenny Root60f7ad82011-03-22 12:49:06 -0700604 ArrayList<String> components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700605 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700606 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700607 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700608 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800609 if (mPendingBroadcasts == null) {
610 return;
611 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700612 size = mPendingBroadcasts.size();
613 if (size <= 0) {
614 // Nothing to be done. Just return
615 return;
616 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800617 packages = new String[size];
618 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700619 uids = new int[size];
Andy McFadden2f362292012-01-20 14:43:38 -0800620 Iterator<Map.Entry<String, ArrayList<String>>>
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800621 it = mPendingBroadcasts.entrySet().iterator();
622 int i = 0;
623 while (it.hasNext() && i < size) {
Andy McFadden2f362292012-01-20 14:43:38 -0800624 Map.Entry<String, ArrayList<String>> ent = it.next();
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800625 packages[i] = ent.getKey();
626 components[i] = ent.getValue();
627 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700628 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800629 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700630 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800631 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700632 mPendingBroadcasts.clear();
633 }
634 // Send broadcasts
635 for (int i = 0; i < size; i++) {
Kenny Root60f7ad82011-03-22 12:49:06 -0700636 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700637 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700638 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700639 break;
640 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800641 case START_CLEANING_PACKAGE: {
642 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700643 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800644 synchronized (mPackages) {
645 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
646 mSettings.mPackagesToBeCleaned.add(packageName);
647 }
648 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700649 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800650 startCleaningPackages();
651 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800652 case POST_INSTALL: {
653 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
654 PostInstallData data = mRunningInstalls.get(msg.arg1);
655 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700656 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800657
658 if (data != null) {
659 InstallArgs args = data.args;
660 PackageInstalledInfo res = data.res;
661
662 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700663 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800664 Bundle extras = new Bundle(1);
665 extras.putInt(Intent.EXTRA_UID, res.uid);
666 final boolean update = res.removedInfo.removedPackage != null;
667 if (update) {
668 extras.putBoolean(Intent.EXTRA_REPLACING, true);
669 }
670 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
671 res.pkg.applicationInfo.packageName,
Dianne Hackborne7f97212011-02-24 14:40:20 -0800672 extras, null, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800673 if (update) {
674 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
675 res.pkg.applicationInfo.packageName,
Dianne Hackborne7f97212011-02-24 14:40:20 -0800676 extras, null, null);
677 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
678 null, null,
679 res.pkg.applicationInfo.packageName, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800680 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700681 if (res.removedInfo.args != null) {
682 // Remove the replaced package's older resources safely now
683 deleteOld = true;
684 }
685 }
686 // Force a gc to clear up things
687 Runtime.getRuntime().gc();
688 // We delete after a gc for applications on sdcard.
689 if (deleteOld) {
690 synchronized (mInstallLock) {
691 res.removedInfo.args.doPostDeleteLI(true);
692 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800693 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800694 if (args.observer != null) {
695 try {
696 args.observer.packageInstalled(res.name, res.returnCode);
697 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800698 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800699 }
700 }
701 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800702 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800703 }
704 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700705 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700706 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
707 boolean reportStatus = msg.arg1 == 1;
708 boolean doGc = msg.arg2 == 1;
709 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
710 if (doGc) {
711 // Force a gc to clear up stale containers.
712 Runtime.getRuntime().gc();
713 }
714 if (msg.obj != null) {
Dianne Hackbornba24e4d2011-09-01 11:17:06 -0700715 @SuppressWarnings("unchecked")
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700716 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
717 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
718 // Unload containers
719 unloadAllContainers(args);
720 }
721 if (reportStatus) {
722 try {
723 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
724 PackageHelper.getMountService().finishMediaUpdate();
725 } catch (RemoteException e) {
726 Log.e(TAG, "MountService not running?");
727 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700728 }
729 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700730 case WRITE_SETTINGS: {
731 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
732 synchronized (mPackages) {
733 removeMessages(WRITE_SETTINGS);
Dianne Hackborne7f97212011-02-24 14:40:20 -0800734 removeMessages(WRITE_STOPPED_PACKAGES);
Kenny Root447106f2011-03-23 11:00:15 -0700735 mSettings.writeLPr();
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700736 }
737 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
738 } break;
Dianne Hackborne7f97212011-02-24 14:40:20 -0800739 case WRITE_STOPPED_PACKAGES: {
740 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
741 synchronized (mPackages) {
742 removeMessages(WRITE_STOPPED_PACKAGES);
Kenny Root447106f2011-03-23 11:00:15 -0700743 mSettings.writeStoppedLPr();
Dianne Hackborne7f97212011-02-24 14:40:20 -0800744 }
745 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
746 } break;
Kenny Root5ab21572011-07-27 11:11:19 -0700747 case CHECK_PENDING_VERIFICATION: {
748 final int verificationId = msg.arg1;
Kenny Root05ca4c92011-09-15 10:36:25 -0700749 final PackageVerificationState state = mPendingVerification.get(verificationId);
Kenny Root5ab21572011-07-27 11:11:19 -0700750
Kenny Root05ca4c92011-09-15 10:36:25 -0700751 if (state != null) {
752 final InstallArgs args = state.getInstallArgs();
Kenny Roota503a0f2011-10-03 14:45:28 -0700753 Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
Kenny Root5ab21572011-07-27 11:11:19 -0700754 mPendingVerification.remove(verificationId);
755
756 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_TIMEOUT;
757 processPendingInstall(args, ret);
758
759 mHandler.sendEmptyMessage(MCS_UNBIND);
760 }
761
762 break;
763 }
764 case PACKAGE_VERIFIED: {
765 final int verificationId = msg.arg1;
Kenny Root5ab21572011-07-27 11:11:19 -0700766
Kenny Root05ca4c92011-09-15 10:36:25 -0700767 final PackageVerificationState state = mPendingVerification.get(verificationId);
768 if (state == null) {
Kenny Roota503a0f2011-10-03 14:45:28 -0700769 Slog.w(TAG, "Invalid verification token " + verificationId + " received");
Kenny Root5ab21572011-07-27 11:11:19 -0700770 break;
771 }
772
Kenny Root05ca4c92011-09-15 10:36:25 -0700773 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
Kenny Root5ab21572011-07-27 11:11:19 -0700774
Kenny Root05ca4c92011-09-15 10:36:25 -0700775 state.setVerifierResponse(response.callerUid, response.code);
776
777 if (state.isVerificationComplete()) {
778 mPendingVerification.remove(verificationId);
779
780 final InstallArgs args = state.getInstallArgs();
781
782 int ret;
783 if (state.isInstallAllowed()) {
784 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
785 try {
786 ret = args.copyApk(mContainerService, true);
787 } catch (RemoteException e) {
788 Slog.e(TAG, "Could not contact the ContainerService");
789 }
790 } else {
791 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
Kenny Root5ab21572011-07-27 11:11:19 -0700792 }
Kenny Root05ca4c92011-09-15 10:36:25 -0700793
794 processPendingInstall(args, ret);
795
796 mHandler.sendEmptyMessage(MCS_UNBIND);
Kenny Root5ab21572011-07-27 11:11:19 -0700797 }
798
Kenny Root5ab21572011-07-27 11:11:19 -0700799 break;
800 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700801 }
802 }
803 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800804
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700805 void scheduleWriteSettingsLocked() {
806 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
807 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
808 }
809 }
810
Dianne Hackborne7f97212011-02-24 14:40:20 -0800811 void scheduleWriteStoppedPackagesLocked() {
812 if (!mHandler.hasMessages(WRITE_STOPPED_PACKAGES)) {
813 mHandler.sendEmptyMessageDelayed(WRITE_STOPPED_PACKAGES, WRITE_SETTINGS_DELAY);
814 }
815 }
816
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800817 static boolean installOnSd(int flags) {
818 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700819 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800820 return false;
821 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700822 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
823 return true;
824 }
825 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800826 }
827
Dianne Hackbornd2509fd2011-09-12 12:29:43 -0700828 public static final IPackageManager main(Context context, boolean factoryTest,
829 boolean onlyCore) {
830 PackageManagerService m = new PackageManagerService(context, factoryTest, onlyCore);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 ServiceManager.addService("package", m);
832 return m;
833 }
834
835 static String[] splitString(String str, char sep) {
836 int count = 1;
837 int i = 0;
838 while ((i=str.indexOf(sep, i)) >= 0) {
839 count++;
840 i++;
841 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 String[] res = new String[count];
844 i=0;
845 count = 0;
846 int lastI=0;
847 while ((i=str.indexOf(sep, i)) >= 0) {
848 res[count] = str.substring(lastI, i);
849 count++;
850 i++;
851 lastI = i;
852 }
853 res[count] = str.substring(lastI, str.length());
854 return res;
855 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800856
Dianne Hackbornd2509fd2011-09-12 12:29:43 -0700857 public PackageManagerService(Context context, boolean factoryTest, boolean onlyCore) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800858 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800862 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 mContext = context;
866 mFactoryTest = factoryTest;
Dianne Hackbornd2509fd2011-09-12 12:29:43 -0700867 mOnlyCore = onlyCore;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700868 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 mMetrics = new DisplayMetrics();
870 mSettings = new Settings();
Kenny Root447106f2011-03-23 11:00:15 -0700871 mSettings.addSharedUserLPw("android.uid.system",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800873 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, ApplicationInfo.FLAG_SYSTEM);
874 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, ApplicationInfo.FLAG_SYSTEM);
875 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876
877 String separateProcesses = SystemProperties.get("debug.separate_processes");
878 if (separateProcesses != null && separateProcesses.length() > 0) {
879 if ("*".equals(separateProcesses)) {
880 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
881 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800882 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 } else {
884 mDefParseFlags = 0;
885 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800886 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 + separateProcesses);
888 }
889 } else {
890 mDefParseFlags = 0;
891 mSeparateProcesses = null;
892 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800893
Jeff Brown5d6d90f2011-07-11 13:04:53 -0700894 mInstaller = new Installer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895
896 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
897 Display d = wm.getDefaultDisplay();
898 d.getMetrics(mMetrics);
899
900 synchronized (mInstallLock) {
Kenny Root447106f2011-03-23 11:00:15 -0700901 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 synchronized (mPackages) {
903 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700904 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 File dataDir = Environment.getDataDirectory();
907 mAppDataDir = new File(dataDir, "data");
Amith Yamasani0b285492011-04-14 17:35:23 -0700908 mUserAppDataDir = new File(dataDir, "user");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
910
Amith Yamasani0b285492011-04-14 17:35:23 -0700911 mUserManager = new UserManager(mInstaller, mUserAppDataDir);
912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 readPermissions();
914
Kenny Root447106f2011-03-23 11:00:15 -0700915 mRestoredSettings = mSettings.readLPw();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800917
918 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800920
Suchi Amalapurapudaec1722010-01-14 21:25:16 -0800921 // Set flag to monitor and not change apk file paths when
922 // scanning install directories.
Dianne Hackborn661cd522011-08-22 00:26:20 -0700923 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700924 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800925 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800926 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700927 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700932 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800933
Jeff Brown5d6d90f2011-07-11 13:04:53 -0700934 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800935
Jeff Brown5d6d90f2011-07-11 13:04:53 -0700936 /**
937 * Out of paranoia, ensure that everything in the boot class
938 * path has been dexed.
939 */
940 String bootClassPath = System.getProperty("java.boot.class.path");
941 if (bootClassPath != null) {
942 String[] paths = splitString(bootClassPath, ':');
943 for (int i=0; i<paths.length; i++) {
944 try {
945 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
946 libFiles.add(paths[i]);
947 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
948 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -0700950 } catch (FileNotFoundException e) {
951 Slog.w(TAG, "Boot class path not found: " + paths[i]);
952 } catch (IOException e) {
Kenny Rootfec5e752011-09-23 10:09:58 -0700953 Slog.w(TAG, "Cannot dexopt " + paths[i] + "; is it an APK or JAR? "
954 + e.getMessage());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 }
956 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -0700957 } else {
958 Slog.w(TAG, "No BOOTCLASSPATH found!");
959 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800960
Jeff Brown5d6d90f2011-07-11 13:04:53 -0700961 /**
962 * Also ensure all external libraries have had dexopt run on them.
963 */
964 if (mSharedLibraries.size() > 0) {
965 Iterator<String> libs = mSharedLibraries.values().iterator();
966 while (libs.hasNext()) {
967 String lib = libs.next();
968 try {
969 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
970 libFiles.add(lib);
971 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
972 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -0700974 } catch (FileNotFoundException e) {
975 Slog.w(TAG, "Library not found: " + lib);
976 } catch (IOException e) {
Kenny Rootfec5e752011-09-23 10:09:58 -0700977 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
978 + e.getMessage());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 }
980 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -0700981 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800982
Jeff Brown5d6d90f2011-07-11 13:04:53 -0700983 // Gross hack for now: we know this file doesn't contain any
984 // code, so don't dexopt it to avoid the resulting log spew.
985 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
986
987 /**
988 * And there are a number of commands implemented in Java, which
989 * we currently need to do the dexopt on so that they can be
990 * run from a non-root shell.
991 */
992 String[] frameworkFiles = mFrameworkDir.list();
993 if (frameworkFiles != null) {
994 for (int i=0; i<frameworkFiles.length; i++) {
995 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
996 String path = libPath.getPath();
997 // Skip the file if we alrady did it.
998 if (libFiles.contains(path)) {
999 continue;
1000 }
1001 // Skip the file if it is not a type we want to dexopt.
1002 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1003 continue;
1004 }
1005 try {
1006 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
1007 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
1008 didDexOpt = true;
1009 }
1010 } catch (FileNotFoundException e) {
1011 Slog.w(TAG, "Jar not found: " + path);
1012 } catch (IOException e) {
1013 Slog.w(TAG, "Exception reading jar: " + path, e);
1014 }
1015 }
1016 }
1017
1018 if (didDexOpt) {
1019 // If we had to do a dexopt of one of the previous
1020 // things, then something on the system has changed.
1021 // Consider this significant, and wipe away all other
1022 // existing dexopt files to ensure we don't leave any
1023 // dangling around.
1024 String[] files = mDalvikCacheDir.list();
1025 if (files != null) {
1026 for (int i=0; i<files.length; i++) {
1027 String fn = files[i];
1028 if (fn.startsWith("data@app@")
1029 || fn.startsWith("data@app-private@")) {
1030 Slog.i(TAG, "Pruning dalvik file: " + fn);
1031 (new File(mDalvikCacheDir, fn)).delete();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001032 }
1033 }
1034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001036
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001037 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 mFrameworkInstallObserver = new AppDirObserver(
1039 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
1040 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -07001041 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
1042 | PackageParser.PARSE_IS_SYSTEM_DIR,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001043 scanMode | SCAN_NO_DEX, 0);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001044
1045 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
1047 mSystemInstallObserver = new AppDirObserver(
1048 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
1049 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -07001050 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001051 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001052
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07001053 // Collect all vendor packages.
1054 mVendorAppDir = new File("/vendor/app");
1055 mVendorInstallObserver = new AppDirObserver(
1056 mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
1057 mVendorInstallObserver.startWatching();
1058 scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001059 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07001060
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001061 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1062 mInstaller.moveFiles();
1063
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001064 // Prune any system packages that no longer exist.
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001065 if (!mOnlyCore) {
1066 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1067 while (psit.hasNext()) {
1068 PackageSetting ps = psit.next();
1069 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
1070 && !mPackages.containsKey(ps.name)
1071 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
1072 psit.remove();
1073 String msg = "System package " + ps.name
1074 + " no longer exists; wiping its data";
1075 reportSettingsProblem(Log.WARN, msg);
1076 mInstaller.remove(ps.name, 0);
1077 mUserManager.removePackageForAllUsers(ps.name);
1078 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08001079 }
1080 }
1081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 mAppInstallDir = new File(dataDir, "app");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 //look for any incomplete package installations
Kenny Root447106f2011-03-23 11:00:15 -07001084 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 //clean up list
1086 for(int i = 0; i < deletePkgsList.size(); i++) {
1087 //clean up here
1088 cleanupInstallFailedPackage(deletePkgsList.get(i));
1089 }
1090 //delete tmp files
1091 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001092
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07001093 if (!mOnlyCore) {
1094 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1095 SystemClock.uptimeMillis());
1096 mAppInstallObserver = new AppDirObserver(
1097 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
1098 mAppInstallObserver.startWatching();
1099 scanDirLI(mAppInstallDir, 0, scanMode, 0);
1100
1101 mDrmAppInstallObserver = new AppDirObserver(
1102 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
1103 mDrmAppInstallObserver.startWatching();
1104 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1105 scanMode, 0);
1106 } else {
1107 mAppInstallObserver = null;
1108 mDrmAppInstallObserver = null;
1109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001111 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001113 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 + ((SystemClock.uptimeMillis()-startTime)/1000f)
1115 + " seconds");
1116
Dianne Hackbornf22221f2010-04-05 18:35:42 -07001117 // If the platform SDK has changed since the last time we booted,
1118 // we need to re-grant app permission to catch any new ones that
1119 // appear. This is really a hack, and means that apps can in some
1120 // cases get permissions that the user didn't initially explicitly
1121 // allow... it would be nice to have some better way to handle
1122 // this situation.
1123 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1124 != mSdkVersion;
1125 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1126 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1127 + "; regranting permissions for internal storage");
1128 mSettings.mInternalSdkPlatform = mSdkVersion;
1129
Dianne Hackborne639da72012-02-21 15:11:13 -08001130 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1131 | (regrantPermissions
1132 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1133 : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134
Dianne Hackborn04505102012-02-29 12:34:04 -08001135 // Verify that all of the preferred activity components actually
1136 // exist. It is possible for applications to be updated and at
1137 // that point remove a previously declared activity component that
1138 // had been set as a preferred activity. We try to clean this up
1139 // the next time we encounter that preferred activity, but it is
1140 // possible for the user flow to never be able to return to that
1141 // situation so here we do a sanity check to make sure we haven't
1142 // left any junk around.
1143 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
1144 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
1145 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
1146 removed.add(pa);
1147 }
1148 }
1149 for (int i=0; i<removed.size(); i++) {
1150 PreferredActivity pa = removed.get(i);
1151 Slog.w(TAG, "Removing dangling preferred activity: "
1152 + pa.mPref.mComponent);
1153 mSettings.mPreferredActivities.removeFilter(pa);
1154 }
1155
Kenny Root447106f2011-03-23 11:00:15 -07001156 // can downgrade to reader
1157 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001159 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 // Now after opening every single application zip, make sure they
1163 // are all flushed. Not really needed, but keeps things nice and
1164 // tidy.
1165 Runtime.getRuntime().gc();
Kenny Root05ca4c92011-09-15 10:36:25 -07001166
1167 mRequiredVerifierPackage = getRequiredVerifierLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 } // synchronized (mPackages)
1169 } // synchronized (mInstallLock)
1170 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001171
Dianne Hackborn58f42a52011-10-10 13:46:34 -07001172 public boolean isFirstBoot() {
1173 return !mRestoredSettings;
1174 }
1175
Kenny Root05ca4c92011-09-15 10:36:25 -07001176 private String getRequiredVerifierLPr() {
1177 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1178 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1179 PackageManager.GET_DISABLED_COMPONENTS);
1180
1181 String requiredVerifier = null;
1182
1183 final int N = receivers.size();
1184 for (int i = 0; i < N; i++) {
1185 final ResolveInfo info = receivers.get(i);
1186
1187 if (info.activityInfo == null) {
1188 continue;
1189 }
1190
1191 final String packageName = info.activityInfo.packageName;
1192
1193 final PackageSetting ps = mSettings.mPackages.get(packageName);
1194 if (ps == null) {
1195 continue;
1196 }
1197
1198 if (!ps.grantedPermissions
1199 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1200 continue;
1201 }
1202
1203 if (requiredVerifier != null) {
1204 throw new RuntimeException("There can be only one required verifier");
1205 }
1206
1207 requiredVerifier = packageName;
1208 }
1209
1210 return requiredVerifier;
1211 }
1212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 @Override
1214 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1215 throws RemoteException {
1216 try {
1217 return super.onTransact(code, data, reply, flags);
1218 } catch (RuntimeException e) {
1219 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001220 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 }
1222 throw e;
1223 }
1224 }
1225
Dianne Hackborne6620b22010-01-22 14:46:21 -08001226 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001227 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001228 int retCode = mInstaller.remove(ps.name, 0);
1229 if (retCode < 0) {
1230 Slog.w(TAG, "Couldn't remove app data directory for package: "
1231 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 } else {
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001233 mUserManager.removePackageForAllUsers(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001235 if (ps.codePath != null) {
1236 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001237 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001238 }
1239 }
1240 if (ps.resourcePath != null) {
1241 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001242 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001243 }
1244 }
Kenny Root447106f2011-03-23 11:00:15 -07001245 mSettings.removePackageLPw(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 }
1247
1248 void readPermissions() {
1249 // Read permissions from .../etc/permission directory.
1250 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1251 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001252 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 return;
1254 }
1255 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001256 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 return;
1258 }
1259
1260 // Iterate over the files in the directory and scan .xml files
1261 for (File f : libraryDir.listFiles()) {
1262 // We'll read platform.xml last
1263 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1264 continue;
1265 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001268 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 continue;
1270 }
1271 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001272 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 continue;
1274 }
1275
1276 readPermissionsFromXml(f);
1277 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1280 final File permFile = new File(Environment.getRootDirectory(),
1281 "etc/permissions/platform.xml");
1282 readPermissionsFromXml(permFile);
1283 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001284
1285 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 FileReader permReader = null;
1287 try {
1288 permReader = new FileReader(permFile);
1289 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001290 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 return;
1292 }
1293
1294 try {
1295 XmlPullParser parser = Xml.newPullParser();
1296 parser.setInput(permReader);
1297
1298 XmlUtils.beginDocument(parser, "permissions");
1299
1300 while (true) {
1301 XmlUtils.nextElement(parser);
1302 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1303 break;
1304 }
1305
1306 String name = parser.getName();
1307 if ("group".equals(name)) {
1308 String gidStr = parser.getAttributeValue(null, "gid");
1309 if (gidStr != null) {
1310 int gid = Integer.parseInt(gidStr);
1311 mGlobalGids = appendInt(mGlobalGids, gid);
1312 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001313 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 + parser.getPositionDescription());
1315 }
1316
1317 XmlUtils.skipCurrentTag(parser);
1318 continue;
1319 } else if ("permission".equals(name)) {
1320 String perm = parser.getAttributeValue(null, "name");
1321 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001322 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 + parser.getPositionDescription());
1324 XmlUtils.skipCurrentTag(parser);
1325 continue;
1326 }
1327 perm = perm.intern();
1328 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 } else if ("assign-permission".equals(name)) {
1331 String perm = parser.getAttributeValue(null, "name");
1332 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001333 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 + parser.getPositionDescription());
1335 XmlUtils.skipCurrentTag(parser);
1336 continue;
1337 }
1338 String uidStr = parser.getAttributeValue(null, "uid");
1339 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001340 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 + parser.getPositionDescription());
1342 XmlUtils.skipCurrentTag(parser);
1343 continue;
1344 }
1345 int uid = Process.getUidForName(uidStr);
1346 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001347 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 + uidStr + "\" at "
1349 + parser.getPositionDescription());
1350 XmlUtils.skipCurrentTag(parser);
1351 continue;
1352 }
1353 perm = perm.intern();
1354 HashSet<String> perms = mSystemPermissions.get(uid);
1355 if (perms == null) {
1356 perms = new HashSet<String>();
1357 mSystemPermissions.put(uid, perms);
1358 }
1359 perms.add(perm);
1360 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 } else if ("library".equals(name)) {
1363 String lname = parser.getAttributeValue(null, "name");
1364 String lfile = parser.getAttributeValue(null, "file");
1365 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001366 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 + parser.getPositionDescription());
1368 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001369 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 + parser.getPositionDescription());
1371 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001372 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001373 mSharedLibraries.put(lname, lfile);
1374 }
1375 XmlUtils.skipCurrentTag(parser);
1376 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001377
Dianne Hackborn49237342009-08-27 20:08:01 -07001378 } else if ("feature".equals(name)) {
1379 String fname = parser.getAttributeValue(null, "name");
1380 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001381 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001382 + parser.getPositionDescription());
1383 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001384 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001385 FeatureInfo fi = new FeatureInfo();
1386 fi.name = fname;
1387 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 }
1389 XmlUtils.skipCurrentTag(parser);
1390 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 } else {
1393 XmlUtils.skipCurrentTag(parser);
1394 continue;
1395 }
1396
1397 }
Brian Carlstromfd9ddd12010-11-04 11:24:58 -07001398 permReader.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001400 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001402 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 }
1404 }
1405
1406 void readPermission(XmlPullParser parser, String name)
1407 throws IOException, XmlPullParserException {
1408
1409 name = name.intern();
1410
1411 BasePermission bp = mSettings.mPermissions.get(name);
1412 if (bp == null) {
1413 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1414 mSettings.mPermissions.put(name, bp);
1415 }
1416 int outerDepth = parser.getDepth();
1417 int type;
1418 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1419 && (type != XmlPullParser.END_TAG
1420 || parser.getDepth() > outerDepth)) {
1421 if (type == XmlPullParser.END_TAG
1422 || type == XmlPullParser.TEXT) {
1423 continue;
1424 }
1425
1426 String tagName = parser.getName();
1427 if ("group".equals(tagName)) {
1428 String gidStr = parser.getAttributeValue(null, "gid");
1429 if (gidStr != null) {
1430 int gid = Process.getGidForName(gidStr);
1431 bp.gids = appendInt(bp.gids, gid);
1432 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001433 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 + parser.getPositionDescription());
1435 }
1436 }
1437 XmlUtils.skipCurrentTag(parser);
1438 }
1439 }
1440
1441 static int[] appendInt(int[] cur, int val) {
1442 if (cur == null) {
1443 return new int[] { val };
1444 }
1445 final int N = cur.length;
1446 for (int i=0; i<N; i++) {
1447 if (cur[i] == val) {
1448 return cur;
1449 }
1450 }
1451 int[] ret = new int[N+1];
1452 System.arraycopy(cur, 0, ret, 0, N);
1453 ret[N] = val;
1454 return ret;
1455 }
1456
1457 static int[] appendInts(int[] cur, int[] add) {
1458 if (add == null) return cur;
1459 if (cur == null) return add;
1460 final int N = add.length;
1461 for (int i=0; i<N; i++) {
1462 cur = appendInt(cur, add[i]);
1463 }
1464 return cur;
1465 }
1466
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001467 static int[] removeInt(int[] cur, int val) {
1468 if (cur == null) {
1469 return null;
1470 }
1471 final int N = cur.length;
1472 for (int i=0; i<N; i++) {
1473 if (cur[i] == val) {
1474 int[] ret = new int[N-1];
1475 if (i > 0) {
1476 System.arraycopy(cur, 0, ret, 0, i);
1477 }
1478 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001479 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001480 }
1481 return ret;
1482 }
1483 }
1484 return cur;
1485 }
1486
1487 static int[] removeInts(int[] cur, int[] rem) {
1488 if (rem == null) return cur;
1489 if (cur == null) return cur;
1490 final int N = rem.length;
1491 for (int i=0; i<N; i++) {
1492 cur = removeInt(cur, rem[i]);
1493 }
1494 return cur;
1495 }
1496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001498 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1499 // The package has been uninstalled but has retained data and resources.
Dianne Hackborne639da72012-02-21 15:11:13 -08001500 return PackageParser.generatePackageInfo(p, null, flags, 0, 0, null);
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 final PackageSetting ps = (PackageSetting)p.mExtras;
1503 if (ps == null) {
1504 return null;
1505 }
1506 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001507 return PackageParser.generatePackageInfo(p, gp.gids, flags,
Dianne Hackborne639da72012-02-21 15:11:13 -08001508 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 }
1510
1511 public PackageInfo getPackageInfo(String packageName, int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001512 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 synchronized (mPackages) {
1514 PackageParser.Package p = mPackages.get(packageName);
Kenny Root9718cf52011-02-23 16:45:26 -08001515 if (DEBUG_PACKAGE_INFO)
1516 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 if (p != null) {
1518 return generatePackageInfo(p, flags);
1519 }
1520 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
Kenny Root447106f2011-03-23 11:00:15 -07001521 return generatePackageInfoFromSettingsLPw(packageName, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 }
1523 }
1524 return null;
1525 }
1526
Dianne Hackborn47096932010-02-11 15:57:09 -08001527 public String[] currentToCanonicalPackageNames(String[] names) {
1528 String[] out = new String[names.length];
Kenny Root447106f2011-03-23 11:00:15 -07001529 // reader
Dianne Hackborn47096932010-02-11 15:57:09 -08001530 synchronized (mPackages) {
1531 for (int i=names.length-1; i>=0; i--) {
1532 PackageSetting ps = mSettings.mPackages.get(names[i]);
1533 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1534 }
1535 }
1536 return out;
1537 }
1538
1539 public String[] canonicalToCurrentPackageNames(String[] names) {
1540 String[] out = new String[names.length];
Kenny Root447106f2011-03-23 11:00:15 -07001541 // reader
Dianne Hackborn47096932010-02-11 15:57:09 -08001542 synchronized (mPackages) {
1543 for (int i=names.length-1; i>=0; i--) {
1544 String cur = mSettings.mRenamedPackages.get(names[i]);
1545 out[i] = cur != null ? cur : names[i];
1546 }
1547 }
1548 return out;
1549 }
1550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 public int getPackageUid(String packageName) {
Kenny Root447106f2011-03-23 11:00:15 -07001552 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 synchronized (mPackages) {
1554 PackageParser.Package p = mPackages.get(packageName);
1555 if(p != null) {
1556 return p.applicationInfo.uid;
1557 }
1558 PackageSetting ps = mSettings.mPackages.get(packageName);
1559 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1560 return -1;
1561 }
1562 p = ps.pkg;
1563 return p != null ? p.applicationInfo.uid : -1;
1564 }
1565 }
1566
1567 public int[] getPackageGids(String packageName) {
Kenny Root447106f2011-03-23 11:00:15 -07001568 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 synchronized (mPackages) {
1570 PackageParser.Package p = mPackages.get(packageName);
Kenny Root9718cf52011-02-23 16:45:26 -08001571 if (DEBUG_PACKAGE_INFO)
1572 Log.v(TAG, "getPackageGids" + packageName + ": " + p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 if (p != null) {
1574 final PackageSetting ps = (PackageSetting)p.mExtras;
1575 final SharedUserSetting suid = ps.sharedUser;
1576 return suid != null ? suid.gids : ps.gids;
1577 }
1578 }
1579 // stupid thing to indicate an error.
1580 return new int[0];
1581 }
1582
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001583 static final PermissionInfo generatePermissionInfo(
1584 BasePermission bp, int flags) {
1585 if (bp.perm != null) {
1586 return PackageParser.generatePermissionInfo(bp.perm, flags);
1587 }
1588 PermissionInfo pi = new PermissionInfo();
1589 pi.name = bp.name;
1590 pi.packageName = bp.sourcePackage;
1591 pi.nonLocalizedLabel = bp.name;
1592 pi.protectionLevel = bp.protectionLevel;
1593 return pi;
1594 }
1595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 public PermissionInfo getPermissionInfo(String name, int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001597 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 synchronized (mPackages) {
1599 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001600 if (p != null) {
1601 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 }
1603 return null;
1604 }
1605 }
1606
1607 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001608 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 synchronized (mPackages) {
1610 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1611 for (BasePermission p : mSettings.mPermissions.values()) {
1612 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001613 if (p.perm == null || p.perm.info.group == null) {
1614 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 }
1616 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001617 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1619 }
1620 }
1621 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 if (out.size() > 0) {
1624 return out;
1625 }
1626 return mPermissionGroups.containsKey(group) ? out : null;
1627 }
1628 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001631 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 synchronized (mPackages) {
1633 return PackageParser.generatePermissionGroupInfo(
1634 mPermissionGroups.get(name), flags);
1635 }
1636 }
1637
1638 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001639 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 synchronized (mPackages) {
1641 final int N = mPermissionGroups.size();
1642 ArrayList<PermissionGroupInfo> out
1643 = new ArrayList<PermissionGroupInfo>(N);
1644 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1645 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1646 }
1647 return out;
1648 }
1649 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001650
Kenny Root447106f2011-03-23 11:00:15 -07001651 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 PackageSetting ps = mSettings.mPackages.get(packageName);
Kenny Root447106f2011-03-23 11:00:15 -07001653 if (ps != null) {
1654 if (ps.pkg == null) {
1655 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, flags);
1656 if (pInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 return pInfo.applicationInfo;
1658 }
1659 return null;
1660 }
1661 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1662 }
1663 return null;
1664 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001665
Kenny Root447106f2011-03-23 11:00:15 -07001666 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 PackageSetting ps = mSettings.mPackages.get(packageName);
Kenny Root447106f2011-03-23 11:00:15 -07001668 if (ps != null) {
1669 if (ps.pkg == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 ps.pkg = new PackageParser.Package(packageName);
1671 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001672 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1673 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1674 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
Amith Yamasani0b285492011-04-14 17:35:23 -07001675 ps.pkg.applicationInfo.dataDir =
1676 getDataPathForPackage(ps.pkg.packageName, 0).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001677 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001678 ps.pkg.mSetEnabled = ps.enabled;
Dianne Hackborne7f97212011-02-24 14:40:20 -08001679 ps.pkg.mSetStopped = ps.stopped;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 }
1681 return generatePackageInfo(ps.pkg, flags);
1682 }
1683 return null;
1684 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07001687 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 synchronized (mPackages) {
1689 PackageParser.Package p = mPackages.get(packageName);
Kenny Root9718cf52011-02-23 16:45:26 -08001690 if (DEBUG_PACKAGE_INFO) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 TAG, "getApplicationInfo " + packageName
1692 + ": " + p);
1693 if (p != null) {
1694 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001695 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 }
1697 if ("android".equals(packageName)||"system".equals(packageName)) {
1698 return mAndroidApplication;
1699 }
1700 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
Kenny Root447106f2011-03-23 11:00:15 -07001701 return generateApplicationInfoFromSettingsLPw(packageName, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 }
1703 }
1704 return null;
1705 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001706
1707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1709 mContext.enforceCallingOrSelfPermission(
1710 android.Manifest.permission.CLEAR_APP_CACHE, null);
1711 // Queue up an async operation since clearing cache may take a little while.
1712 mHandler.post(new Runnable() {
1713 public void run() {
1714 mHandler.removeCallbacks(this);
1715 int retCode = -1;
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001716 retCode = mInstaller.freeCache(freeStorageSize);
1717 if (retCode < 0) {
1718 Slog.w(TAG, "Couldn't clear application caches");
1719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 if (observer != null) {
1721 try {
1722 observer.onRemoveCompleted(null, (retCode >= 0));
1723 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001724 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 }
1726 }
1727 }
1728 });
1729 }
1730
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001731 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001732 mContext.enforceCallingOrSelfPermission(
1733 android.Manifest.permission.CLEAR_APP_CACHE, null);
1734 // Queue up an async operation since clearing cache may take a little while.
1735 mHandler.post(new Runnable() {
1736 public void run() {
1737 mHandler.removeCallbacks(this);
1738 int retCode = -1;
Jeff Brown5d6d90f2011-07-11 13:04:53 -07001739 retCode = mInstaller.freeCache(freeStorageSize);
1740 if (retCode < 0) {
1741 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001742 }
1743 if(pi != null) {
1744 try {
1745 // Callback via pending intent
1746 int code = (retCode >= 0) ? 1 : 0;
1747 pi.sendIntent(null, code, null,
1748 null, null);
1749 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001750 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001751 }
1752 }
1753 }
1754 });
1755 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001758 return getActivityInfo(component, flags, Binder.getOrigCallingUser());
1759 }
1760
1761 ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 synchronized (mPackages) {
1763 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001764
Kenny Root9718cf52011-02-23 16:45:26 -08001765 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
Kenny Root447106f2011-03-23 11:00:15 -07001766 if (a != null && mSettings.isEnabledLPr(a.info, flags)) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001767 return PackageParser.generateActivityInfo(a, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 }
1769 if (mResolveComponentName.equals(component)) {
1770 return mResolveActivity;
1771 }
1772 }
1773 return null;
1774 }
1775
1776 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001777 return getReceiverInfo(component, flags, Binder.getOrigCallingUser());
1778 }
1779
1780 ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 synchronized (mPackages) {
1782 PackageParser.Activity a = mReceivers.mActivities.get(component);
Kenny Root9718cf52011-02-23 16:45:26 -08001783 if (DEBUG_PACKAGE_INFO) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 TAG, "getReceiverInfo " + component + ": " + a);
Kenny Root447106f2011-03-23 11:00:15 -07001785 if (a != null && mSettings.isEnabledLPr(a.info, flags)) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001786 return PackageParser.generateActivityInfo(a, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 }
1788 }
1789 return null;
1790 }
1791
1792 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001793 return getServiceInfo(component, flags, Binder.getOrigCallingUser());
1794 }
1795
1796 ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 synchronized (mPackages) {
1798 PackageParser.Service s = mServices.mServices.get(component);
Kenny Root9718cf52011-02-23 16:45:26 -08001799 if (DEBUG_PACKAGE_INFO) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 TAG, "getServiceInfo " + component + ": " + s);
Kenny Root447106f2011-03-23 11:00:15 -07001801 if (s != null && mSettings.isEnabledLPr(s.info, flags)) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001802 return PackageParser.generateServiceInfo(s, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 }
1804 }
1805 return null;
1806 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001807
Dianne Hackborn361199b2010-08-30 17:42:07 -07001808 public ProviderInfo getProviderInfo(ComponentName component, int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001809 return getProviderInfo(component, flags, UserId.getUserId(Binder.getCallingUid()));
1810 }
1811
1812 ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
Dianne Hackborn361199b2010-08-30 17:42:07 -07001813 synchronized (mPackages) {
1814 PackageParser.Provider p = mProvidersByComponent.get(component);
Kenny Root9718cf52011-02-23 16:45:26 -08001815 if (DEBUG_PACKAGE_INFO) Log.v(
Dianne Hackborn361199b2010-08-30 17:42:07 -07001816 TAG, "getProviderInfo " + component + ": " + p);
Kenny Root447106f2011-03-23 11:00:15 -07001817 if (p != null && mSettings.isEnabledLPr(p.info, flags)) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001818 return PackageParser.generateProviderInfo(p, flags, userId);
Dianne Hackborn361199b2010-08-30 17:42:07 -07001819 }
1820 }
1821 return null;
1822 }
1823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 public String[] getSystemSharedLibraryNames() {
1825 Set<String> libSet;
1826 synchronized (mPackages) {
1827 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001828 int size = libSet.size();
1829 if (size > 0) {
1830 String[] libs = new String[size];
1831 libSet.toArray(libs);
1832 return libs;
1833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001835 return null;
1836 }
1837
1838 public FeatureInfo[] getSystemAvailableFeatures() {
1839 Collection<FeatureInfo> featSet;
1840 synchronized (mPackages) {
1841 featSet = mAvailableFeatures.values();
1842 int size = featSet.size();
1843 if (size > 0) {
1844 FeatureInfo[] features = new FeatureInfo[size+1];
1845 featSet.toArray(features);
1846 FeatureInfo fi = new FeatureInfo();
1847 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1848 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1849 features[size] = fi;
1850 return features;
1851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 }
1853 return null;
1854 }
1855
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001856 public boolean hasSystemFeature(String name) {
1857 synchronized (mPackages) {
1858 return mAvailableFeatures.containsKey(name);
1859 }
1860 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 public int checkPermission(String permName, String pkgName) {
1863 synchronized (mPackages) {
1864 PackageParser.Package p = mPackages.get(pkgName);
1865 if (p != null && p.mExtras != null) {
1866 PackageSetting ps = (PackageSetting)p.mExtras;
1867 if (ps.sharedUser != null) {
1868 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1869 return PackageManager.PERMISSION_GRANTED;
1870 }
1871 } else if (ps.grantedPermissions.contains(permName)) {
1872 return PackageManager.PERMISSION_GRANTED;
1873 }
1874 }
1875 }
1876 return PackageManager.PERMISSION_DENIED;
1877 }
1878
1879 public int checkUidPermission(String permName, int uid) {
1880 synchronized (mPackages) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001881 Object obj = mSettings.getUserIdLPr(UserId.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001883 GrantedPermissions gp = (GrantedPermissions)obj;
1884 if (gp.grantedPermissions.contains(permName)) {
1885 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 }
1887 } else {
1888 HashSet<String> perms = mSystemPermissions.get(uid);
1889 if (perms != null && perms.contains(permName)) {
1890 return PackageManager.PERMISSION_GRANTED;
1891 }
1892 }
1893 }
1894 return PackageManager.PERMISSION_DENIED;
1895 }
1896
1897 private BasePermission findPermissionTreeLP(String permName) {
1898 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1899 if (permName.startsWith(bp.name) &&
1900 permName.length() > bp.name.length() &&
1901 permName.charAt(bp.name.length()) == '.') {
1902 return bp;
1903 }
1904 }
1905 return null;
1906 }
1907
1908 private BasePermission checkPermissionTreeLP(String permName) {
1909 if (permName != null) {
1910 BasePermission bp = findPermissionTreeLP(permName);
1911 if (bp != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001912 if (bp.uid == UserId.getAppId(Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 return bp;
1914 }
1915 throw new SecurityException("Calling uid "
1916 + Binder.getCallingUid()
1917 + " is not allowed to add to permission tree "
1918 + bp.name + " owned by uid " + bp.uid);
1919 }
1920 }
1921 throw new SecurityException("No permission tree found for " + permName);
1922 }
1923
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001924 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1925 if (s1 == null) {
1926 return s2 == null;
1927 }
1928 if (s2 == null) {
1929 return false;
1930 }
1931 if (s1.getClass() != s2.getClass()) {
1932 return false;
1933 }
1934 return s1.equals(s2);
1935 }
1936
1937 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1938 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001939 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001940 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1941 if (!compareStrings(pi1.name, pi2.name)) return false;
1942 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1943 // We'll take care of setting this one.
1944 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1945 // These are not currently stored in settings.
1946 //if (!compareStrings(pi1.group, pi2.group)) return false;
1947 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1948 //if (pi1.labelRes != pi2.labelRes) return false;
1949 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1950 return true;
1951 }
1952
1953 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1954 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1955 throw new SecurityException("Label must be specified in permission");
1956 }
1957 BasePermission tree = checkPermissionTreeLP(info.name);
1958 BasePermission bp = mSettings.mPermissions.get(info.name);
1959 boolean added = bp == null;
1960 boolean changed = true;
Dianne Hackborne639da72012-02-21 15:11:13 -08001961 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001962 if (added) {
1963 bp = new BasePermission(info.name, tree.sourcePackage,
1964 BasePermission.TYPE_DYNAMIC);
1965 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1966 throw new SecurityException(
1967 "Not allowed to modify non-dynamic permission "
1968 + info.name);
1969 } else {
Dianne Hackborne639da72012-02-21 15:11:13 -08001970 if (bp.protectionLevel == fixedLevel
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001971 && bp.perm.owner.equals(tree.perm.owner)
1972 && bp.uid == tree.uid
1973 && comparePermissionInfos(bp.perm.info, info)) {
1974 changed = false;
1975 }
1976 }
Dianne Hackborne639da72012-02-21 15:11:13 -08001977 bp.protectionLevel = fixedLevel;
1978 info = new PermissionInfo(info);
1979 info.protectionLevel = fixedLevel;
1980 bp.perm = new PackageParser.Permission(tree.perm.owner, info);
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001981 bp.perm.info.packageName = tree.perm.info.packageName;
1982 bp.uid = tree.uid;
1983 if (added) {
1984 mSettings.mPermissions.put(info.name, bp);
1985 }
1986 if (changed) {
1987 if (!async) {
Kenny Root447106f2011-03-23 11:00:15 -07001988 mSettings.writeLPr();
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001989 } else {
1990 scheduleWriteSettingsLocked();
1991 }
1992 }
1993 return added;
1994 }
1995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 public boolean addPermission(PermissionInfo info) {
1997 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001998 return addPermissionLocked(info, false);
1999 }
2000 }
2001
2002 public boolean addPermissionAsync(PermissionInfo info) {
2003 synchronized (mPackages) {
2004 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 }
2006 }
2007
2008 public void removePermission(String name) {
2009 synchronized (mPackages) {
2010 checkPermissionTreeLP(name);
2011 BasePermission bp = mSettings.mPermissions.get(name);
2012 if (bp != null) {
2013 if (bp.type != BasePermission.TYPE_DYNAMIC) {
2014 throw new SecurityException(
2015 "Not allowed to modify non-dynamic permission "
2016 + name);
2017 }
2018 mSettings.mPermissions.remove(name);
Kenny Root447106f2011-03-23 11:00:15 -07002019 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 }
2021 }
2022 }
2023
Dianne Hackborne639da72012-02-21 15:11:13 -08002024 public void grantPermission(String packageName, String permissionName) {
2025 mContext.enforceCallingOrSelfPermission(
2026 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2027 synchronized (mPackages) {
2028 final PackageParser.Package pkg = mPackages.get(packageName);
2029 if (pkg == null) {
2030 throw new IllegalArgumentException("Unknown package: " + packageName);
2031 }
2032 final BasePermission bp = mSettings.mPermissions.get(permissionName);
2033 if (bp == null) {
2034 throw new IllegalArgumentException("Unknown permission: " + packageName);
2035 }
2036 if (!pkg.requestedPermissions.contains(permissionName)) {
2037 throw new SecurityException("Package " + packageName
2038 + " has not requested permission " + permissionName);
2039 }
2040 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) == 0) {
2041 throw new SecurityException("Permission " + permissionName
2042 + " is not a development permission");
2043 }
2044 final PackageSetting ps = (PackageSetting) pkg.mExtras;
2045 if (ps == null) {
2046 return;
2047 }
2048 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2049 if (gp.grantedPermissions.add(permissionName)) {
2050 if (ps.haveGids) {
2051 gp.gids = appendInts(gp.gids, bp.gids);
2052 }
2053 mSettings.writeLPr();
2054 }
2055 }
2056 }
2057
2058 public void revokePermission(String packageName, String permissionName) {
2059 synchronized (mPackages) {
2060 final PackageParser.Package pkg = mPackages.get(packageName);
2061 if (pkg == null) {
2062 throw new IllegalArgumentException("Unknown package: " + packageName);
2063 }
2064 if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2065 mContext.enforceCallingOrSelfPermission(
2066 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2067 }
2068 final BasePermission bp = mSettings.mPermissions.get(permissionName);
2069 if (bp == null) {
2070 throw new IllegalArgumentException("Unknown permission: " + packageName);
2071 }
2072 if (!pkg.requestedPermissions.contains(permissionName)) {
2073 throw new SecurityException("Package " + packageName
2074 + " has not requested permission " + permissionName);
2075 }
2076 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) == 0) {
2077 throw new SecurityException("Permission " + permissionName
2078 + " is not a development permission");
2079 }
2080 final PackageSetting ps = (PackageSetting) pkg.mExtras;
2081 if (ps == null) {
2082 return;
2083 }
2084 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2085 if (gp.grantedPermissions.remove(permissionName)) {
2086 gp.grantedPermissions.remove(permissionName);
2087 if (ps.haveGids) {
2088 gp.gids = removeInts(gp.gids, bp.gids);
2089 }
2090 mSettings.writeLPr();
2091 }
2092 }
2093 }
2094
Dianne Hackborn854060af2009-07-09 18:14:31 -07002095 public boolean isProtectedBroadcast(String actionName) {
2096 synchronized (mPackages) {
2097 return mProtectedBroadcasts.contains(actionName);
2098 }
2099 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 public int checkSignatures(String pkg1, String pkg2) {
2102 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002103 final PackageParser.Package p1 = mPackages.get(pkg1);
2104 final PackageParser.Package p2 = mPackages.get(pkg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 if (p1 == null || p1.mExtras == null
2106 || p2 == null || p2.mExtras == null) {
2107 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2108 }
Kenny Root447106f2011-03-23 11:00:15 -07002109 return compareSignatures(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 }
2111 }
2112
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002113 public int checkUidSignatures(int uid1, int uid2) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002114 // Map to base uids.
2115 uid1 = UserId.getAppId(uid1);
2116 uid2 = UserId.getAppId(uid2);
Kenny Root447106f2011-03-23 11:00:15 -07002117 // reader
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002118 synchronized (mPackages) {
2119 Signature[] s1;
2120 Signature[] s2;
Kenny Root447106f2011-03-23 11:00:15 -07002121 Object obj = mSettings.getUserIdLPr(uid1);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002122 if (obj != null) {
2123 if (obj instanceof SharedUserSetting) {
2124 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2125 } else if (obj instanceof PackageSetting) {
2126 s1 = ((PackageSetting)obj).signatures.mSignatures;
2127 } else {
2128 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2129 }
2130 } else {
2131 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2132 }
Kenny Root447106f2011-03-23 11:00:15 -07002133 obj = mSettings.getUserIdLPr(uid2);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002134 if (obj != null) {
2135 if (obj instanceof SharedUserSetting) {
2136 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2137 } else if (obj instanceof PackageSetting) {
2138 s2 = ((PackageSetting)obj).signatures.mSignatures;
2139 } else {
2140 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2141 }
2142 } else {
2143 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2144 }
Kenny Root447106f2011-03-23 11:00:15 -07002145 return compareSignatures(s1, s2);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002146 }
2147 }
2148
Kenny Root447106f2011-03-23 11:00:15 -07002149 static int compareSignatures(Signature[] s1, Signature[] s2) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002150 if (s1 == null) {
2151 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 ? PackageManager.SIGNATURE_NEITHER_SIGNED
2153 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2154 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07002155 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002156 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2157 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002158 HashSet<Signature> set1 = new HashSet<Signature>();
2159 for (Signature sig : s1) {
2160 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002162 HashSet<Signature> set2 = new HashSet<Signature>();
2163 for (Signature sig : s2) {
2164 set2.add(sig);
2165 }
2166 // Make sure s2 contains all signatures in s1.
2167 if (set1.equals(set2)) {
2168 return PackageManager.SIGNATURE_MATCH;
2169 }
2170 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 }
2172
2173 public String[] getPackagesForUid(int uid) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002174 uid = UserId.getAppId(uid);
Kenny Root447106f2011-03-23 11:00:15 -07002175 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002177 Object obj = mSettings.getUserIdLPr(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002178 if (obj instanceof SharedUserSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002179 final SharedUserSetting sus = (SharedUserSetting) obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002180 final int N = sus.packages.size();
Kenny Root447106f2011-03-23 11:00:15 -07002181 final String[] res = new String[N];
2182 final Iterator<PackageSetting> it = sus.packages.iterator();
2183 int i = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 while (it.hasNext()) {
2185 res[i++] = it.next().name;
2186 }
2187 return res;
2188 } else if (obj instanceof PackageSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002189 final PackageSetting ps = (PackageSetting) obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002190 return new String[] { ps.name };
2191 }
2192 }
2193 return null;
2194 }
2195
2196 public String getNameForUid(int uid) {
Kenny Root447106f2011-03-23 11:00:15 -07002197 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002198 synchronized (mPackages) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002199 Object obj = mSettings.getUserIdLPr(UserId.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 if (obj instanceof SharedUserSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002201 final SharedUserSetting sus = (SharedUserSetting) obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 return sus.name + ":" + sus.userId;
2203 } else if (obj instanceof PackageSetting) {
Kenny Root447106f2011-03-23 11:00:15 -07002204 final PackageSetting ps = (PackageSetting) obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 return ps.name;
2206 }
2207 }
2208 return null;
2209 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211 public int getUidForSharedUser(String sharedUserName) {
2212 if(sharedUserName == null) {
2213 return -1;
2214 }
Kenny Root447106f2011-03-23 11:00:15 -07002215 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002217 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
Amith Yamasani742a6712011-05-04 14:49:28 -07002218 if (suid == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002219 return -1;
2220 }
2221 return suid.userId;
2222 }
2223 }
2224
2225 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2226 int flags) {
2227 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02002228 return chooseBestActivity(intent, resolvedType, flags, query);
2229 }
2230
Mihai Predaeae850c2009-05-13 10:13:48 +02002231 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2232 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002233 if (query != null) {
2234 final int N = query.size();
2235 if (N == 1) {
2236 return query.get(0);
2237 } else if (N > 1) {
2238 // If there is more than one activity with the same priority,
2239 // then let the user decide between them.
2240 ResolveInfo r0 = query.get(0);
2241 ResolveInfo r1 = query.get(1);
Kenny Root4dfe6ff2011-02-23 17:00:43 -08002242 if (DEBUG_INTENT_MATCHING) {
2243 Log.d(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2244 + r1.activityInfo.name + "=" + r1.priority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 }
2246 // If the first activity has a higher priority, or a different
2247 // default, then it is always desireable to pick it.
2248 if (r0.priority != r1.priority
2249 || r0.preferredOrder != r1.preferredOrder
2250 || r0.isDefault != r1.isDefault) {
2251 return query.get(0);
2252 }
2253 // If we have saved a preference for a preferred activity for
2254 // this Intent, use that.
2255 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2256 flags, query, r0.priority);
2257 if (ri != null) {
2258 return ri;
2259 }
2260 return mResolveInfo;
2261 }
2262 }
2263 return null;
2264 }
2265
2266 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
2267 int flags, List<ResolveInfo> query, int priority) {
Kenny Root447106f2011-03-23 11:00:15 -07002268 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 synchronized (mPackages) {
Dianne Hackbornf5b86712011-12-05 17:42:41 -08002270 if (intent.getSelector() != null) {
2271 intent = intent.getSelector();
2272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
2274 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02002275 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
2277 if (prefs != null && prefs.size() > 0) {
2278 // First figure out how good the original match set is.
2279 // We will only allow preferred activities that came
2280 // from the same match quality.
2281 int match = 0;
Kenny Root447106f2011-03-23 11:00:15 -07002282
2283 if (DEBUG_PREFERRED) {
2284 Log.v(TAG, "Figuring out best match...");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 }
Kenny Root447106f2011-03-23 11:00:15 -07002286
2287 final int N = query.size();
2288 for (int j=0; j<N; j++) {
2289 final ResolveInfo ri = query.get(j);
2290 if (DEBUG_PREFERRED) {
2291 Log.v(TAG, "Match for " + ri.activityInfo + ": 0x"
2292 + Integer.toHexString(match));
2293 }
2294 if (ri.match > match) {
2295 match = ri.match;
2296 }
2297 }
2298
2299 if (DEBUG_PREFERRED) {
2300 Log.v(TAG, "Best match: 0x" + Integer.toHexString(match));
2301 }
2302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303 match &= IntentFilter.MATCH_CATEGORY_MASK;
2304 final int M = prefs.size();
2305 for (int i=0; i<M; i++) {
Kenny Root447106f2011-03-23 11:00:15 -07002306 final PreferredActivity pa = prefs.get(i);
Dianne Hackbornf8b8a3f2011-03-04 00:05:31 -08002307 if (pa.mPref.mMatch != match) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 continue;
2309 }
Kenny Root447106f2011-03-23 11:00:15 -07002310 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 if (DEBUG_PREFERRED) {
2312 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002313 if (ai != null) {
2314 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2315 } else {
2316 Log.v(TAG, " null");
2317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 }
Dianne Hackborn04505102012-02-29 12:34:04 -08002319 if (ai == null) {
2320 // This previously registered preferred activity
2321 // component is no longer known. Most likely an update
2322 // to the app was installed and in the new version this
2323 // component no longer exists. Clean it up by removing
2324 // it from the preferred activities list, and skip it.
2325 Slog.w(TAG, "Removing dangling preferred activity: "
2326 + pa.mPref.mComponent);
2327 mSettings.mPreferredActivities.removeFilter(pa);
2328 continue;
2329 }
2330 for (int j=0; j<N; j++) {
2331 final ResolveInfo ri = query.get(j);
2332 if (!ri.activityInfo.applicationInfo.packageName
2333 .equals(ai.applicationInfo.packageName)) {
2334 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002335 }
Dianne Hackborn04505102012-02-29 12:34:04 -08002336 if (!ri.activityInfo.name.equals(ai.name)) {
2337 continue;
2338 }
2339
2340 // Okay we found a previously set preferred app.
2341 // If the result set is different from when this
2342 // was created, we need to clear it and re-ask the
2343 // user their preference.
2344 if (!pa.mPref.sameSet(query, priority)) {
2345 Slog.i(TAG, "Result set changed, dropping preferred activity for "
2346 + intent + " type " + resolvedType);
2347 mSettings.mPreferredActivities.removeFilter(pa);
2348 return null;
2349 }
2350
2351 // Yay!
2352 return ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 }
2354 }
2355 }
2356 }
2357 return null;
2358 }
2359
2360 public List<ResolveInfo> queryIntentActivities(Intent intent,
2361 String resolvedType, int flags) {
Dianne Hackbornf5b86712011-12-05 17:42:41 -08002362 ComponentName comp = intent.getComponent();
2363 if (comp == null) {
2364 if (intent.getSelector() != null) {
2365 intent = intent.getSelector();
2366 comp = intent.getComponent();
2367 }
2368 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370 if (comp != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002371 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2372 final ActivityInfo ai = getActivityInfo(comp, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 if (ai != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002374 final ResolveInfo ri = new ResolveInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 ri.activityInfo = ai;
2376 list.add(ri);
2377 }
2378 return list;
2379 }
2380
Kenny Root447106f2011-03-23 11:00:15 -07002381 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002382 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002383 final String pkgName = intent.getPackage();
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002384 if (pkgName == null) {
Kenny Root447106f2011-03-23 11:00:15 -07002385 return mActivities.queryIntent(intent, resolvedType, flags);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002386 }
Kenny Root447106f2011-03-23 11:00:15 -07002387 final PackageParser.Package pkg = mPackages.get(pkgName);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002388 if (pkg != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002389 return mActivities.queryIntentForPackage(intent, resolvedType, flags,
2390 pkg.activities);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002391 }
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002392 return new ArrayList<ResolveInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002393 }
2394 }
2395
2396 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2397 Intent[] specifics, String[] specificTypes, Intent intent,
2398 String resolvedType, int flags) {
2399 final String resultsAction = intent.getAction();
2400
Kenny Root447106f2011-03-23 11:00:15 -07002401 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
2402 | PackageManager.GET_RESOLVED_FILTER);
2403
2404 if (DEBUG_INTENT_MATCHING) {
2405 Log.v(TAG, "Query " + intent + ": " + results);
2406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002407
2408 int specificsPos = 0;
2409 int N;
2410
2411 // todo: note that the algorithm used here is O(N^2). This
2412 // isn't a problem in our current environment, but if we start running
2413 // into situations where we have more than 5 or 10 matches then this
2414 // should probably be changed to something smarter...
2415
2416 // First we go through and resolve each of the specific items
2417 // that were supplied, taking care of removing any corresponding
2418 // duplicate items in the generic resolve list.
2419 if (specifics != null) {
2420 for (int i=0; i<specifics.length; i++) {
2421 final Intent sintent = specifics[i];
2422 if (sintent == null) {
2423 continue;
2424 }
2425
Kenny Root447106f2011-03-23 11:00:15 -07002426 if (DEBUG_INTENT_MATCHING) {
2427 Log.v(TAG, "Specific #" + i + ": " + sintent);
2428 }
2429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 String action = sintent.getAction();
2431 if (resultsAction != null && resultsAction.equals(action)) {
2432 // If this action was explicitly requested, then don't
2433 // remove things that have it.
2434 action = null;
2435 }
Kenny Root447106f2011-03-23 11:00:15 -07002436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002437 ResolveInfo ri = null;
2438 ActivityInfo ai = null;
Kenny Root447106f2011-03-23 11:00:15 -07002439
2440 ComponentName comp = sintent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 if (comp == null) {
2442 ri = resolveIntent(
2443 sintent,
2444 specificTypes != null ? specificTypes[i] : null,
2445 flags);
2446 if (ri == null) {
2447 continue;
2448 }
2449 if (ri == mResolveInfo) {
2450 // ACK! Must do something better with this.
2451 }
2452 ai = ri.activityInfo;
2453 comp = new ComponentName(ai.applicationInfo.packageName,
2454 ai.name);
2455 } else {
2456 ai = getActivityInfo(comp, flags);
2457 if (ai == null) {
2458 continue;
2459 }
2460 }
2461
2462 // Look for any generic query activities that are duplicates
2463 // of this specific one, and remove them from the results.
Kenny Root9718cf52011-02-23 16:45:26 -08002464 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465 N = results.size();
2466 int j;
2467 for (j=specificsPos; j<N; j++) {
2468 ResolveInfo sri = results.get(j);
2469 if ((sri.activityInfo.name.equals(comp.getClassName())
2470 && sri.activityInfo.applicationInfo.packageName.equals(
2471 comp.getPackageName()))
2472 || (action != null && sri.filter.matchAction(action))) {
2473 results.remove(j);
Kenny Root9718cf52011-02-23 16:45:26 -08002474 if (DEBUG_INTENT_MATCHING) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002475 TAG, "Removing duplicate item from " + j
2476 + " due to specific " + specificsPos);
2477 if (ri == null) {
2478 ri = sri;
2479 }
2480 j--;
2481 N--;
2482 }
2483 }
2484
2485 // Add this specific item to its proper place.
2486 if (ri == null) {
2487 ri = new ResolveInfo();
2488 ri.activityInfo = ai;
2489 }
2490 results.add(specificsPos, ri);
2491 ri.specificIndex = i;
2492 specificsPos++;
2493 }
2494 }
2495
2496 // Now we go through the remaining generic results and remove any
2497 // duplicate actions that are found here.
2498 N = results.size();
2499 for (int i=specificsPos; i<N-1; i++) {
2500 final ResolveInfo rii = results.get(i);
2501 if (rii.filter == null) {
2502 continue;
2503 }
2504
2505 // Iterate over all of the actions of this result's intent
2506 // filter... typically this should be just one.
2507 final Iterator<String> it = rii.filter.actionsIterator();
2508 if (it == null) {
2509 continue;
2510 }
2511 while (it.hasNext()) {
2512 final String action = it.next();
2513 if (resultsAction != null && resultsAction.equals(action)) {
2514 // If this action was explicitly requested, then don't
2515 // remove things that have it.
2516 continue;
2517 }
2518 for (int j=i+1; j<N; j++) {
2519 final ResolveInfo rij = results.get(j);
2520 if (rij.filter != null && rij.filter.hasAction(action)) {
2521 results.remove(j);
Kenny Root9718cf52011-02-23 16:45:26 -08002522 if (DEBUG_INTENT_MATCHING) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 TAG, "Removing duplicate item from " + j
2524 + " due to action " + action + " at " + i);
2525 j--;
2526 N--;
2527 }
2528 }
2529 }
2530
2531 // If the caller didn't request filter information, drop it now
2532 // so we don't have to marshall/unmarshall it.
2533 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2534 rii.filter = null;
2535 }
2536 }
2537
2538 // Filter out the caller activity if so requested.
2539 if (caller != null) {
2540 N = results.size();
2541 for (int i=0; i<N; i++) {
2542 ActivityInfo ainfo = results.get(i).activityInfo;
2543 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2544 && caller.getClassName().equals(ainfo.name)) {
2545 results.remove(i);
2546 break;
2547 }
2548 }
2549 }
2550
2551 // If the caller didn't request filter information,
2552 // drop them now so we don't have to
2553 // marshall/unmarshall it.
2554 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2555 N = results.size();
2556 for (int i=0; i<N; i++) {
2557 results.get(i).filter = null;
2558 }
2559 }
2560
Kenny Root9718cf52011-02-23 16:45:26 -08002561 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 return results;
2563 }
2564
Kenny Root447106f2011-03-23 11:00:15 -07002565 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags) {
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002566 ComponentName comp = intent.getComponent();
Dianne Hackbornf5b86712011-12-05 17:42:41 -08002567 if (comp == null) {
2568 if (intent.getSelector() != null) {
2569 intent = intent.getSelector();
2570 comp = intent.getComponent();
2571 }
2572 }
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002573 if (comp != null) {
2574 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2575 ActivityInfo ai = getReceiverInfo(comp, flags);
2576 if (ai != null) {
2577 ResolveInfo ri = new ResolveInfo();
2578 ri.activityInfo = ai;
2579 list.add(ri);
2580 }
2581 return list;
2582 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002583
Kenny Root447106f2011-03-23 11:00:15 -07002584 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 synchronized (mPackages) {
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002586 String pkgName = intent.getPackage();
2587 if (pkgName == null) {
Kenny Root447106f2011-03-23 11:00:15 -07002588 return mReceivers.queryIntent(intent, resolvedType, flags);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002589 }
Kenny Root447106f2011-03-23 11:00:15 -07002590 final PackageParser.Package pkg = mPackages.get(pkgName);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002591 if (pkg != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002592 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002593 }
2594 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 }
2596 }
2597
Kenny Root447106f2011-03-23 11:00:15 -07002598 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags) {
2599 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 if (query != null) {
2601 if (query.size() >= 1) {
2602 // If there is more than one service with the same priority,
2603 // just arbitrarily pick the first one.
2604 return query.get(0);
2605 }
2606 }
2607 return null;
2608 }
2609
Kenny Root447106f2011-03-23 11:00:15 -07002610 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags) {
Dianne Hackbornf5b86712011-12-05 17:42:41 -08002611 ComponentName comp = intent.getComponent();
2612 if (comp == null) {
2613 if (intent.getSelector() != null) {
2614 intent = intent.getSelector();
2615 comp = intent.getComponent();
2616 }
2617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002618 if (comp != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002619 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2620 final ServiceInfo si = getServiceInfo(comp, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 if (si != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002622 final ResolveInfo ri = new ResolveInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 ri.serviceInfo = si;
2624 list.add(ri);
2625 }
2626 return list;
2627 }
2628
Kenny Root447106f2011-03-23 11:00:15 -07002629 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 synchronized (mPackages) {
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002631 String pkgName = intent.getPackage();
2632 if (pkgName == null) {
Kenny Root447106f2011-03-23 11:00:15 -07002633 return mServices.queryIntent(intent, resolvedType, flags);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002634 }
Kenny Root447106f2011-03-23 11:00:15 -07002635 final PackageParser.Package pkg = mPackages.get(pkgName);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002636 if (pkg != null) {
Kenny Root447106f2011-03-23 11:00:15 -07002637 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services);
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002638 }
2639 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 }
2641 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002642
Kenny Root0e2c0f32011-04-15 17:50:10 -07002643 private static final int getContinuationPoint(final String[] keys, final String key) {
2644 final int index;
2645 if (key == null) {
2646 index = 0;
2647 } else {
2648 final int insertPoint = Arrays.binarySearch(keys, key);
2649 if (insertPoint < 0) {
2650 index = -insertPoint;
2651 } else {
2652 index = insertPoint + 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 }
2654 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002655 return index;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 }
2657
Kenny Root0e2c0f32011-04-15 17:50:10 -07002658 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, String lastRead) {
2659 final ParceledListSlice<PackageInfo> list = new ParceledListSlice<PackageInfo>();
2660 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
2661 final String[] keys;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662
Kenny Root447106f2011-03-23 11:00:15 -07002663 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 synchronized (mPackages) {
Kenny Root0e2c0f32011-04-15 17:50:10 -07002665 if (listUninstalled) {
2666 keys = mSettings.mPackages.keySet().toArray(new String[mSettings.mPackages.size()]);
2667 } else {
2668 keys = mPackages.keySet().toArray(new String[mPackages.size()]);
2669 }
2670
2671 Arrays.sort(keys);
2672 int i = getContinuationPoint(keys, lastRead);
2673 final int N = keys.length;
2674
2675 while (i < N) {
2676 final String packageName = keys[i++];
2677
2678 PackageInfo pi = null;
2679 if (listUninstalled) {
2680 final PackageSetting ps = mSettings.mPackages.get(packageName);
2681 if (ps != null) {
Kenny Roota51b6fd62011-05-19 15:02:18 -07002682 pi = generatePackageInfoFromSettingsLPw(ps.name, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002684 } else {
2685 final PackageParser.Package p = mPackages.get(packageName);
2686 if (p != null) {
2687 pi = generatePackageInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 }
2689 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002690
2691 if (pi != null && !list.append(pi)) {
2692 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 }
2694 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002695
2696 if (i == N) {
2697 list.setLastSlice(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002700
2701 return list;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 }
2703
Kenny Root0e2c0f32011-04-15 17:50:10 -07002704 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags,
2705 String lastRead) {
2706 final ParceledListSlice<ApplicationInfo> list = new ParceledListSlice<ApplicationInfo>();
2707 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
2708 final String[] keys;
2709
Kenny Root447106f2011-03-23 11:00:15 -07002710 // writer
Kenny Root0e2c0f32011-04-15 17:50:10 -07002711 synchronized (mPackages) {
2712 if (listUninstalled) {
2713 keys = mSettings.mPackages.keySet().toArray(new String[mSettings.mPackages.size()]);
2714 } else {
2715 keys = mPackages.keySet().toArray(new String[mPackages.size()]);
2716 }
2717
2718 Arrays.sort(keys);
2719 int i = getContinuationPoint(keys, lastRead);
2720 final int N = keys.length;
Amith Yamasani742a6712011-05-04 14:49:28 -07002721 final int userId = UserId.getUserId(Binder.getCallingUid());
Kenny Root0e2c0f32011-04-15 17:50:10 -07002722
2723 while (i < N) {
2724 final String packageName = keys[i++];
2725
2726 ApplicationInfo ai = null;
2727 if (listUninstalled) {
2728 final PackageSetting ps = mSettings.mPackages.get(packageName);
2729 if (ps != null) {
Kenny Roota51b6fd62011-05-19 15:02:18 -07002730 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags);
Kenny Root0e2c0f32011-04-15 17:50:10 -07002731 }
2732 } else {
2733 final PackageParser.Package p = mPackages.get(packageName);
2734 if (p != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002735 ai = PackageParser.generateApplicationInfo(p, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736 }
2737 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002738
2739 if (ai != null && !list.append(ai)) {
2740 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002741 }
2742 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002743
2744 if (i == N) {
2745 list.setLastSlice(true);
2746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 }
Kenny Root0e2c0f32011-04-15 17:50:10 -07002748
2749 return list;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750 }
2751
2752 public List<ApplicationInfo> getPersistentApplications(int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07002753 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002754
Kenny Root447106f2011-03-23 11:00:15 -07002755 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002757 final Iterator<PackageParser.Package> i = mPackages.values().iterator();
Amith Yamasani742a6712011-05-04 14:49:28 -07002758 final int userId = UserId.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 while (i.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07002760 final PackageParser.Package p = i.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761 if (p.applicationInfo != null
2762 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002763 && (!mSafeMode || isSystemApp(p))) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002764 finalList.add(PackageParser.generateApplicationInfo(p, flags, userId));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 }
2766 }
2767 }
2768
2769 return finalList;
2770 }
2771
2772 public ProviderInfo resolveContentProvider(String name, int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07002773 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774 synchronized (mPackages) {
2775 final PackageParser.Provider provider = mProviders.get(name);
2776 return provider != null
Kenny Root447106f2011-03-23 11:00:15 -07002777 && mSettings.isEnabledLPr(provider.info, flags)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002778 && (!mSafeMode || (provider.info.applicationInfo.flags
2779 &ApplicationInfo.FLAG_SYSTEM) != 0)
Amith Yamasani742a6712011-05-04 14:49:28 -07002780 ? PackageParser.generateProviderInfo(provider, flags,
2781 UserId.getUserId(Binder.getCallingUid()))
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 : null;
2783 }
2784 }
2785
Fred Quintana718d8a22009-04-29 17:53:20 -07002786 /**
2787 * @deprecated
2788 */
Kenny Root60f7ad82011-03-22 12:49:06 -07002789 @Deprecated
2790 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
Kenny Root447106f2011-03-23 11:00:15 -07002791 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002792 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002793 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProviders.entrySet()
2794 .iterator();
Amith Yamasani742a6712011-05-04 14:49:28 -07002795 final int userId = UserId.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 while (i.hasNext()) {
2797 Map.Entry<String, PackageParser.Provider> entry = i.next();
2798 PackageParser.Provider p = entry.getValue();
2799
2800 if (p.syncable
2801 && (!mSafeMode || (p.info.applicationInfo.flags
2802 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2803 outNames.add(entry.getKey());
Amith Yamasani742a6712011-05-04 14:49:28 -07002804 outInfo.add(PackageParser.generateProviderInfo(p, 0, userId));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002805 }
2806 }
2807 }
2808 }
2809
2810 public List<ProviderInfo> queryContentProviders(String processName,
2811 int uid, int flags) {
2812 ArrayList<ProviderInfo> finalList = null;
2813
Kenny Root447106f2011-03-23 11:00:15 -07002814 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002816 final Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
Amith Yamasani742a6712011-05-04 14:49:28 -07002817 final int userId = UserId.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 while (i.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07002819 final PackageParser.Provider p = i.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 if (p.info.authority != null
Kenny Root447106f2011-03-23 11:00:15 -07002821 && (processName == null
2822 || (p.info.processName.equals(processName)
Amith Yamasani742a6712011-05-04 14:49:28 -07002823 && UserId.getAppId(p.info.applicationInfo.uid)
2824 == UserId.getAppId(uid)))
Kenny Root447106f2011-03-23 11:00:15 -07002825 && mSettings.isEnabledLPr(p.info, flags)
2826 && (!mSafeMode
2827 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 if (finalList == null) {
2829 finalList = new ArrayList<ProviderInfo>(3);
2830 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002831 finalList.add(PackageParser.generateProviderInfo(p, flags, userId));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 }
2833 }
2834 }
2835
2836 if (finalList != null) {
2837 Collections.sort(finalList, mProviderInitOrderSorter);
2838 }
2839
2840 return finalList;
2841 }
2842
2843 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2844 int flags) {
Kenny Root447106f2011-03-23 11:00:15 -07002845 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002846 synchronized (mPackages) {
2847 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2848 return PackageParser.generateInstrumentationInfo(i, flags);
2849 }
2850 }
2851
2852 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2853 int flags) {
2854 ArrayList<InstrumentationInfo> finalList =
2855 new ArrayList<InstrumentationInfo>();
2856
Kenny Root447106f2011-03-23 11:00:15 -07002857 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07002859 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 while (i.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07002861 final PackageParser.Instrumentation p = i.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 if (targetPackage == null
2863 || targetPackage.equals(p.info.targetPackage)) {
2864 finalList.add(PackageParser.generateInstrumentationInfo(p,
2865 flags));
2866 }
2867 }
2868 }
2869
2870 return finalList;
2871 }
2872
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002873 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 String[] files = dir.list();
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07002875 if (files == null) {
2876 Log.d(TAG, "No files in app dir " + dir);
2877 return;
2878 }
2879
Kenny Root4dfe6ff2011-02-23 17:00:43 -08002880 if (DEBUG_PACKAGE_SCANNING) {
Joe Onorato431bb222010-10-18 19:13:23 -04002881 Log.d(TAG, "Scanning app dir " + dir);
2882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883
2884 int i;
2885 for (i=0; i<files.length; i++) {
2886 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002887 if (!isPackageFilename(files[i])) {
2888 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002889 continue;
2890 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002891 PackageParser.Package pkg = scanPackageLI(file,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002892 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002893 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002894 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2895 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002896 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002897 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002898 file.delete();
2899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 }
2901 }
2902
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002903 private static File getSettingsProblemFile() {
2904 File dataDir = Environment.getDataDirectory();
2905 File systemDir = new File(dataDir, "system");
2906 File fname = new File(systemDir, "uiderrors.txt");
2907 return fname;
2908 }
2909
Kenny Rootcf0b38c2011-03-22 14:17:59 -07002910 static void reportSettingsProblem(int priority, String msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002911 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002912 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 FileOutputStream out = new FileOutputStream(fname, true);
2914 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002915 SimpleDateFormat formatter = new SimpleDateFormat();
2916 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2917 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 pw.close();
2919 FileUtils.setPermissions(
2920 fname.toString(),
2921 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2922 -1, -1);
2923 } catch (java.io.IOException e) {
2924 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002925 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926 }
2927
2928 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2929 PackageParser.Package pkg, File srcFile, int parseFlags) {
2930 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002931 if (ps != null
2932 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07002933 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07002934 if (ps.signatures.mSignatures != null
2935 && ps.signatures.mSignatures.length != 0) {
2936 // Optimization: reuse the existing cached certificates
2937 // if the package appears to be unchanged.
2938 pkg.mSignatures = ps.signatures.mSignatures;
2939 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 }
Jeff Browne7600722010-04-07 18:28:23 -07002941
2942 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002943 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002944 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2945 }
2946
2947 if (!pp.collectCertificates(pkg, parseFlags)) {
2948 mLastScanError = pp.getParseError();
2949 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 }
2951 }
2952 return true;
2953 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002955 /*
2956 * Scan a package and return the newly parsed package.
2957 * Returns null in case of errors and the error code is stored in mLastScanError
2958 */
2959 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002960 int parseFlags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002961 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002962 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002963 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002964 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965 pp.setSeparateProcesses(mSeparateProcesses);
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07002966 pp.setOnlyCoreApps(mOnlyCore);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002967 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002968 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002969 if (pkg == null) {
2970 mLastScanError = pp.getParseError();
2971 return null;
2972 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002973 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 PackageSetting updatedPkg;
Kenny Root447106f2011-03-23 11:00:15 -07002975 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002977 // Look to see if we already know about this package.
2978 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002979 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002980 // This package has been renamed to its original name. Let's
2981 // use that.
Kenny Root447106f2011-03-23 11:00:15 -07002982 ps = mSettings.peekPackageLPr(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002983 }
2984 // If there was no original package, see one for the real package name.
2985 if (ps == null) {
Kenny Root447106f2011-03-23 11:00:15 -07002986 ps = mSettings.peekPackageLPr(pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002987 }
2988 // Check to see if this package could be hiding/updating a system
2989 // package. Must look for it either under the original or real
2990 // package name depending on our state.
2991 updatedPkg = mSettings.mDisabledSysPackages.get(
2992 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002993 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002994 // First check if this is a system package that may involve an update
2995 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002996 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002997 // The path has changed from what was last scanned... check the
2998 // version of the new path against what we have stored to determine
2999 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003000 if (pkg.mVersionCode < ps.versionCode) {
3001 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003002 // Ignore entry. Skip it.
3003 Log.i(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborncef65ee2010-09-30 18:27:22 -07003004 + " ignored: updated version " + ps.versionCode
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003005 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003006 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3007 return null;
3008 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003009 // The current app on the system partion is better than
3010 // what we have updated to on the data partition; switch
3011 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003012 // At this point, its safely assumed that package installation for
3013 // apps in system partition will go through. If not there won't be a working
3014 // version of the app
Kenny Root447106f2011-03-23 11:00:15 -07003015 // writer
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003016 synchronized (mPackages) {
3017 // Just remove the loaded entries from package lists.
3018 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003019 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003020 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003021 + "reverting from " + ps.codePathString
3022 + ": new version " + pkg.mVersionCode
3023 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07003024 InstallArgs args = new FileInstallArgs(ps.codePathString,
3025 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003026 args.cleanUpResourcesLI();
Kenny Root447106f2011-03-23 11:00:15 -07003027 mSettings.enableSystemPackageLPw(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 }
3030 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003031 if (updatedPkg != null) {
3032 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
3033 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
3034 }
3035 // Verify certificates against what was last scanned
3036 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003037 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003038 return null;
3039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 // The apk is forward locked (not public) if its code and resources
3041 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003042 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003043 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003044 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07003045 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003046
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003047 String codePath = null;
3048 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003049 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
3050 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003051 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003052 } else {
3053 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003054 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003055 }
3056 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003057 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003058 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003059 codePath = pkg.mScanPath;
3060 // Set application objects path explicitly.
3061 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003062 // Note that we invoke the following method only if we are about to unpack an application
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003063 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE, currentTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 }
3065
Kenny Root85387d72010-08-26 10:13:11 -07003066 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
3067 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003068 pkg.mPath = pkg.mScanPath = destCodePath;
3069 pkg.applicationInfo.sourceDir = destCodePath;
3070 pkg.applicationInfo.publicSourceDir = destResPath;
3071 }
3072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 private static String fixProcessName(String defProcessName,
3074 String processName, int uid) {
3075 if (processName == null) {
3076 return defProcessName;
3077 }
3078 return processName;
3079 }
3080
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003081 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003082 PackageParser.Package pkg) {
3083 if (pkgSetting.signatures.mSignatures != null) {
3084 // Already existing package. Make sure signatures match
Kenny Root447106f2011-03-23 11:00:15 -07003085 if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003086 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003087 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003088 + " signatures do not match the previously installed version; ignoring!");
3089 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090 return false;
3091 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003092 }
3093 // Check for shared user signatures
3094 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
Kenny Root447106f2011-03-23 11:00:15 -07003095 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003096 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3097 Slog.e(TAG, "Package " + pkg.packageName
3098 + " has no signatures that match those in shared user "
3099 + pkgSetting.sharedUser.name + "; ignoring!");
3100 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
3101 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003103 }
3104 return true;
3105 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003106
Kenny Root461ff1f2011-08-09 09:43:03 -07003107 /**
3108 * Enforces that only the system UID or root's UID can call a method exposed
3109 * via Binder.
3110 *
3111 * @param message used as message if SecurityException is thrown
3112 * @throws SecurityException if the caller is not system or root
3113 */
3114 private static final void enforceSystemOrRoot(String message) {
3115 final int uid = Binder.getCallingUid();
3116 if (uid != Process.SYSTEM_UID && uid != 0) {
3117 throw new SecurityException(message);
3118 }
3119 }
3120
Dianne Hackborn661cd522011-08-22 00:26:20 -07003121 public void performBootDexOpt() {
3122 ArrayList<PackageParser.Package> pkgs = null;
3123 synchronized (mPackages) {
3124 if (mDeferredDexOpt.size() > 0) {
3125 pkgs = new ArrayList<PackageParser.Package>(mDeferredDexOpt);
3126 mDeferredDexOpt.clear();
3127 }
3128 }
3129 if (pkgs != null) {
3130 for (int i=0; i<pkgs.size(); i++) {
Dianne Hackborn58f42a52011-10-10 13:46:34 -07003131 if (!isFirstBoot()) {
3132 try {
3133 ActivityManagerNative.getDefault().showBootMessage(
3134 mContext.getResources().getString(
3135 com.android.internal.R.string.android_upgrading_apk,
3136 i+1, pkgs.size()), true);
3137 } catch (RemoteException e) {
3138 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07003139 }
3140 PackageParser.Package p = pkgs.get(i);
3141 synchronized (mInstallLock) {
3142 if (!p.mDidDexOpt) {
3143 performDexOptLI(p, false, false);
3144 }
3145 }
3146 }
3147 }
3148 }
3149
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003150 public boolean performDexOpt(String packageName) {
Kenny Root461ff1f2011-08-09 09:43:03 -07003151 enforceSystemOrRoot("Only the system can request dexopt be performed");
3152
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003153 if (!mNoDexOpt) {
3154 return false;
3155 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003156
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003157 PackageParser.Package p;
3158 synchronized (mPackages) {
3159 p = mPackages.get(packageName);
3160 if (p == null || p.mDidDexOpt) {
3161 return false;
3162 }
3163 }
3164 synchronized (mInstallLock) {
Dianne Hackborn661cd522011-08-22 00:26:20 -07003165 return performDexOptLI(p, false, false) == DEX_OPT_PERFORMED;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003166 }
3167 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003168
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003169 static final int DEX_OPT_SKIPPED = 0;
3170 static final int DEX_OPT_PERFORMED = 1;
Dianne Hackborn661cd522011-08-22 00:26:20 -07003171 static final int DEX_OPT_DEFERRED = 2;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003172 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003173
Dianne Hackborn661cd522011-08-22 00:26:20 -07003174 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003175 boolean performed = false;
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003176 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003177 String path = pkg.mScanPath;
3178 int ret = 0;
3179 try {
3180 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Dianne Hackborn661cd522011-08-22 00:26:20 -07003181 if (!forceDex && defer) {
3182 mDeferredDexOpt.add(pkg);
3183 return DEX_OPT_DEFERRED;
3184 } else {
3185 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
3186 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
3187 !isForwardLocked(pkg));
3188 pkg.mDidDexOpt = true;
3189 performed = true;
3190 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003191 }
3192 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003193 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003194 ret = -1;
3195 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07003196 Slog.w(TAG, "IOException reading apk: " + path, e);
3197 ret = -1;
3198 } catch (dalvik.system.StaleDexCacheError e) {
3199 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
3200 ret = -1;
3201 } catch (Exception e) {
3202 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003203 ret = -1;
3204 }
3205 if (ret < 0) {
3206 //error from installer
3207 return DEX_OPT_FAILED;
3208 }
3209 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003210
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003211 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
3212 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08003213
Kenny Root447106f2011-03-23 11:00:15 -07003214 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003215 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003216 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003217 + " to " + newPkg.packageName
3218 + ": old package not in system partition");
3219 return false;
3220 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003221 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003222 + " to " + newPkg.packageName
3223 + ": old package still exists");
3224 return false;
3225 }
3226 return true;
3227 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003228
Amith Yamasani0b285492011-04-14 17:35:23 -07003229 File getDataPathForUser(int userId) {
3230 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003231 }
Amith Yamasani0b285492011-04-14 17:35:23 -07003232
3233 private File getDataPathForPackage(String packageName, int userId) {
Kenny Root9c8625e2011-07-25 09:42:22 -07003234 /*
3235 * Until we fully support multiple users, return the directory we
3236 * previously would have. The PackageManagerTests will need to be
3237 * revised when this is changed back..
3238 */
3239 if (userId == 0) {
3240 return new File(mAppDataDir, packageName);
3241 } else {
3242 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
Amith Yamasani0f3f29b2011-05-09 14:17:14 -07003243 + File.separator + packageName);
Kenny Root9c8625e2011-07-25 09:42:22 -07003244 }
Amith Yamasani0b285492011-04-14 17:35:23 -07003245 }
3246
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003247 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003248 int parseFlags, int scanMode, long currentTime) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003249 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08003250 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
3251 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003252 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003253 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08003254 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
3255 return null;
3256 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 mScanningPath = scanFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3260 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
3261 }
3262
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003263 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264 synchronized (mPackages) {
3265 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003266 Slog.w(TAG, "*************************************************");
3267 Slog.w(TAG, "Core android package being redefined. Skipping.");
3268 Slog.w(TAG, " file=" + mScanningPath);
3269 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003270 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3271 return null;
3272 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274 // Set up information for our fall-back user intent resolution
3275 // activity.
3276 mPlatformPackage = pkg;
3277 pkg.mVersionCode = mSdkVersion;
3278 mAndroidApplication = pkg.applicationInfo;
3279 mResolveActivity.applicationInfo = mAndroidApplication;
3280 mResolveActivity.name = ResolverActivity.class.getName();
3281 mResolveActivity.packageName = mAndroidApplication.packageName;
3282 mResolveActivity.processName = mAndroidApplication.processName;
3283 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
3284 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
Joe Onorato646f46e2010-11-08 15:08:56 -08003285 mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003286 mResolveActivity.exported = true;
3287 mResolveActivity.enabled = true;
3288 mResolveInfo.activityInfo = mResolveActivity;
3289 mResolveInfo.priority = 0;
3290 mResolveInfo.preferredOrder = 0;
3291 mResolveInfo.match = 0;
3292 mResolveComponentName = new ComponentName(
3293 mAndroidApplication.packageName, mResolveActivity.name);
3294 }
3295 }
3296
Kenny Root4dfe6ff2011-02-23 17:00:43 -08003297 if (DEBUG_PACKAGE_SCANNING) {
3298 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
3299 Log.d(TAG, "Scanning package " + pkg.packageName);
3300 }
3301
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003302 if (mPackages.containsKey(pkg.packageName)
3303 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003304 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 + " already installed. Skipping duplicate.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3307 return null;
3308 }
3309
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003310 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003311 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
3312 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 SharedUserSetting suid = null;
3315 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003316
Kenny Root502e9a42011-01-10 13:48:15 -08003317 if (!isSystemApp(pkg)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003318 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08003319 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003320 pkg.mRealPackage = null;
3321 pkg.mAdoptPermissions = null;
3322 }
Kenny Root502e9a42011-01-10 13:48:15 -08003323
Kenny Root447106f2011-03-23 11:00:15 -07003324 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 synchronized (mPackages) {
3326 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07003327 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
3328 if (mTmpSharedLibraries == null ||
3329 mTmpSharedLibraries.length < mSharedLibraries.size()) {
3330 mTmpSharedLibraries = new String[mSharedLibraries.size()];
3331 }
3332 int num = 0;
3333 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
3334 for (int i=0; i<N; i++) {
Kenny Root447106f2011-03-23 11:00:15 -07003335 final String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003336 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003337 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07003339 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003340 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
3341 return null;
3342 }
Dianne Hackborn49237342009-08-27 20:08:01 -07003343 mTmpSharedLibraries[num] = file;
3344 num++;
3345 }
3346 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
3347 for (int i=0; i<N; i++) {
Kenny Root447106f2011-03-23 11:00:15 -07003348 final String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
Dianne Hackborn49237342009-08-27 20:08:01 -07003349 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003350 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07003351 + " desires unavailable shared library "
3352 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
3353 } else {
3354 mTmpSharedLibraries[num] = file;
3355 num++;
3356 }
3357 }
3358 if (num > 0) {
3359 pkg.usesLibraryFiles = new String[num];
3360 System.arraycopy(mTmpSharedLibraries, 0,
3361 pkg.usesLibraryFiles, 0, num);
3362 }
Kenny Root1683afa2011-01-07 14:27:50 -08003363 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003365 if (pkg.mSharedUserId != null) {
Kenny Root447106f2011-03-23 11:00:15 -07003366 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003367 pkg.applicationInfo.flags, true);
3368 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003369 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 + " for shared user failed");
3371 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3372 return null;
3373 }
Kenny Root4dfe6ff2011-02-23 17:00:43 -08003374 if (DEBUG_PACKAGE_SCANNING) {
3375 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
3376 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
3377 + "): packages=" + suid.packages);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003378 }
3379 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003380
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003381 // Check if we are renaming from an original package name.
3382 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003383 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08003384 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003385 // This package may need to be renamed to a previously
3386 // installed name. Let's check on that...
Kenny Root447106f2011-03-23 11:00:15 -07003387 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08003388 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003389 // This package had originally been installed as the
3390 // original name, and we have already taken care of
3391 // transitioning to the new one. Just update the new
3392 // one to continue using the old name.
3393 realName = pkg.mRealPackage;
3394 if (!pkg.packageName.equals(renamed)) {
3395 // Callers into this function may have already taken
3396 // care of renaming the package; only do it here if
3397 // it is not already done.
3398 pkg.setPackageName(renamed);
3399 }
3400
Dianne Hackbornc1552392010-03-03 16:19:01 -08003401 } else {
3402 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
Kenny Root447106f2011-03-23 11:00:15 -07003403 if ((origPackage = mSettings.peekPackageLPr(
Dianne Hackbornc1552392010-03-03 16:19:01 -08003404 pkg.mOriginalPackages.get(i))) != null) {
3405 // We do have the package already installed under its
3406 // original name... should we use it?
Kenny Root447106f2011-03-23 11:00:15 -07003407 if (!verifyPackageUpdateLPr(origPackage, pkg)) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08003408 // New package is not compatible with original.
3409 origPackage = null;
3410 continue;
3411 } else if (origPackage.sharedUser != null) {
3412 // Make sure uid is compatible between packages.
3413 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003414 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003415 + " to " + pkg.packageName + ": old uid "
3416 + origPackage.sharedUser.name
3417 + " differs from " + pkg.mSharedUserId);
3418 origPackage = null;
3419 continue;
3420 }
3421 } else {
3422 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3423 + pkg.packageName + " to old name " + origPackage.name);
3424 }
3425 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003426 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003427 }
3428 }
3429 }
3430
3431 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003432 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003433 + " was transferred to another, but its .apk remains");
3434 }
3435
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003436 // Just create the setting, don't add it yet. For already existing packages
3437 // the PkgSetting exists already and doesn't have to be created.
Kenny Root447106f2011-03-23 11:00:15 -07003438 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07003439 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3440 pkg.applicationInfo.flags, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003441 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003442 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3444 return null;
3445 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003446
3447 if (pkgSetting.origPackage != null) {
3448 // If we are first transitioning from an original package,
3449 // fix up the new package's name now. We need to do this after
3450 // looking up the package under its new name, so getPackageLP
3451 // can take care of fiddling things correctly.
3452 pkg.setPackageName(origPackage.name);
3453
3454 // File a report about this.
3455 String msg = "New package " + pkgSetting.realName
3456 + " renamed to replace old package " + pkgSetting.name;
3457 reportSettingsProblem(Log.WARN, msg);
3458
3459 // Make a note of it.
3460 mTransferedPackages.add(origPackage.name);
3461
3462 // No longer need to retain this.
3463 pkgSetting.origPackage = null;
3464 }
3465
3466 if (realName != null) {
3467 // Make a note of it.
3468 mTransferedPackages.add(pkg.packageName);
3469 }
3470
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003471 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003472 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3473 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 pkg.applicationInfo.uid = pkgSetting.userId;
3476 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003477
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003478 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003479 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003480 return null;
3481 }
3482 // The signature has changed, but this package is in the system
3483 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003484 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 // However... if this package is part of a shared user, but it
3486 // doesn't match the signature of the shared user, let's fail.
3487 // What this means is that you can't change the signatures
3488 // associated with an overall shared user, which doesn't seem all
3489 // that unreasonable.
3490 if (pkgSetting.sharedUser != null) {
Kenny Root447106f2011-03-23 11:00:15 -07003491 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003492 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3493 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3495 return null;
3496 }
3497 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003498 // File a report about this.
3499 String msg = "System package " + pkg.packageName
3500 + " signature changed; retaining data.";
3501 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003502 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003503
The Android Open Source Project10592532009-03-18 17:39:46 -07003504 // Verify that this new package doesn't have any content providers
3505 // that conflict with existing packages. Only do this if the
3506 // package isn't already installed, since we don't want to break
3507 // things that are installed.
3508 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
Kenny Root62cc6902011-02-23 16:49:21 -08003509 final int N = pkg.providers.size();
The Android Open Source Project10592532009-03-18 17:39:46 -07003510 int i;
3511 for (i=0; i<N; i++) {
3512 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003513 if (p.info.authority != null) {
3514 String names[] = p.info.authority.split(";");
3515 for (int j = 0; j < names.length; j++) {
3516 if (mProviders.containsKey(names[j])) {
3517 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003518 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003519 " (in package " + pkg.applicationInfo.packageName +
3520 ") is already used by "
3521 + ((other != null && other.getComponentName() != null)
3522 ? other.getComponentName().getPackageName() : "?"));
3523 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3524 return null;
3525 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003526 }
3527 }
3528 }
3529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530
Kenny Root447106f2011-03-23 11:00:15 -07003531 if (pkg.mAdoptPermissions != null) {
3532 // This package wants to adopt ownership of permissions from
3533 // another package.
3534 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
3535 final String origName = pkg.mAdoptPermissions.get(i);
3536 final PackageSetting orig = mSettings.peekPackageLPr(origName);
3537 if (orig != null) {
3538 if (verifyPackageUpdateLPr(orig, pkg)) {
3539 Slog.i(TAG, "Adopting permissions from " + origName + " to "
3540 + pkg.packageName);
3541 mSettings.transferPermissionsLPw(origName, pkg.packageName);
3542 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003543 }
3544 }
3545 }
3546 }
Kenny Root447106f2011-03-23 11:00:15 -07003547
3548 final String pkgName = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003549
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003550 final long scanFileTime = scanFile.lastModified();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003552 pkg.applicationInfo.processName = fixProcessName(
3553 pkg.applicationInfo.packageName,
3554 pkg.applicationInfo.processName,
3555 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556
3557 File dataPath;
3558 if (mPlatformPackage == pkg) {
3559 // The system package is special.
3560 dataPath = new File (Environment.getDataDirectory(), "system");
3561 pkg.applicationInfo.dataDir = dataPath.getPath();
3562 } else {
3563 // This is a normal package, need to make its data directory.
Amith Yamasani0b285492011-04-14 17:35:23 -07003564 dataPath = getDataPathForPackage(pkg.packageName, 0);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003565
3566 boolean uidError = false;
3567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 if (dataPath.exists()) {
3569 mOutPermissions[1] = 0;
3570 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003571
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003572 // If we have mismatched owners for the data path, we have a problem.
Jeff Brown10e89712011-07-08 18:52:57 -07003573 if (mOutPermissions[1] != pkg.applicationInfo.uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574 boolean recovered = false;
3575 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3576 // If this is a system app, we can at least delete its
3577 // current data so the application will still work.
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003578 int ret = mInstaller.remove(pkgName, 0);
3579 if (ret >= 0) {
3580 // TODO: Kill the processes first
3581 // Remove the data directories for all users
3582 mUserManager.removePackageForAllUsers(pkgName);
3583 // Old data gone!
3584 String msg = "System package " + pkg.packageName
3585 + " has changed from uid: "
3586 + mOutPermissions[1] + " to "
3587 + pkg.applicationInfo.uid + "; old data erased";
3588 reportSettingsProblem(Log.WARN, msg);
3589 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003590
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003591 // And now re-install the app.
3592 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
3593 pkg.applicationInfo.uid);
3594 if (ret == -1) {
3595 // Ack should not happen!
3596 msg = "System package " + pkg.packageName
3597 + " could not have data directory re-created after delete.";
3598 reportSettingsProblem(Log.WARN, msg);
3599 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3600 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003601 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003602 // Create data directories for all users
3603 mUserManager.installPackageForAllUsers(pkgName,
3604 pkg.applicationInfo.uid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003605 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003606 if (!recovered) {
3607 mHasSystemUidErrors = true;
3608 }
3609 }
3610 if (!recovered) {
3611 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3612 + pkg.applicationInfo.uid + "/fs_"
3613 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003614 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003615 String msg = "Package " + pkg.packageName
3616 + " has mismatched uid: "
3617 + mOutPermissions[1] + " on disk, "
3618 + pkg.applicationInfo.uid + " in settings";
Kenny Root447106f2011-03-23 11:00:15 -07003619 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003621 mSettings.mReadMessages.append(msg);
3622 mSettings.mReadMessages.append('\n');
3623 uidError = true;
3624 if (!pkgSetting.uidError) {
3625 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003627 }
3628 }
3629 }
3630 pkg.applicationInfo.dataDir = dataPath.getPath();
3631 } else {
Kenny Root4dfe6ff2011-02-23 17:00:43 -08003632 if (DEBUG_PACKAGE_SCANNING) {
3633 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
3634 Log.v(TAG, "Want this data dir: " + dataPath);
3635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636 //invoke installer to do the actual installation
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003637 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
3638 pkg.applicationInfo.uid);
3639 if (ret < 0) {
3640 // Error from installer
3641 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3642 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003644 // Create data directories for all users
3645 mUserManager.installPackageForAllUsers(pkgName, pkg.applicationInfo.uid);
3646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003647 if (dataPath.exists()) {
3648 pkg.applicationInfo.dataDir = dataPath.getPath();
3649 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003650 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003651 pkg.applicationInfo.dataDir = null;
3652 }
3653 }
Kenny Root85387d72010-08-26 10:13:11 -07003654
3655 /*
3656 * Set the data dir to the default "/data/data/<package name>/lib"
3657 * if we got here without anyone telling us different (e.g., apps
3658 * stored on SD card have their native libraries stored in the ASEC
3659 * container with the APK).
Kenny Root806cc132010-09-12 08:34:19 -07003660 *
3661 * This happens during an upgrade from a package settings file that
3662 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07003663 */
Kenny Rootbd135c12010-10-05 12:26:27 -07003664 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
3665 if (pkgSetting.nativeLibraryPathString == null) {
3666 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
3667 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
3668 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
3669 } else {
3670 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
3671 }
Kenny Root85387d72010-08-26 10:13:11 -07003672 }
3673
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003674 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003675 }
3676
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003677 String path = scanFile.getPath();
3678 /* Note: We don't want to unpack the native binaries for
3679 * system applications, unless they have been updated
3680 * (the binaries are already under /system/lib).
3681 * Also, don't unpack libs for apps on the external card
3682 * since they should have their libraries in the ASEC
3683 * container already.
3684 *
3685 * In other words, we're going to unpack the binaries
3686 * only for non-system apps and system app upgrades.
3687 */
3688 if (pkg.applicationInfo.nativeLibraryDir != null) {
3689 try {
3690 final File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
Kenny Root5832ead2011-08-02 15:47:08 -07003691 final String dataPathString = dataPath.getCanonicalPath();
Kenny Roote68d58a2010-10-18 16:08:54 -07003692
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003693 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
3694 /*
3695 * Upgrading from a previous version of the OS sometimes
3696 * leaves native libraries in the /data/data/<app>/lib
3697 * directory for system apps even when they shouldn't be.
3698 * Recent changes in the JNI library search path
3699 * necessitates we remove those to match previous behavior.
3700 */
3701 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
3702 Log.i(TAG, "removed obsolete native libraries for system package "
3703 + path);
Kenny Root831baa22010-10-05 12:29:25 -07003704 }
Kenny Root5832ead2011-08-02 15:47:08 -07003705 } else if (nativeLibraryDir.getParentFile().getCanonicalPath()
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003706 .equals(dataPathString)) {
3707 /*
Kenny Root66269ea2011-07-12 14:14:01 -07003708 * Make sure the native library dir isn't a symlink to
3709 * something. If it is, ask installd to remove it and create
3710 * a directory so we can copy to it afterwards.
3711 */
3712 boolean isSymLink;
3713 try {
3714 isSymLink = S_ISLNK(Libcore.os.lstat(nativeLibraryDir.getPath()).st_mode);
3715 } catch (ErrnoException e) {
3716 // This shouldn't happen, but we'll fail-safe.
3717 isSymLink = true;
3718 }
3719 if (isSymLink) {
3720 mInstaller.unlinkNativeLibraryDirectory(dataPathString);
3721 }
3722
3723 /*
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003724 * If this is an internal application or our
3725 * nativeLibraryPath points to our data directory, unpack
Kenny Root66269ea2011-07-12 14:14:01 -07003726 * the libraries if necessary.
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003727 */
Kenny Root66269ea2011-07-12 14:14:01 -07003728 NativeLibraryHelper.copyNativeBinariesIfNeededLI(scanFile, nativeLibraryDir);
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003729 } else {
3730 Slog.i(TAG, "Linking native library dir for " + path);
3731 mInstaller.linkNativeLibraryDirectory(dataPathString,
3732 pkg.applicationInfo.nativeLibraryDir);
Kenny Root831baa22010-10-05 12:29:25 -07003733 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003734 } catch (IOException ioe) {
3735 Log.e(TAG, "Unable to get canonical file " + ioe.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003736 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003737 }
3738 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003739
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003740 if ((scanMode&SCAN_NO_DEX) == 0) {
Dianne Hackborn661cd522011-08-22 00:26:20 -07003741 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0)
3742 == DEX_OPT_FAILED) {
Jeff Brown5d6d90f2011-07-11 13:04:53 -07003743 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3744 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003745 }
3746 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 if (mFactoryTest && pkg.requestedPermissions.contains(
3749 android.Manifest.permission.FACTORY_TEST)) {
3750 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3751 }
3752
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003753 // Request the ActivityManager to kill the process(only for existing packages)
3754 // so that we do not end up in a confused state while the user is still using the older
3755 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003756 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003757 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003758 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003759 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003760
Kenny Root447106f2011-03-23 11:00:15 -07003761 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003762 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003763 // We don't expect installation to fail beyond this point,
3764 if ((scanMode&SCAN_MONITOR) != 0) {
3765 mAppDirs.put(pkg.mPath, pkg);
3766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003767 // Add the new setting to mSettings
Kenny Root447106f2011-03-23 11:00:15 -07003768 mSettings.insertPackageSettingLPw(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003769 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003770 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003771 // Make sure we don't accidentally delete its data.
3772 mSettings.mPackagesToBeCleaned.remove(pkgName);
3773
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003774 // Take care of first install / last update times.
3775 if (currentTime != 0) {
3776 if (pkgSetting.firstInstallTime == 0) {
3777 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
3778 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
3779 pkgSetting.lastUpdateTime = currentTime;
3780 }
3781 } else if (pkgSetting.firstInstallTime == 0) {
3782 // We need *something*. Take time time stamp of the file.
3783 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
3784 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
3785 if (scanFileTime != pkgSetting.timeStamp) {
3786 // A package on the system image has changed; consider this
3787 // to be an update.
3788 pkgSetting.lastUpdateTime = scanFileTime;
3789 }
3790 }
3791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003792 int N = pkg.providers.size();
3793 StringBuilder r = null;
3794 int i;
3795 for (i=0; i<N; i++) {
3796 PackageParser.Provider p = pkg.providers.get(i);
3797 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3798 p.info.processName, pkg.applicationInfo.uid);
3799 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3800 p.info.name), p);
3801 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003802 if (p.info.authority != null) {
3803 String names[] = p.info.authority.split(";");
3804 p.info.authority = null;
3805 for (int j = 0; j < names.length; j++) {
3806 if (j == 1 && p.syncable) {
3807 // We only want the first authority for a provider to possibly be
3808 // syncable, so if we already added this provider using a different
3809 // authority clear the syncable flag. We copy the provider before
3810 // changing it because the mProviders object contains a reference
3811 // to a provider that we don't want to change.
3812 // Only do this for the second authority since the resulting provider
3813 // object can be the same for all future authorities for this provider.
3814 p = new PackageParser.Provider(p);
3815 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003816 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003817 if (!mProviders.containsKey(names[j])) {
3818 mProviders.put(names[j], p);
3819 if (p.info.authority == null) {
3820 p.info.authority = names[j];
3821 } else {
3822 p.info.authority = p.info.authority + ";" + names[j];
3823 }
Kenny Root4dfe6ff2011-02-23 17:00:43 -08003824 if (DEBUG_PACKAGE_SCANNING) {
3825 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
3826 Log.d(TAG, "Registered content provider: " + names[j]
3827 + ", className = " + p.info.name + ", isSyncable = "
3828 + p.info.isSyncable);
3829 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003830 } else {
3831 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003832 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003833 " (in package " + pkg.applicationInfo.packageName +
3834 "): name already used by "
3835 + ((other != null && other.getComponentName() != null)
3836 ? other.getComponentName().getPackageName() : "?"));
3837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003838 }
3839 }
3840 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3841 if (r == null) {
3842 r = new StringBuilder(256);
3843 } else {
3844 r.append(' ');
3845 }
3846 r.append(p.info.name);
3847 }
3848 }
3849 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08003850 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003853 N = pkg.services.size();
3854 r = null;
3855 for (i=0; i<N; i++) {
3856 PackageParser.Service s = pkg.services.get(i);
3857 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3858 s.info.processName, pkg.applicationInfo.uid);
3859 mServices.addService(s);
3860 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3861 if (r == null) {
3862 r = new StringBuilder(256);
3863 } else {
3864 r.append(' ');
3865 }
3866 r.append(s.info.name);
3867 }
3868 }
3869 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08003870 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003871 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003873 N = pkg.receivers.size();
3874 r = null;
3875 for (i=0; i<N; i++) {
3876 PackageParser.Activity a = pkg.receivers.get(i);
3877 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3878 a.info.processName, pkg.applicationInfo.uid);
3879 mReceivers.addActivity(a, "receiver");
3880 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3881 if (r == null) {
3882 r = new StringBuilder(256);
3883 } else {
3884 r.append(' ');
3885 }
3886 r.append(a.info.name);
3887 }
3888 }
3889 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08003890 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003893 N = pkg.activities.size();
3894 r = null;
3895 for (i=0; i<N; i++) {
3896 PackageParser.Activity a = pkg.activities.get(i);
3897 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3898 a.info.processName, pkg.applicationInfo.uid);
3899 mActivities.addActivity(a, "activity");
3900 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3901 if (r == null) {
3902 r = new StringBuilder(256);
3903 } else {
3904 r.append(' ');
3905 }
3906 r.append(a.info.name);
3907 }
3908 }
3909 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08003910 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003911 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003913 N = pkg.permissionGroups.size();
3914 r = null;
3915 for (i=0; i<N; i++) {
3916 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3917 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3918 if (cur == null) {
3919 mPermissionGroups.put(pg.info.name, pg);
3920 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3921 if (r == null) {
3922 r = new StringBuilder(256);
3923 } else {
3924 r.append(' ');
3925 }
3926 r.append(pg.info.name);
3927 }
3928 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003929 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003930 + pg.info.packageName + " ignored: original from "
3931 + cur.info.packageName);
3932 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3933 if (r == null) {
3934 r = new StringBuilder(256);
3935 } else {
3936 r.append(' ');
3937 }
3938 r.append("DUP:");
3939 r.append(pg.info.name);
3940 }
3941 }
3942 }
3943 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08003944 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003947 N = pkg.permissions.size();
3948 r = null;
3949 for (i=0; i<N; i++) {
3950 PackageParser.Permission p = pkg.permissions.get(i);
3951 HashMap<String, BasePermission> permissionMap =
3952 p.tree ? mSettings.mPermissionTrees
3953 : mSettings.mPermissions;
3954 p.group = mPermissionGroups.get(p.info.group);
3955 if (p.info.group == null || p.group != null) {
3956 BasePermission bp = permissionMap.get(p.info.name);
3957 if (bp == null) {
3958 bp = new BasePermission(p.info.name, p.info.packageName,
3959 BasePermission.TYPE_NORMAL);
3960 permissionMap.put(p.info.name, bp);
3961 }
3962 if (bp.perm == null) {
3963 if (bp.sourcePackage == null
3964 || bp.sourcePackage.equals(p.info.packageName)) {
3965 BasePermission tree = findPermissionTreeLP(p.info.name);
3966 if (tree == null
3967 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003968 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969 bp.perm = p;
3970 bp.uid = pkg.applicationInfo.uid;
3971 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3972 if (r == null) {
3973 r = new StringBuilder(256);
3974 } else {
3975 r.append(' ');
3976 }
3977 r.append(p.info.name);
3978 }
3979 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003980 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003981 + p.info.packageName + " ignored: base tree "
3982 + tree.name + " is from package "
3983 + tree.sourcePackage);
3984 }
3985 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003986 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 + p.info.packageName + " ignored: original from "
3988 + bp.sourcePackage);
3989 }
3990 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3991 if (r == null) {
3992 r = new StringBuilder(256);
3993 } else {
3994 r.append(' ');
3995 }
3996 r.append("DUP:");
3997 r.append(p.info.name);
3998 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003999 if (bp.perm == p) {
4000 bp.protectionLevel = p.info.protectionLevel;
4001 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004002 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004003 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 + p.info.packageName + " ignored: no group "
4005 + p.group);
4006 }
4007 }
4008 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004009 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 N = pkg.instrumentation.size();
4013 r = null;
4014 for (i=0; i<N; i++) {
4015 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
4016 a.info.packageName = pkg.applicationInfo.packageName;
4017 a.info.sourceDir = pkg.applicationInfo.sourceDir;
4018 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
4019 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07004020 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004021 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4023 if (r == null) {
4024 r = new StringBuilder(256);
4025 } else {
4026 r.append(' ');
4027 }
4028 r.append(a.info.name);
4029 }
4030 }
4031 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004032 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004034
Dianne Hackborn854060af2009-07-09 18:14:31 -07004035 if (pkg.protectedBroadcasts != null) {
4036 N = pkg.protectedBroadcasts.size();
4037 for (i=0; i<N; i++) {
4038 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
4039 }
4040 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004042 pkgSetting.setTimeStamp(scanFileTime);
4043 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 return pkg;
4046 }
4047
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004048 private void killApplication(String pkgName, int uid) {
4049 // Request the ActivityManager to kill the process(only for existing packages)
4050 // so that we do not end up in a confused state while the user is still using the older
4051 // version of the application while the new one gets installed.
4052 IActivityManager am = ActivityManagerNative.getDefault();
4053 if (am != null) {
4054 try {
4055 am.killApplicationWithUid(pkgName, uid);
4056 } catch (RemoteException e) {
4057 }
4058 }
4059 }
4060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004061 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004062 if (DEBUG_INSTALL) {
4063 if (chatty)
4064 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
4065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004066
Kenny Root447106f2011-03-23 11:00:15 -07004067 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004068 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004069 mPackages.remove(pkg.applicationInfo.packageName);
4070 if (pkg.mPath != null) {
4071 mAppDirs.remove(pkg.mPath);
4072 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004074 int N = pkg.providers.size();
4075 StringBuilder r = null;
4076 int i;
4077 for (i=0; i<N; i++) {
4078 PackageParser.Provider p = pkg.providers.get(i);
4079 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
4080 p.info.name));
4081 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004083 /* The is another ContentProvider with this authority when
4084 * this app was installed so this authority is null,
4085 * Ignore it as we don't have to unregister the provider.
4086 */
4087 continue;
4088 }
4089 String names[] = p.info.authority.split(";");
4090 for (int j = 0; j < names.length; j++) {
4091 if (mProviders.get(names[j]) == p) {
4092 mProviders.remove(names[j]);
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004093 if (DEBUG_REMOVE) {
4094 if (chatty)
4095 Log.d(TAG, "Unregistered content provider: " + names[j]
4096 + ", className = " + p.info.name + ", isSyncable = "
4097 + p.info.isSyncable);
4098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004099 }
4100 }
4101 if (chatty) {
4102 if (r == null) {
4103 r = new StringBuilder(256);
4104 } else {
4105 r.append(' ');
4106 }
4107 r.append(p.info.name);
4108 }
4109 }
4110 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004111 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004112 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004114 N = pkg.services.size();
4115 r = null;
4116 for (i=0; i<N; i++) {
4117 PackageParser.Service s = pkg.services.get(i);
4118 mServices.removeService(s);
4119 if (chatty) {
4120 if (r == null) {
4121 r = new StringBuilder(256);
4122 } else {
4123 r.append(' ');
4124 }
4125 r.append(s.info.name);
4126 }
4127 }
4128 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004129 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004130 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132 N = pkg.receivers.size();
4133 r = null;
4134 for (i=0; i<N; i++) {
4135 PackageParser.Activity a = pkg.receivers.get(i);
4136 mReceivers.removeActivity(a, "receiver");
4137 if (chatty) {
4138 if (r == null) {
4139 r = new StringBuilder(256);
4140 } else {
4141 r.append(' ');
4142 }
4143 r.append(a.info.name);
4144 }
4145 }
4146 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004147 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 N = pkg.activities.size();
4151 r = null;
4152 for (i=0; i<N; i++) {
4153 PackageParser.Activity a = pkg.activities.get(i);
4154 mActivities.removeActivity(a, "activity");
4155 if (chatty) {
4156 if (r == null) {
4157 r = new StringBuilder(256);
4158 } else {
4159 r.append(' ');
4160 }
4161 r.append(a.info.name);
4162 }
4163 }
4164 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004165 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004167
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004168 N = pkg.permissions.size();
4169 r = null;
4170 for (i=0; i<N; i++) {
4171 PackageParser.Permission p = pkg.permissions.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004172 BasePermission bp = mSettings.mPermissions.get(p.info.name);
4173 if (bp == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 bp = mSettings.mPermissionTrees.get(p.info.name);
4175 }
4176 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004177 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004178 if (chatty) {
4179 if (r == null) {
4180 r = new StringBuilder(256);
4181 } else {
4182 r.append(' ');
4183 }
4184 r.append(p.info.name);
4185 }
4186 }
4187 }
4188 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004189 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004190 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004192 N = pkg.instrumentation.size();
4193 r = null;
4194 for (i=0; i<N; i++) {
4195 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004196 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004197 if (chatty) {
4198 if (r == null) {
4199 r = new StringBuilder(256);
4200 } else {
4201 r.append(' ');
4202 }
4203 r.append(a.info.name);
4204 }
4205 }
4206 if (r != null) {
Kenny Root9718cf52011-02-23 16:45:26 -08004207 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004208 }
4209 }
4210 }
4211
4212 private static final boolean isPackageFilename(String name) {
4213 return name != null && name.endsWith(".apk");
4214 }
4215
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004216 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
4217 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
4218 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
4219 return true;
4220 }
4221 }
4222 return false;
4223 }
Dianne Hackborne639da72012-02-21 15:11:13 -08004224
4225 static final int UPDATE_PERMISSIONS_ALL = 1<<0;
4226 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
4227 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
4228
Kenny Root447106f2011-03-23 11:00:15 -07004229 private void updatePermissionsLPw(String changingPkg,
Dianne Hackborne639da72012-02-21 15:11:13 -08004230 PackageParser.Package pkgInfo, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004231 // Make sure there are no dangling permission trees.
Kenny Root447106f2011-03-23 11:00:15 -07004232 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004233 while (it.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07004234 final BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004235 if (bp.packageSetting == null) {
4236 // We may not yet have parsed the package, so just see if
4237 // we still know about its settings.
4238 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4239 }
4240 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004241 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004242 + " from package " + bp.sourcePackage);
4243 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004244 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4245 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4246 Slog.i(TAG, "Removing old permission tree: " + bp.name
4247 + " from package " + bp.sourcePackage);
Dianne Hackborne639da72012-02-21 15:11:13 -08004248 flags |= UPDATE_PERMISSIONS_ALL;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004249 it.remove();
4250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004251 }
4252 }
4253
4254 // Make sure all dynamic permissions have been assigned to a package,
4255 // and make sure there are no dangling permissions.
4256 it = mSettings.mPermissions.values().iterator();
4257 while (it.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07004258 final BasePermission bp = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 if (bp.type == BasePermission.TYPE_DYNAMIC) {
4260 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
4261 + bp.name + " pkg=" + bp.sourcePackage
4262 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004263 if (bp.packageSetting == null && bp.pendingInfo != null) {
Kenny Root447106f2011-03-23 11:00:15 -07004264 final BasePermission tree = findPermissionTreeLP(bp.name);
Dianne Hackbornd2509fd2011-09-12 12:29:43 -07004265 if (tree != null && tree.perm != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004266 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004267 bp.perm = new PackageParser.Permission(tree.perm.owner,
4268 new PermissionInfo(bp.pendingInfo));
4269 bp.perm.info.packageName = tree.perm.info.packageName;
4270 bp.perm.info.name = bp.name;
4271 bp.uid = tree.uid;
4272 }
4273 }
4274 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004275 if (bp.packageSetting == null) {
4276 // We may not yet have parsed the package, so just see if
4277 // we still know about its settings.
4278 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4279 }
4280 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004281 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004282 + " from package " + bp.sourcePackage);
4283 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004284 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4285 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4286 Slog.i(TAG, "Removing old permission: " + bp.name
4287 + " from package " + bp.sourcePackage);
Dianne Hackborne639da72012-02-21 15:11:13 -08004288 flags |= UPDATE_PERMISSIONS_ALL;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004289 it.remove();
4290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 }
4292 }
4293
4294 // Now update the permissions for all packages, in particular
4295 // replace the granted permissions of the system packages.
Dianne Hackborne639da72012-02-21 15:11:13 -08004296 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004297 for (PackageParser.Package pkg : mPackages.values()) {
4298 if (pkg != pkgInfo) {
Dianne Hackborne639da72012-02-21 15:11:13 -08004299 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004300 }
4301 }
4302 }
4303
4304 if (pkgInfo != null) {
Dianne Hackborne639da72012-02-21 15:11:13 -08004305 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004306 }
4307 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004308
Kenny Root447106f2011-03-23 11:00:15 -07004309 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
4310 final PackageSetting ps = (PackageSetting) pkg.mExtras;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004311 if (ps == null) {
4312 return;
4313 }
4314 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackborne639da72012-02-21 15:11:13 -08004315 HashSet<String> origPermissions = gp.grantedPermissions;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004316 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004318 if (replace) {
4319 ps.permissionsFixed = false;
4320 if (gp == ps) {
Dianne Hackborne639da72012-02-21 15:11:13 -08004321 origPermissions = new HashSet<String>(gp.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004322 gp.grantedPermissions.clear();
4323 gp.gids = mGlobalGids;
4324 }
4325 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004327 if (gp.gids == null) {
4328 gp.gids = mGlobalGids;
4329 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004331 final int N = pkg.requestedPermissions.size();
4332 for (int i=0; i<N; i++) {
Kenny Root447106f2011-03-23 11:00:15 -07004333 final String name = pkg.requestedPermissions.get(i);
Dianne Hackborne639da72012-02-21 15:11:13 -08004334 //final boolean required = pkg.requestedPermssionsRequired.get(i);
Kenny Root447106f2011-03-23 11:00:15 -07004335 final BasePermission bp = mSettings.mPermissions.get(name);
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004336 if (DEBUG_INSTALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004337 if (gp != ps) {
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004338 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004339 }
4340 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004341 if (bp != null && bp.packageSetting != null) {
4342 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004343 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004344 boolean allowedSig = false;
Dianne Hackborne639da72012-02-21 15:11:13 -08004345 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
4346 if (level == PermissionInfo.PROTECTION_NORMAL
4347 || level == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004348 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07004349 } else if (bp.packageSetting == null) {
4350 // This permission is invalid; skip it.
4351 allowed = false;
Dianne Hackborne639da72012-02-21 15:11:13 -08004352 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
Kenny Root447106f2011-03-23 11:00:15 -07004353 allowed = (compareSignatures(
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07004354 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004355 == PackageManager.SIGNATURE_MATCH)
Kenny Root447106f2011-03-23 11:00:15 -07004356 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004357 == PackageManager.SIGNATURE_MATCH);
Dianne Hackborne639da72012-02-21 15:11:13 -08004358 if (!allowed && (bp.protectionLevel
4359 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
Kenny Root85387d72010-08-26 10:13:11 -07004360 if (isSystemApp(pkg)) {
Dianne Hackborne639da72012-02-21 15:11:13 -08004361 // For updated system applications, a system permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004362 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07004363 if (isUpdatedSystemApp(pkg)) {
Kenny Root447106f2011-03-23 11:00:15 -07004364 final PackageSetting sysPs = mSettings
4365 .getDisabledSystemPkgLPr(pkg.packageName);
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07004366 final GrantedPermissions origGp = sysPs.sharedUser != null
4367 ? sysPs.sharedUser : sysPs;
4368 if (origGp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004369 allowed = true;
4370 } else {
4371 allowed = false;
4372 }
4373 } else {
4374 allowed = true;
4375 }
4376 }
4377 }
Dianne Hackborne639da72012-02-21 15:11:13 -08004378 if (!allowed && (bp.protectionLevel
4379 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
4380 // For development permissions, a development permission
4381 // is granted only if it was already granted.
4382 if (origPermissions.contains(perm)) {
4383 allowed = true;
4384 } else {
4385 allowed = false;
4386 }
4387 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004388 if (allowed) {
4389 allowedSig = true;
4390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004391 } else {
4392 allowed = false;
4393 }
Kenny Root4dfe6ff2011-02-23 17:00:43 -08004394 if (DEBUG_INSTALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004395 if (gp != ps) {
4396 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4397 }
4398 }
4399 if (allowed) {
4400 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4401 && ps.permissionsFixed) {
4402 // If this is an existing, non-system package, then
4403 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004404 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004405 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004406 // Except... if this is a permission that was added
4407 // to the platform (note: need to only do this when
4408 // updating the platform).
4409 final int NP = PackageParser.NEW_PERMISSIONS.length;
4410 for (int ip=0; ip<NP; ip++) {
4411 final PackageParser.NewPermissionInfo npi
4412 = PackageParser.NEW_PERMISSIONS[ip];
4413 if (npi.name.equals(perm)
4414 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4415 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004416 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004417 + pkg.packageName);
4418 break;
4419 }
4420 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004421 }
4422 }
4423 if (allowed) {
4424 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004425 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004426 gp.grantedPermissions.add(perm);
4427 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004428 } else if (!ps.haveGids) {
4429 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004430 }
4431 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004432 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004433 + " to package " + pkg.packageName
4434 + " because it was previously installed without");
4435 }
4436 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004437 if (gp.grantedPermissions.remove(perm)) {
4438 changedPermission = true;
4439 gp.gids = removeInts(gp.gids, bp.gids);
4440 Slog.i(TAG, "Un-granting permission " + perm
4441 + " from package " + pkg.packageName
4442 + " (protectionLevel=" + bp.protectionLevel
4443 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4444 + ")");
4445 } else {
4446 Slog.w(TAG, "Not granting permission " + perm
4447 + " to package " + pkg.packageName
4448 + " (protectionLevel=" + bp.protectionLevel
4449 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4450 + ")");
4451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004452 }
4453 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004454 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004455 + " in package " + pkg.packageName);
4456 }
4457 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004458
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004459 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004460 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4461 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004462 // This is the first that we have heard about this package, so the
4463 // permissions we have now selected are fixed until explicitly
4464 // changed.
4465 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004466 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004467 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004468 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004470 private final class ActivityIntentResolver
4471 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Kenny Root60f7ad82011-03-22 12:49:06 -07004472 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
4473 boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004474 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004475 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004476 }
4477
Kenny Root60f7ad82011-03-22 12:49:06 -07004478 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004479 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004480 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004481 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4482 }
4483
Kenny Root60f7ad82011-03-22 12:49:06 -07004484 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
4485 int flags, ArrayList<PackageParser.Activity> packageActivities) {
Mihai Predaeae850c2009-05-13 10:13:48 +02004486 if (packageActivities == null) {
4487 return null;
4488 }
4489 mFlags = flags;
4490 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
Kenny Root62cc6902011-02-23 16:49:21 -08004491 final int N = packageActivities.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004492 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4493 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004494
4495 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004496 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004497 intentFilters = packageActivities.get(i).intents;
4498 if (intentFilters != null && intentFilters.size() > 0) {
4499 listCut.add(intentFilters);
4500 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004501 }
4502 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4503 }
4504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004505 public final void addActivity(PackageParser.Activity a, String type) {
Kenny Root502e9a42011-01-10 13:48:15 -08004506 final boolean systemApp = isSystemApp(a.info.applicationInfo);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004507 mActivities.put(a.getComponentName(), a);
Kenny Root9718cf52011-02-23 16:45:26 -08004508 if (DEBUG_SHOW_INFO)
4509 Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004510 TAG, " " + type + " " +
4511 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
Kenny Root9718cf52011-02-23 16:45:26 -08004512 if (DEBUG_SHOW_INFO)
4513 Log.v(TAG, " Class=" + a.info.name);
Kenny Root62cc6902011-02-23 16:49:21 -08004514 final int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004515 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004516 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
Kenny Root502e9a42011-01-10 13:48:15 -08004517 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
4518 intent.setPriority(0);
4519 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
4520 + a.className + " with priority > 0, forcing to 0");
4521 }
Kenny Root9718cf52011-02-23 16:45:26 -08004522 if (DEBUG_SHOW_INFO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004523 Log.v(TAG, " IntentFilter:");
4524 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4525 }
4526 if (!intent.debugCheck()) {
4527 Log.w(TAG, "==> For Activity " + a.info.name);
4528 }
4529 addFilter(intent);
4530 }
4531 }
4532
4533 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004534 mActivities.remove(a.getComponentName());
Kenny Root9718cf52011-02-23 16:45:26 -08004535 if (DEBUG_SHOW_INFO) {
4536 Log.v(TAG, " " + type + " "
4537 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
4538 : a.info.name) + ":");
4539 Log.v(TAG, " Class=" + a.info.name);
4540 }
4541 final int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004542 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004543 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
Kenny Root9718cf52011-02-23 16:45:26 -08004544 if (DEBUG_SHOW_INFO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004545 Log.v(TAG, " IntentFilter:");
4546 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4547 }
4548 removeFilter(intent);
4549 }
4550 }
4551
4552 @Override
4553 protected boolean allowFilterResult(
4554 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4555 ActivityInfo filterAi = filter.activity.info;
4556 for (int i=dest.size()-1; i>=0; i--) {
4557 ActivityInfo destAi = dest.get(i).activityInfo;
4558 if (destAi.name == filterAi.name
4559 && destAi.packageName == filterAi.packageName) {
4560 return false;
4561 }
4562 }
4563 return true;
4564 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004566 @Override
Dianne Hackborne7f97212011-02-24 14:40:20 -08004567 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter) {
4568 PackageParser.Package p = filter.activity.owner;
4569 if (p != null) {
4570 PackageSetting ps = (PackageSetting)p.mExtras;
4571 if (ps != null) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07004572 // System apps are never considered stopped for purposes of
4573 // filtering, because there may be no way for the user to
4574 // actually re-launch them.
4575 return ps.stopped && (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0;
Dianne Hackborne7f97212011-02-24 14:40:20 -08004576 }
4577 }
4578 return false;
4579 }
4580
4581 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004582 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4583 return info.activity.owner.packageName;
4584 }
4585
4586 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004587 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4588 int match) {
Kenny Root447106f2011-03-23 11:00:15 -07004589 if (!mSettings.isEnabledLPr(info.activity.info, mFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004590 return null;
4591 }
4592 final PackageParser.Activity activity = info.activity;
4593 if (mSafeMode && (activity.info.applicationInfo.flags
4594 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4595 return null;
4596 }
4597 final ResolveInfo res = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -07004598 res.activityInfo = PackageParser.generateActivityInfo(activity, mFlags,
4599 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004600 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4601 res.filter = info;
4602 }
4603 res.priority = info.getPriority();
4604 res.preferredOrder = activity.owner.mPreferredOrder;
4605 //System.out.println("Result: " + res.activityInfo.className +
4606 // " = " + res.priority);
4607 res.match = match;
4608 res.isDefault = info.hasDefault;
4609 res.labelRes = info.labelRes;
4610 res.nonLocalizedLabel = info.nonLocalizedLabel;
4611 res.icon = info.icon;
Dianne Hackbornd99b2932011-08-18 14:39:58 -07004612 res.system = isSystemApp(res.activityInfo.applicationInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004613 return res;
4614 }
4615
4616 @Override
4617 protected void sortResults(List<ResolveInfo> results) {
4618 Collections.sort(results, mResolvePrioritySorter);
4619 }
4620
4621 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004622 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004623 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004624 out.print(prefix); out.print(
4625 Integer.toHexString(System.identityHashCode(filter.activity)));
4626 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004627 out.print(filter.activity.getComponentShortName());
4628 out.print(" filter ");
4629 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004630 }
4631
4632// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4633// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4634// final List<ResolveInfo> retList = Lists.newArrayList();
4635// while (i.hasNext()) {
4636// final ResolveInfo resolveInfo = i.next();
4637// if (isEnabledLP(resolveInfo.activityInfo)) {
4638// retList.add(resolveInfo);
4639// }
4640// }
4641// return retList;
4642// }
4643
4644 // Keys are String (activity class name), values are Activity.
4645 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4646 = new HashMap<ComponentName, PackageParser.Activity>();
4647 private int mFlags;
4648 }
4649
4650 private final class ServiceIntentResolver
4651 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Kenny Root60f7ad82011-03-22 12:49:06 -07004652 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
4653 boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004654 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004655 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004656 }
4657
Kenny Root60f7ad82011-03-22 12:49:06 -07004658 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004659 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004660 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004661 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4662 }
4663
Kenny Root60f7ad82011-03-22 12:49:06 -07004664 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
4665 int flags, ArrayList<PackageParser.Service> packageServices) {
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07004666 if (packageServices == null) {
4667 return null;
4668 }
4669 mFlags = flags;
4670 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
Kenny Root62cc6902011-02-23 16:49:21 -08004671 final int N = packageServices.size();
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07004672 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4673 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4674
4675 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4676 for (int i = 0; i < N; ++i) {
4677 intentFilters = packageServices.get(i).intents;
4678 if (intentFilters != null && intentFilters.size() > 0) {
4679 listCut.add(intentFilters);
4680 }
4681 }
4682 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4683 }
4684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004685 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004686 mServices.put(s.getComponentName(), s);
Kenny Root9718cf52011-02-23 16:45:26 -08004687 if (DEBUG_SHOW_INFO) {
4688 Log.v(TAG, " "
4689 + (s.info.nonLocalizedLabel != null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004690 ? s.info.nonLocalizedLabel : s.info.name) + ":");
Kenny Root9718cf52011-02-23 16:45:26 -08004691 Log.v(TAG, " Class=" + s.info.name);
4692 }
4693 final int NI = s.intents.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004694 int j;
4695 for (j=0; j<NI; j++) {
4696 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
Kenny Root9718cf52011-02-23 16:45:26 -08004697 if (DEBUG_SHOW_INFO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004698 Log.v(TAG, " IntentFilter:");
4699 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4700 }
4701 if (!intent.debugCheck()) {
4702 Log.w(TAG, "==> For Service " + s.info.name);
4703 }
4704 addFilter(intent);
4705 }
4706 }
4707
4708 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004709 mServices.remove(s.getComponentName());
Kenny Root9718cf52011-02-23 16:45:26 -08004710 if (DEBUG_SHOW_INFO) {
4711 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004712 ? s.info.nonLocalizedLabel : s.info.name) + ":");
Kenny Root9718cf52011-02-23 16:45:26 -08004713 Log.v(TAG, " Class=" + s.info.name);
4714 }
4715 final int NI = s.intents.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004716 int j;
4717 for (j=0; j<NI; j++) {
4718 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
Kenny Root9718cf52011-02-23 16:45:26 -08004719 if (DEBUG_SHOW_INFO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004720 Log.v(TAG, " IntentFilter:");
4721 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4722 }
4723 removeFilter(intent);
4724 }
4725 }
4726
4727 @Override
4728 protected boolean allowFilterResult(
4729 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4730 ServiceInfo filterSi = filter.service.info;
4731 for (int i=dest.size()-1; i>=0; i--) {
4732 ServiceInfo destAi = dest.get(i).serviceInfo;
4733 if (destAi.name == filterSi.name
4734 && destAi.packageName == filterSi.packageName) {
4735 return false;
4736 }
4737 }
4738 return true;
4739 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004741 @Override
Dianne Hackborne7f97212011-02-24 14:40:20 -08004742 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter) {
4743 PackageParser.Package p = filter.service.owner;
4744 if (p != null) {
4745 PackageSetting ps = (PackageSetting)p.mExtras;
4746 if (ps != null) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07004747 // System apps are never considered stopped for purposes of
4748 // filtering, because there may be no way for the user to
4749 // actually re-launch them.
4750 return ps.stopped && (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0;
Dianne Hackborne7f97212011-02-24 14:40:20 -08004751 }
4752 }
4753 return false;
4754 }
4755
4756 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004757 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4758 return info.service.owner.packageName;
4759 }
4760
4761 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004762 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4763 int match) {
Jason parksa3cdaa52011-01-13 14:15:43 -06004764 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
Kenny Root447106f2011-03-23 11:00:15 -07004765 if (!mSettings.isEnabledLPr(info.service.info, mFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004766 return null;
4767 }
4768 final PackageParser.Service service = info.service;
4769 if (mSafeMode && (service.info.applicationInfo.flags
4770 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4771 return null;
4772 }
4773 final ResolveInfo res = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -07004774 res.serviceInfo = PackageParser.generateServiceInfo(service, mFlags,
4775 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004776 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4777 res.filter = filter;
4778 }
4779 res.priority = info.getPriority();
4780 res.preferredOrder = service.owner.mPreferredOrder;
4781 //System.out.println("Result: " + res.activityInfo.className +
4782 // " = " + res.priority);
4783 res.match = match;
4784 res.isDefault = info.hasDefault;
4785 res.labelRes = info.labelRes;
4786 res.nonLocalizedLabel = info.nonLocalizedLabel;
4787 res.icon = info.icon;
Dianne Hackbornd99b2932011-08-18 14:39:58 -07004788 res.system = isSystemApp(res.serviceInfo.applicationInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004789 return res;
4790 }
4791
4792 @Override
4793 protected void sortResults(List<ResolveInfo> results) {
4794 Collections.sort(results, mResolvePrioritySorter);
4795 }
4796
4797 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004798 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004799 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004800 out.print(prefix); out.print(
4801 Integer.toHexString(System.identityHashCode(filter.service)));
4802 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004803 out.print(filter.service.getComponentShortName());
4804 out.print(" filter ");
4805 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004806 }
4807
4808// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4809// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4810// final List<ResolveInfo> retList = Lists.newArrayList();
4811// while (i.hasNext()) {
4812// final ResolveInfo resolveInfo = (ResolveInfo) i;
4813// if (isEnabledLP(resolveInfo.serviceInfo)) {
4814// retList.add(resolveInfo);
4815// }
4816// }
4817// return retList;
4818// }
4819
4820 // Keys are String (activity class name), values are Activity.
4821 private final HashMap<ComponentName, PackageParser.Service> mServices
4822 = new HashMap<ComponentName, PackageParser.Service>();
4823 private int mFlags;
4824 };
4825
4826 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4827 new Comparator<ResolveInfo>() {
4828 public int compare(ResolveInfo r1, ResolveInfo r2) {
4829 int v1 = r1.priority;
4830 int v2 = r2.priority;
4831 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4832 if (v1 != v2) {
4833 return (v1 > v2) ? -1 : 1;
4834 }
4835 v1 = r1.preferredOrder;
4836 v2 = r2.preferredOrder;
4837 if (v1 != v2) {
4838 return (v1 > v2) ? -1 : 1;
4839 }
4840 if (r1.isDefault != r2.isDefault) {
4841 return r1.isDefault ? -1 : 1;
4842 }
4843 v1 = r1.match;
4844 v2 = r2.match;
4845 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
Dianne Hackbornd99b2932011-08-18 14:39:58 -07004846 if (v1 != v2) {
4847 return (v1 > v2) ? -1 : 1;
4848 }
4849 if (r1.system != r2.system) {
4850 return r1.system ? -1 : 1;
4851 }
4852 return 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004853 }
4854 };
4855
4856 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4857 new Comparator<ProviderInfo>() {
4858 public int compare(ProviderInfo p1, ProviderInfo p2) {
4859 final int v1 = p1.initOrder;
4860 final int v2 = p2.initOrder;
4861 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4862 }
4863 };
4864
Kenny Root447106f2011-03-23 11:00:15 -07004865 static final void sendPackageBroadcast(String action, String pkg,
Dianne Hackborne7f97212011-02-24 14:40:20 -08004866 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004867 IActivityManager am = ActivityManagerNative.getDefault();
4868 if (am != null) {
4869 try {
4870 final Intent intent = new Intent(action,
4871 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4872 if (extras != null) {
4873 intent.putExtras(extras);
4874 }
Dianne Hackborne7f97212011-02-24 14:40:20 -08004875 if (targetPkg != null) {
4876 intent.setPackage(targetPkg);
4877 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004878 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Amith Yamasani742a6712011-05-04 14:49:28 -07004879 // TODO: Fix the userId argument
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004880 am.broadcastIntent(null, intent, null, finishedReceiver,
Amith Yamasani742a6712011-05-04 14:49:28 -07004881 0, null, null, null, finishedReceiver != null, false,
4882 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004883 } catch (RemoteException ex) {
4884 }
4885 }
4886 }
Kenny Root300c13a2011-01-18 13:04:40 -08004887
4888 /**
4889 * Check if the external storage media is available. This is true if there
4890 * is a mounted external storage medium or if the external storage is
4891 * emulated.
4892 */
4893 private boolean isExternalMediaAvailable() {
4894 return mMediaMounted || Environment.isExternalStorageEmulated();
4895 }
4896
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004897 public String nextPackageToClean(String lastPackage) {
Kenny Root447106f2011-03-23 11:00:15 -07004898 // writer
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004899 synchronized (mPackages) {
Kenny Root300c13a2011-01-18 13:04:40 -08004900 if (!isExternalMediaAvailable()) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004901 // If the external storage is no longer mounted at this point,
4902 // the caller may not have been able to delete all of this
4903 // packages files and can not delete any more. Bail.
4904 return null;
4905 }
4906 if (lastPackage != null) {
4907 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4908 }
4909 return mSettings.mPackagesToBeCleaned.size() > 0
4910 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4911 }
4912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004913
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004914 void schedulePackageCleaning(String packageName) {
4915 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4916 }
4917
4918 void startCleaningPackages() {
Kenny Root447106f2011-03-23 11:00:15 -07004919 // reader
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004920 synchronized (mPackages) {
Kenny Root300c13a2011-01-18 13:04:40 -08004921 if (!isExternalMediaAvailable()) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004922 return;
4923 }
4924 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4925 return;
4926 }
4927 }
4928 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4929 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4930 IActivityManager am = ActivityManagerNative.getDefault();
4931 if (am != null) {
4932 try {
4933 am.startService(null, intent, null);
4934 } catch (RemoteException e) {
4935 }
4936 }
4937 }
4938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004939 private final class AppDirObserver extends FileObserver {
4940 public AppDirObserver(String path, int mask, boolean isrom) {
4941 super(path, mask);
4942 mRootDir = path;
4943 mIsRom = isrom;
4944 }
4945
4946 public void onEvent(int event, String path) {
4947 String removedPackage = null;
4948 int removedUid = -1;
4949 String addedPackage = null;
4950 int addedUid = -1;
4951
Kenny Root447106f2011-03-23 11:00:15 -07004952 // TODO post a message to the handler to obtain serial ordering
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004953 synchronized (mInstallLock) {
4954 String fullPathStr = null;
4955 File fullPath = null;
4956 if (path != null) {
4957 fullPath = new File(mRootDir, path);
4958 fullPathStr = fullPath.getPath();
4959 }
4960
Kenny Root9718cf52011-02-23 16:45:26 -08004961 if (DEBUG_APP_DIR_OBSERVER)
4962 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004963
4964 if (!isPackageFilename(path)) {
Kenny Root9718cf52011-02-23 16:45:26 -08004965 if (DEBUG_APP_DIR_OBSERVER)
4966 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004967 return;
4968 }
4969
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004970 // Ignore packages that are being installed or
4971 // have just been installed.
4972 if (ignoreCodePath(fullPathStr)) {
4973 return;
4974 }
4975 PackageParser.Package p = null;
Kenny Root447106f2011-03-23 11:00:15 -07004976 // reader
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004977 synchronized (mPackages) {
4978 p = mAppDirs.get(fullPathStr);
4979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004980 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004981 if (p != null) {
4982 removePackageLI(p, true);
4983 removedPackage = p.applicationInfo.packageName;
4984 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004985 }
4986 }
4987
4988 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004989 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004990 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004991 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4992 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004993 PackageParser.PARSE_CHATTY |
4994 PackageParser.PARSE_MUST_BE_APK,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07004995 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
4996 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004997 if (p != null) {
Kenny Root447106f2011-03-23 11:00:15 -07004998 /*
4999 * TODO this seems dangerous as the package may have
5000 * changed since we last acquired the mPackages
5001 * lock.
5002 */
5003 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005004 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07005005 updatePermissionsLPw(p.packageName, p,
Dianne Hackborne639da72012-02-21 15:11:13 -08005006 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005007 }
5008 addedPackage = p.applicationInfo.packageName;
5009 addedUid = p.applicationInfo.uid;
5010 }
5011 }
5012 }
5013
Kenny Root447106f2011-03-23 11:00:15 -07005014 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005015 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07005016 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005017 }
5018 }
5019
5020 if (removedPackage != null) {
5021 Bundle extras = new Bundle(1);
5022 extras.putInt(Intent.EXTRA_UID, removedUid);
5023 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07005024 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
Dianne Hackborne7f97212011-02-24 14:40:20 -08005025 extras, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005026 }
5027 if (addedPackage != null) {
5028 Bundle extras = new Bundle(1);
5029 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07005030 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
Dianne Hackborne7f97212011-02-24 14:40:20 -08005031 extras, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005032 }
5033 }
5034
5035 private final String mRootDir;
5036 private final boolean mIsRom;
5037 }
Jacek Surazski65e13172009-04-28 15:26:38 +02005038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005039 /* Called when a downloaded package installation has been confirmed by the user */
5040 public void installPackage(
5041 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02005042 installPackage(packageURI, observer, flags, null);
5043 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005044
Jacek Surazski65e13172009-04-28 15:26:38 +02005045 /* Called when a downloaded package installation has been confirmed by the user */
5046 public void installPackage(
5047 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
5048 final String installerPackageName) {
Kenny Root5ab21572011-07-27 11:11:19 -07005049 installPackageWithVerification(packageURI, observer, flags, installerPackageName, null,
5050 null);
5051 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005052
Kenny Root5ab21572011-07-27 11:11:19 -07005053 @Override
5054 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
5055 int flags, String installerPackageName, Uri verificationURI,
5056 ManifestDigest manifestDigest) {
5057 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
5058
5059 final int uid = Binder.getCallingUid();
5060
5061 final int filteredFlags;
5062
5063 if (uid == Process.SHELL_UID || uid == 0) {
5064 if (DEBUG_INSTALL) {
5065 Slog.v(TAG, "Install from ADB");
5066 }
5067 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
5068 } else {
5069 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
5070 }
5071
5072 final Message msg = mHandler.obtainMessage(INIT_COPY);
5073 msg.obj = new InstallParams(packageURI, observer, filteredFlags, installerPackageName,
5074 verificationURI, manifestDigest);
5075 mHandler.sendMessage(msg);
5076 }
5077
5078 @Override
Kenny Root05ca4c92011-09-15 10:36:25 -07005079 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
Kenny Root5ab21572011-07-27 11:11:19 -07005080 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
Kenny Root05ca4c92011-09-15 10:36:25 -07005081 final PackageVerificationResponse response = new PackageVerificationResponse(
5082 verificationCode, Binder.getCallingUid());
Kenny Root5ab21572011-07-27 11:11:19 -07005083 msg.arg1 = id;
Kenny Root05ca4c92011-09-15 10:36:25 -07005084 msg.obj = response;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005085 mHandler.sendMessage(msg);
5086 }
5087
Kenny Root05ca4c92011-09-15 10:36:25 -07005088 private ComponentName matchComponentForVerifier(String packageName,
5089 List<ResolveInfo> receivers) {
5090 ActivityInfo targetReceiver = null;
5091
5092 final int NR = receivers.size();
5093 for (int i = 0; i < NR; i++) {
5094 final ResolveInfo info = receivers.get(i);
5095 if (info.activityInfo == null) {
5096 continue;
5097 }
5098
5099 if (packageName.equals(info.activityInfo.packageName)) {
5100 targetReceiver = info.activityInfo;
5101 break;
5102 }
5103 }
5104
5105 if (targetReceiver == null) {
5106 return null;
5107 }
5108
5109 return new ComponentName(targetReceiver.packageName, targetReceiver.name);
5110 }
5111
5112 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
5113 List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
5114 if (pkgInfo.verifiers.length == 0) {
5115 return null;
5116 }
5117
5118 final int N = pkgInfo.verifiers.length;
5119 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
5120 for (int i = 0; i < N; i++) {
5121 final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
5122
5123 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
5124 receivers);
5125 if (comp == null) {
5126 continue;
5127 }
5128
5129 final int verifierUid = getUidForVerifier(verifierInfo);
5130 if (verifierUid == -1) {
5131 continue;
5132 }
5133
5134 if (DEBUG_VERIFY) {
5135 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
5136 + " with the correct signature");
5137 }
5138 sufficientVerifiers.add(comp);
5139 verificationState.addSufficientVerifier(verifierUid);
5140 }
5141
5142 return sufficientVerifiers;
5143 }
5144
5145 private int getUidForVerifier(VerifierInfo verifierInfo) {
5146 synchronized (mPackages) {
5147 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
5148 if (pkg == null) {
5149 return -1;
5150 } else if (pkg.mSignatures.length != 1) {
5151 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
5152 + " has more than one signature; ignoring");
5153 return -1;
5154 }
5155
5156 /*
5157 * If the public key of the package's signature does not match
5158 * our expected public key, then this is a different package and
5159 * we should skip.
5160 */
5161
5162 final byte[] expectedPublicKey;
5163 try {
5164 final Signature verifierSig = pkg.mSignatures[0];
5165 final PublicKey publicKey = verifierSig.getPublicKey();
5166 expectedPublicKey = publicKey.getEncoded();
5167 } catch (CertificateException e) {
5168 return -1;
5169 }
5170
5171 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
5172
5173 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
5174 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
5175 + " does not have the expected public key; ignoring");
5176 return -1;
5177 }
5178
5179 return pkg.applicationInfo.uid;
5180 }
5181 }
5182
Christopher Tate1bb69062010-02-19 17:02:12 -08005183 public void finishPackageInstall(int token) {
Kenny Root461ff1f2011-08-09 09:43:03 -07005184 enforceSystemOrRoot("Only the system is allowed to finish installs");
5185
5186 if (DEBUG_INSTALL) {
5187 Slog.v(TAG, "BM finishing package install for " + token);
5188 }
5189
5190 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
Christopher Tate1bb69062010-02-19 17:02:12 -08005191 mHandler.sendMessage(msg);
5192 }
5193
Kenny Root5ab21572011-07-27 11:11:19 -07005194 /**
5195 * Get the verification agent timeout.
5196 *
5197 * @return verification timeout in milliseconds
5198 */
5199 private long getVerificationTimeout() {
5200 return android.provider.Settings.Secure.getLong(mContext.getContentResolver(),
5201 android.provider.Settings.Secure.PACKAGE_VERIFIER_TIMEOUT,
5202 DEFAULT_VERIFICATION_TIMEOUT);
5203 }
5204
5205 /**
5206 * Check whether or not package verification has been enabled.
5207 *
5208 * @return true if verification should be performed
5209 */
5210 private boolean isVerificationEnabled() {
5211 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
5212 android.provider.Settings.Secure.PACKAGE_VERIFIER_ENABLE,
5213 DEFAULT_VERIFY_ENABLE ? 1 : 0) == 1 ? true : false;
5214 }
5215
Kenny Rootf03b45f2011-02-23 17:25:45 -08005216 public void setInstallerPackageName(String targetPackage, String installerPackageName) {
Dianne Hackborn880119b2010-11-18 22:26:40 -08005217 final int uid = Binder.getCallingUid();
Kenny Root447106f2011-03-23 11:00:15 -07005218 // writer
Dianne Hackborn880119b2010-11-18 22:26:40 -08005219 synchronized (mPackages) {
5220 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
5221 if (targetPackageSetting == null) {
5222 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
5223 }
5224
5225 PackageSetting installerPackageSetting;
5226 if (installerPackageName != null) {
5227 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
5228 if (installerPackageSetting == null) {
5229 throw new IllegalArgumentException("Unknown installer package: "
5230 + installerPackageName);
5231 }
5232 } else {
5233 installerPackageSetting = null;
5234 }
5235
5236 Signature[] callerSignature;
Kenny Root447106f2011-03-23 11:00:15 -07005237 Object obj = mSettings.getUserIdLPr(uid);
Dianne Hackborn880119b2010-11-18 22:26:40 -08005238 if (obj != null) {
5239 if (obj instanceof SharedUserSetting) {
5240 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
5241 } else if (obj instanceof PackageSetting) {
5242 callerSignature = ((PackageSetting)obj).signatures.mSignatures;
5243 } else {
5244 throw new SecurityException("Bad object " + obj + " for uid " + uid);
5245 }
5246 } else {
5247 throw new SecurityException("Unknown calling uid " + uid);
5248 }
5249
5250 // Verify: can't set installerPackageName to a package that is
5251 // not signed with the same cert as the caller.
5252 if (installerPackageSetting != null) {
Kenny Root447106f2011-03-23 11:00:15 -07005253 if (compareSignatures(callerSignature,
Dianne Hackborn880119b2010-11-18 22:26:40 -08005254 installerPackageSetting.signatures.mSignatures)
5255 != PackageManager.SIGNATURE_MATCH) {
5256 throw new SecurityException(
5257 "Caller does not have same cert as new installer package "
5258 + installerPackageName);
5259 }
5260 }
5261
5262 // Verify: if target already has an installer package, it must
5263 // be signed with the same cert as the caller.
5264 if (targetPackageSetting.installerPackageName != null) {
5265 PackageSetting setting = mSettings.mPackages.get(
5266 targetPackageSetting.installerPackageName);
5267 // If the currently set package isn't valid, then it's always
5268 // okay to change it.
5269 if (setting != null) {
Kenny Root447106f2011-03-23 11:00:15 -07005270 if (compareSignatures(callerSignature,
Dianne Hackborn880119b2010-11-18 22:26:40 -08005271 setting.signatures.mSignatures)
5272 != PackageManager.SIGNATURE_MATCH) {
5273 throw new SecurityException(
5274 "Caller does not have same cert as old installer package "
5275 + targetPackageSetting.installerPackageName);
5276 }
5277 }
5278 }
5279
5280 // Okay!
5281 targetPackageSetting.installerPackageName = installerPackageName;
5282 scheduleWriteSettingsLocked();
5283 }
5284 }
5285
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005286 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005287 // Queue up an async operation since the package installation may take a little while.
5288 mHandler.post(new Runnable() {
5289 public void run() {
5290 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005291 // Result object to be returned
5292 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005293 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005294 res.uid = -1;
5295 res.pkg = null;
5296 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005297 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07005298 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005299 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005300 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005301 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005302 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005303 }
Christopher Tate1bb69062010-02-19 17:02:12 -08005304
5305 // A restore should be performed at this point if (a) the install
5306 // succeeded, (b) the operation is not an update, and (c) the new
5307 // package has a backupAgent defined.
5308 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08005309 boolean doRestore = (!update
5310 && res.pkg != null
5311 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08005312
5313 // Set up the post-install work request bookkeeping. This will be used
5314 // and cleaned up by the post-install event handling regardless of whether
5315 // there's a restore pass performed. Token values are >= 1.
5316 int token;
5317 if (mNextInstallToken < 0) mNextInstallToken = 1;
5318 token = mNextInstallToken++;
5319
5320 PostInstallData data = new PostInstallData(args, res);
5321 mRunningInstalls.put(token, data);
5322 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
5323
5324 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
5325 // Pass responsibility to the Backup Manager. It will perform a
5326 // restore if appropriate, then pass responsibility back to the
5327 // Package Manager to run the post-install observer callbacks
5328 // and broadcasts.
5329 IBackupManager bm = IBackupManager.Stub.asInterface(
5330 ServiceManager.getService(Context.BACKUP_SERVICE));
5331 if (bm != null) {
5332 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
5333 + " to BM for possible restore");
5334 try {
5335 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
5336 } catch (RemoteException e) {
5337 // can't happen; the backup manager is local
5338 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005339 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08005340 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005341 }
Christopher Tate1bb69062010-02-19 17:02:12 -08005342 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005343 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08005344 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005345 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005346 }
Christopher Tate1bb69062010-02-19 17:02:12 -08005347
5348 if (!doRestore) {
5349 // No restore possible, or the Backup Manager was mysteriously not
5350 // available -- just fire the post-install work request directly.
5351 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
5352 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
5353 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005355 }
5356 });
5357 }
5358
Kenny Root5ab21572011-07-27 11:11:19 -07005359 private abstract class HandlerParams {
5360 private static final int MAX_RETRIES = 4;
5361
5362 /**
5363 * Number of times startCopy() has been attempted and had a non-fatal
5364 * error.
5365 */
5366 private int mRetries = 0;
5367
Dianne Hackborn7d608422011-08-07 16:24:18 -07005368 final boolean startCopy() {
5369 boolean res;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005370 try {
Kenny Root5ab21572011-07-27 11:11:19 -07005371 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy");
5372
5373 if (++mRetries > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005374 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005375 mHandler.sendEmptyMessage(MCS_GIVE_UP);
5376 handleServiceError();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005377 return false;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005378 } else {
5379 handleStartCopy();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005380 res = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005381 }
5382 } catch (RemoteException e) {
Kenny Root5ab21572011-07-27 11:11:19 -07005383 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005384 mHandler.sendEmptyMessage(MCS_RECONNECT);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005385 res = false;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005386 }
5387 handleReturnCode();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005388 return res;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005389 }
5390
5391 final void serviceError() {
Kenny Root5ab21572011-07-27 11:11:19 -07005392 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005393 handleServiceError();
5394 handleReturnCode();
5395 }
Kenny Root5ab21572011-07-27 11:11:19 -07005396
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005397 abstract void handleStartCopy() throws RemoteException;
5398 abstract void handleServiceError();
5399 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005400 }
5401
Kenny Root366949c2011-01-14 17:18:14 -08005402 class MeasureParams extends HandlerParams {
5403 private final PackageStats mStats;
5404 private boolean mSuccess;
5405
5406 private final IPackageStatsObserver mObserver;
5407
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07005408 public MeasureParams(PackageStats stats, boolean success, IPackageStatsObserver observer) {
Kenny Root366949c2011-01-14 17:18:14 -08005409 mObserver = observer;
5410 mStats = stats;
5411 mSuccess = success;
5412 }
5413
5414 @Override
5415 void handleStartCopy() throws RemoteException {
5416 final boolean mounted;
5417
5418 if (Environment.isExternalStorageEmulated()) {
5419 mounted = true;
5420 } else {
5421 final String status = Environment.getExternalStorageState();
5422
5423 mounted = status.equals(Environment.MEDIA_MOUNTED)
5424 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
5425 }
5426
5427 if (mounted) {
5428 final File externalCacheDir = Environment
5429 .getExternalStorageAppCacheDirectory(mStats.packageName);
5430 final long externalCacheSize = mContainerService
5431 .calculateDirectorySize(externalCacheDir.getPath());
5432 mStats.externalCacheSize = externalCacheSize;
5433
5434 final File externalDataDir = Environment
5435 .getExternalStorageAppDataDirectory(mStats.packageName);
5436 long externalDataSize = mContainerService.calculateDirectorySize(externalDataDir
5437 .getPath());
5438
5439 if (externalCacheDir.getParentFile().equals(externalDataDir)) {
5440 externalDataSize -= externalCacheSize;
5441 }
5442 mStats.externalDataSize = externalDataSize;
5443
5444 final File externalMediaDir = Environment
5445 .getExternalStorageAppMediaDirectory(mStats.packageName);
5446 mStats.externalMediaSize = mContainerService
Kenny Rootc7624d92011-02-23 16:25:25 -08005447 .calculateDirectorySize(externalMediaDir.getPath());
Kenny Rootbcd6c962011-01-17 11:21:49 -08005448
5449 final File externalObbDir = Environment
5450 .getExternalStorageAppObbDirectory(mStats.packageName);
5451 mStats.externalObbSize = mContainerService.calculateDirectorySize(externalObbDir
5452 .getPath());
Kenny Root366949c2011-01-14 17:18:14 -08005453 }
5454 }
5455
5456 @Override
5457 void handleReturnCode() {
5458 if (mObserver != null) {
5459 try {
5460 mObserver.onGetStatsCompleted(mStats, mSuccess);
5461 } catch (RemoteException e) {
5462 Slog.i(TAG, "Observer no longer exists.");
5463 }
5464 }
5465 }
5466
5467 @Override
5468 void handleServiceError() {
5469 Slog.e(TAG, "Could not measure application " + mStats.packageName
5470 + " external storage");
5471 }
5472 }
5473
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005474 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005475 final IPackageInstallObserver observer;
5476 int flags;
5477 final Uri packageURI;
5478 final String installerPackageName;
Kenny Root5ab21572011-07-27 11:11:19 -07005479 final Uri verificationURI;
5480 final ManifestDigest manifestDigest;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005481 private InstallArgs mArgs;
5482 private int mRet;
Kenny Root5ab21572011-07-27 11:11:19 -07005483
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005484 InstallParams(Uri packageURI,
5485 IPackageInstallObserver observer, int flags,
Kenny Root5ab21572011-07-27 11:11:19 -07005486 String installerPackageName, Uri verificationURI, ManifestDigest manifestDigest) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005487 this.packageURI = packageURI;
5488 this.flags = flags;
5489 this.observer = observer;
5490 this.installerPackageName = installerPackageName;
Kenny Root5ab21572011-07-27 11:11:19 -07005491 this.verificationURI = verificationURI;
5492 this.manifestDigest = manifestDigest;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005493 }
5494
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08005495 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
5496 String packageName = pkgLite.packageName;
5497 int installLocation = pkgLite.installLocation;
5498 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Kenny Root447106f2011-03-23 11:00:15 -07005499 // reader
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08005500 synchronized (mPackages) {
5501 PackageParser.Package pkg = mPackages.get(packageName);
5502 if (pkg != null) {
5503 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5504 // Check for updated system application.
5505 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5506 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005507 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08005508 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
5509 }
5510 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
5511 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08005512 if (onSd) {
5513 // Install flag overrides everything.
5514 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
5515 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07005516 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08005517 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
5518 // Application explicitly specified internal.
5519 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
5520 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
5521 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07005522 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08005523 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07005524 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07005525 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
5526 }
5527 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08005528 }
5529 }
5530 } else {
5531 // Invalid install. Return error code
5532 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
5533 }
5534 }
5535 }
5536 // All the special cases have been taken care of.
5537 // Return result based on recommended install location.
5538 if (onSd) {
5539 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
5540 }
5541 return pkgLite.recommendedInstallLocation;
5542 }
5543
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005544 /*
5545 * Invoke remote method to get package information and install
5546 * location values. Override install location based on default
5547 * policy if needed and then create install arguments based
5548 * on the install location.
5549 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005550 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08005551 int ret = PackageManager.INSTALL_SUCCEEDED;
Kenny Root05ca4c92011-09-15 10:36:25 -07005552 final boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5553 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
5554 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
5555 PackageInfoLite pkgLite = null;
5556
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07005557 if (onInt && onSd) {
5558 // Check if both bits are set.
5559 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
5560 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5561 } else if (fwdLocked && onSd) {
5562 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005563 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08005564 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005565 } else {
Kenny Root62e1b4e2011-03-14 17:13:39 -07005566 final long lowThreshold;
5567
5568 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
5569 .getService(DeviceStorageMonitorService.SERVICE);
5570 if (dsm == null) {
5571 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
5572 lowThreshold = 0L;
5573 } else {
5574 lowThreshold = dsm.getMemoryLowThreshold();
5575 }
5576
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005577 // Remote call to find out default install location
Kenny Root11128572010-10-11 10:51:32 -07005578 try {
5579 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5580 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root62e1b4e2011-03-14 17:13:39 -07005581 pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags,
5582 lowThreshold);
Kenny Root11128572010-10-11 10:51:32 -07005583 } finally {
5584 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5585 }
5586
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005587 int loc = pkgLite.recommendedInstallLocation;
Kenny Root1ebd74a2011-08-03 15:09:44 -07005588 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08005589 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Kenny Root1ebd74a2011-08-03 15:09:44 -07005590 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08005591 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
Kenny Root1ebd74a2011-08-03 15:09:44 -07005592 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005593 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5594 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
5595 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Kenny Root1ebd74a2011-08-03 15:09:44 -07005596 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
5597 ret = PackageManager.INSTALL_FAILED_INVALID_URI;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005598 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
Kenny Root1ebd74a2011-08-03 15:09:44 -07005599 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005600 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005601 // Override with defaults if needed.
5602 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07005603 if (!onSd && !onInt) {
5604 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005605 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
5606 // Set the flag to install on external media.
5607 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07005608 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005609 } else {
5610 // Make sure the flag for installing on external
5611 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07005612 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005613 flags &= ~PackageManager.INSTALL_EXTERNAL;
5614 }
5615 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005616 }
5617 }
Kenny Root5ab21572011-07-27 11:11:19 -07005618
5619 final InstallArgs args = createInstallArgs(this);
Kenny Root05ca4c92011-09-15 10:36:25 -07005620 mArgs = args;
5621
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005622 if (ret == PackageManager.INSTALL_SUCCEEDED) {
Kenny Root5ab21572011-07-27 11:11:19 -07005623 /*
5624 * Determine if we have any installed package verifiers. If we
5625 * do, then we'll defer to them to verify the packages.
5626 */
Kenny Root05ca4c92011-09-15 10:36:25 -07005627 final int requiredUid = mRequiredVerifierPackage == null ? -1
5628 : getPackageUid(mRequiredVerifierPackage);
5629 if (requiredUid != -1 && isVerificationEnabled()) {
Kenny Roota503a0f2011-10-03 14:45:28 -07005630 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
5631 verification.setDataAndType(packageURI, PACKAGE_MIME_TYPE);
Kenny Root05ca4c92011-09-15 10:36:25 -07005632 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root5ab21572011-07-27 11:11:19 -07005633
Kenny Root05ca4c92011-09-15 10:36:25 -07005634 final List<ResolveInfo> receivers = queryIntentReceivers(verification, null,
5635 PackageManager.GET_DISABLED_COMPONENTS);
5636
5637 if (DEBUG_VERIFY) {
Kenny Root5ab21572011-07-27 11:11:19 -07005638 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
Kenny Root05ca4c92011-09-15 10:36:25 -07005639 + verification.toString() + " with " + pkgLite.verifiers.length
5640 + " optional verifiers");
Kenny Root5ab21572011-07-27 11:11:19 -07005641 }
5642
5643 final int verificationId = mPendingVerificationToken++;
5644
5645 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
5646
5647 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
5648 installerPackageName);
5649
5650 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
5651
5652 if (verificationURI != null) {
5653 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
5654 verificationURI);
5655 }
5656
Kenny Root05ca4c92011-09-15 10:36:25 -07005657 final PackageVerificationState verificationState = new PackageVerificationState(
5658 requiredUid, args);
5659
5660 mPendingVerification.append(verificationId, verificationState);
5661
5662 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
5663 receivers, verificationState);
Kenny Root5ab21572011-07-27 11:11:19 -07005664
5665 /*
Kenny Root05ca4c92011-09-15 10:36:25 -07005666 * If any sufficient verifiers were listed in the package
5667 * manifest, attempt to ask them.
Kenny Root5ab21572011-07-27 11:11:19 -07005668 */
Kenny Root05ca4c92011-09-15 10:36:25 -07005669 if (sufficientVerifiers != null) {
5670 final int N = sufficientVerifiers.size();
5671 if (N == 0) {
5672 Slog.i(TAG, "Additional verifiers required, but none installed.");
5673 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
5674 } else {
5675 for (int i = 0; i < N; i++) {
5676 final ComponentName verifierComponent = sufficientVerifiers.get(i);
5677
5678 final Intent sufficientIntent = new Intent(verification);
5679 sufficientIntent.setComponent(verifierComponent);
5680
5681 mContext.sendBroadcast(sufficientIntent);
5682 }
5683 }
5684 }
5685
5686 final ComponentName requiredVerifierComponent = matchComponentForVerifier(
5687 mRequiredVerifierPackage, receivers);
5688 if (ret == PackageManager.INSTALL_SUCCEEDED
5689 && mRequiredVerifierPackage != null) {
5690 /*
5691 * Send the intent to the required verification agent,
5692 * but only start the verification timeout after the
5693 * target BroadcastReceivers have run.
5694 */
5695 verification.setComponent(requiredVerifierComponent);
5696 mContext.sendOrderedBroadcast(verification,
5697 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
5698 new BroadcastReceiver() {
5699 @Override
5700 public void onReceive(Context context, Intent intent) {
5701 final Message msg = mHandler
5702 .obtainMessage(CHECK_PENDING_VERIFICATION);
5703 msg.arg1 = verificationId;
5704 mHandler.sendMessageDelayed(msg, getVerificationTimeout());
5705 }
5706 }, null, 0, null, null);
5707
5708 /*
5709 * We don't want the copy to proceed until verification
5710 * succeeds, so null out this field.
5711 */
5712 mArgs = null;
5713 }
Kenny Root5ab21572011-07-27 11:11:19 -07005714 } else {
Kenny Root05ca4c92011-09-15 10:36:25 -07005715 /*
5716 * No package verification is enabled, so immediately start
5717 * the remote call to initiate copy using temporary file.
5718 */
Kenny Root5ab21572011-07-27 11:11:19 -07005719 ret = args.copyApk(mContainerService, true);
5720 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005721 }
Kenny Root5ab21572011-07-27 11:11:19 -07005722
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005723 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005724 }
5725
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005726 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005727 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07005728 // If mArgs is null, then MCS couldn't be reached. When it
5729 // reconnects, it will try again to install. At that point, this
5730 // will succeed.
5731 if (mArgs != null) {
5732 processPendingInstall(mArgs, mRet);
5733 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005734 }
5735
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005736 @Override
5737 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005738 mArgs = createInstallArgs(this);
5739 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005740 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005741 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005742
5743 /*
5744 * Utility class used in movePackage api.
5745 * srcArgs and targetArgs are not set for invalid flags and make
5746 * sure to do null checks when invoking methods on them.
5747 * We probably want to return ErrorPrams for both failed installs
5748 * and moves.
5749 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005750 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005751 final IPackageMoveObserver observer;
5752 final int flags;
5753 final String packageName;
5754 final InstallArgs srcArgs;
5755 final InstallArgs targetArgs;
5756 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07005757
5758 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
5759 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005760 this.srcArgs = srcArgs;
5761 this.observer = observer;
5762 this.flags = flags;
5763 this.packageName = packageName;
5764 if (srcArgs != null) {
5765 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07005766 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005767 } else {
5768 targetArgs = null;
5769 }
5770 }
5771
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005772 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005773 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5774 // Check for storage space on target medium
5775 if (!targetArgs.checkFreeStorage(mContainerService)) {
5776 Log.w(TAG, "Insufficient storage to install");
5777 return;
5778 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005779 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005780 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005781 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005782 if (DEBUG_SD_INSTALL) {
5783 StringBuilder builder = new StringBuilder();
5784 if (srcArgs != null) {
5785 builder.append("src: ");
5786 builder.append(srcArgs.getCodePath());
5787 }
5788 if (targetArgs != null) {
5789 builder.append(" target : ");
5790 builder.append(targetArgs.getCodePath());
5791 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005792 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005793 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005794 }
5795
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005796 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005797 void handleReturnCode() {
5798 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005799 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
5800 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
5801 currentStatus = PackageManager.MOVE_SUCCEEDED;
5802 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
5803 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
5804 }
5805 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005806 }
5807
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005808 @Override
5809 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005810 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005811 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005812 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005813
5814 private InstallArgs createInstallArgs(InstallParams params) {
5815 if (installOnSd(params.flags)) {
5816 return new SdInstallArgs(params);
5817 } else {
5818 return new FileInstallArgs(params);
5819 }
5820 }
5821
Kenny Root85387d72010-08-26 10:13:11 -07005822 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
5823 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005824 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07005825 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005826 } else {
Kenny Root85387d72010-08-26 10:13:11 -07005827 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005828 }
5829 }
5830
Kenny Root85387d72010-08-26 10:13:11 -07005831 // Used by package mover
5832 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005833 if (installOnSd(flags)) {
5834 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
5835 return new SdInstallArgs(packageURI, cid);
5836 } else {
Kenny Root85387d72010-08-26 10:13:11 -07005837 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005838 }
5839 }
5840
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005841 static abstract class InstallArgs {
5842 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005843 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005844 final int flags;
5845 final Uri packageURI;
5846 final String installerPackageName;
Kenny Root5ab21572011-07-27 11:11:19 -07005847 final ManifestDigest manifestDigest;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005848
Kenny Root5ab21572011-07-27 11:11:19 -07005849 InstallArgs(Uri packageURI, IPackageInstallObserver observer, int flags,
5850 String installerPackageName, ManifestDigest manifestDigest) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005851 this.packageURI = packageURI;
5852 this.flags = flags;
5853 this.observer = observer;
5854 this.installerPackageName = installerPackageName;
Kenny Root5ab21572011-07-27 11:11:19 -07005855 this.manifestDigest = manifestDigest;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005856 }
5857
5858 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005859 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005860 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005861 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005862 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005863 abstract String getCodePath();
5864 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07005865 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005866 // Need installer lock especially for dex file removal.
5867 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005868 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005869 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005870 }
5871
5872 class FileInstallArgs extends InstallArgs {
5873 File installDir;
5874 String codeFileName;
5875 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07005876 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005877 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005878
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005879 FileInstallArgs(InstallParams params) {
Kenny Root5ab21572011-07-27 11:11:19 -07005880 super(params.packageURI, params.observer, params.flags, params.installerPackageName,
5881 params.manifestDigest);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005882 }
5883
Kenny Root85387d72010-08-26 10:13:11 -07005884 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Kenny Root5ab21572011-07-27 11:11:19 -07005885 super(null, null, 0, null, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005886 File codeFile = new File(fullCodePath);
5887 installDir = codeFile.getParentFile();
5888 codeFileName = fullCodePath;
5889 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07005890 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005891 }
5892
Kenny Root85387d72010-08-26 10:13:11 -07005893 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Kenny Root5ab21572011-07-27 11:11:19 -07005894 super(packageURI, null, 0, null, null);
Kenny Root85387d72010-08-26 10:13:11 -07005895 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005896 String apkName = getNextCodePath(null, pkgName, ".apk");
5897 codeFileName = new File(installDir, apkName + ".apk").getPath();
5898 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07005899 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005900 }
5901
Kenny Root11128572010-10-11 10:51:32 -07005902 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
Kenny Root62e1b4e2011-03-14 17:13:39 -07005903 final long lowThreshold;
5904
5905 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
5906 .getService(DeviceStorageMonitorService.SERVICE);
5907 if (dsm == null) {
5908 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
5909 lowThreshold = 0L;
5910 } else {
5911 if (dsm.isMemoryLow()) {
5912 Log.w(TAG, "Memory is reported as being too low; aborting package install");
5913 return false;
5914 }
5915
5916 lowThreshold = dsm.getMemoryLowThreshold();
5917 }
5918
Kenny Root11128572010-10-11 10:51:32 -07005919 try {
5920 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5921 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root62e1b4e2011-03-14 17:13:39 -07005922 return imcs.checkInternalFreeStorage(packageURI, lowThreshold);
Kenny Root11128572010-10-11 10:51:32 -07005923 } finally {
5924 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5925 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005926 }
5927
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005928 String getCodePath() {
5929 return codeFileName;
5930 }
5931
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005932 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07005933 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005934 codeFileName = createTempPackageFile(installDir).getPath();
5935 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005936 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005937 }
5938
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005939 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005940 if (temp) {
5941 // Generate temp file name
5942 createCopyFile();
5943 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005944 // Get a ParcelFileDescriptor to write to the output file
5945 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005946 if (!created) {
5947 try {
5948 codeFile.createNewFile();
5949 // Set permissions
5950 if (!setPermissions()) {
5951 // Failed setting permissions.
5952 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5953 }
5954 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005955 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005956 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5957 }
5958 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005959 ParcelFileDescriptor out = null;
5960 try {
Kenny Root85387d72010-08-26 10:13:11 -07005961 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005962 } catch (FileNotFoundException e) {
Kenny Rootf5121a92011-08-10 16:23:32 -07005963 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005964 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5965 }
5966 // Copy the resource now
5967 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5968 try {
Kenny Root11128572010-10-11 10:51:32 -07005969 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5970 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Rootf5121a92011-08-10 16:23:32 -07005971 ret = imcs.copyResource(packageURI, out);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005972 } finally {
5973 try { if (out != null) out.close(); } catch (IOException e) {}
Kenny Root11128572010-10-11 10:51:32 -07005974 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005975 }
Kenny Root85387d72010-08-26 10:13:11 -07005976
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005977 return ret;
5978 }
5979
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005980 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005981 if (status != PackageManager.INSTALL_SUCCEEDED) {
5982 cleanUp();
5983 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005984 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005985 }
5986
5987 boolean doRename(int status, final String pkgName, String oldCodePath) {
5988 if (status != PackageManager.INSTALL_SUCCEEDED) {
5989 cleanUp();
5990 return false;
5991 } else {
5992 // Rename based on packageName
5993 File codeFile = new File(getCodePath());
5994 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5995 File desFile = new File(installDir, apkName + ".apk");
5996 if (!codeFile.renameTo(desFile)) {
5997 return false;
5998 }
5999 // Reset paths since the file has been renamed.
6000 codeFileName = desFile.getPath();
6001 resourceFileName = getResourcePathFromCodePath();
6002 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006003 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006004 // Failed setting permissions.
6005 return false;
6006 }
6007 return true;
6008 }
6009 }
6010
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006011 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006012 if (status != PackageManager.INSTALL_SUCCEEDED) {
6013 cleanUp();
6014 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006015 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006016 }
6017
6018 String getResourcePath() {
6019 return resourceFileName;
6020 }
6021
6022 String getResourcePathFromCodePath() {
6023 String codePath = getCodePath();
6024 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
6025 String apkNameOnly = getApkName(codePath);
6026 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
6027 } else {
6028 return codePath;
6029 }
6030 }
6031
Kenny Root85387d72010-08-26 10:13:11 -07006032 @Override
6033 String getNativeLibraryPath() {
6034 return libraryPath;
6035 }
6036
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006037 private boolean cleanUp() {
6038 boolean ret = true;
6039 String sourceDir = getCodePath();
6040 String publicSourceDir = getResourcePath();
6041 if (sourceDir != null) {
6042 File sourceFile = new File(sourceDir);
6043 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006044 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006045 ret = false;
6046 }
6047 // Delete application's code and resources
6048 sourceFile.delete();
6049 }
6050 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
6051 final File publicSourceFile = new File(publicSourceDir);
6052 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006053 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006054 }
6055 if (publicSourceFile.exists()) {
6056 publicSourceFile.delete();
6057 }
6058 }
6059 return ret;
6060 }
6061
6062 void cleanUpResourcesLI() {
6063 String sourceDir = getCodePath();
Jeff Brown5d6d90f2011-07-11 13:04:53 -07006064 if (cleanUp()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006065 int retCode = mInstaller.rmdex(sourceDir);
6066 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006067 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006068 + " at location "
6069 + sourceDir + ", retcode=" + retCode);
6070 // we don't consider this to be a failure of the core package deletion
6071 }
6072 }
6073 }
6074
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006075 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006076 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07006077 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006078 final int filePermissions =
6079 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
6080 |FileUtils.S_IROTH;
6081 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
6082 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006083 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006084 getCodePath()
6085 + ". The return code was: " + retCode);
6086 // TODO Define new internal error
6087 return false;
6088 }
6089 return true;
6090 }
6091 return true;
6092 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006093
6094 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07006095 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006096 cleanUpResourcesLI();
6097 return true;
6098 }
Kenny Root85387d72010-08-26 10:13:11 -07006099
6100 private boolean isFwdLocked() {
6101 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
6102 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006103 }
6104
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07006105 /**
6106 * Extract the MountService "container ID" from the full code path of an
6107 * .apk.
6108 */
6109 static String cidFromCodePath(String fullCodePath) {
6110 int eidx = fullCodePath.lastIndexOf("/");
6111 String subStr1 = fullCodePath.substring(0, eidx);
6112 int sidx = subStr1.lastIndexOf("/");
6113 return subStr1.substring(sidx+1, eidx);
6114 }
6115
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006116 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006117 static final String RES_FILE_NAME = "pkg.apk";
6118
Kenny Root85387d72010-08-26 10:13:11 -07006119 String cid;
6120 String packagePath;
6121 String libraryPath;
6122
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006123 SdInstallArgs(InstallParams params) {
Kenny Root5ab21572011-07-27 11:11:19 -07006124 super(params.packageURI, params.observer, params.flags, params.installerPackageName,
6125 params.manifestDigest);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006126 }
6127
Kenny Root85387d72010-08-26 10:13:11 -07006128 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Kenny Root5ab21572011-07-27 11:11:19 -07006129 super(null, null, PackageManager.INSTALL_EXTERNAL, null, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006130 // Extract cid from fullCodePath
6131 int eidx = fullCodePath.lastIndexOf("/");
6132 String subStr1 = fullCodePath.substring(0, eidx);
6133 int sidx = subStr1.lastIndexOf("/");
6134 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07006135 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006136 }
6137
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006138 SdInstallArgs(String cid) {
Kenny Root5ab21572011-07-27 11:11:19 -07006139 super(null, null, PackageManager.INSTALL_EXTERNAL, null, null);
Dianne Hackbornaa77de12010-05-14 22:33:54 -07006140 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07006141 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006142 }
6143
6144 SdInstallArgs(Uri packageURI, String cid) {
Kenny Root5ab21572011-07-27 11:11:19 -07006145 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006146 this.cid = cid;
6147 }
6148
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006149 void createCopyFile() {
6150 cid = getTempContainerId();
6151 }
6152
Kenny Root11128572010-10-11 10:51:32 -07006153 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
6154 try {
6155 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
6156 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Kenny Root62e1b4e2011-03-14 17:13:39 -07006157 return imcs.checkExternalFreeStorage(packageURI);
Kenny Root11128572010-10-11 10:51:32 -07006158 } finally {
6159 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
6160 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08006161 }
6162
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006163 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006164 if (temp) {
6165 createCopyFile();
Kenny Rootf5121a92011-08-10 16:23:32 -07006166 } else {
6167 /*
6168 * Pre-emptively destroy the container since it's destroyed if
6169 * copying fails due to it existing anyway.
6170 */
6171 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006172 }
Kenny Root11128572010-10-11 10:51:32 -07006173
6174 final String newCachePath;
6175 try {
6176 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
6177 Intent.FLAG_GRANT_READ_URI_PERMISSION);
6178 newCachePath = imcs.copyResourceToContainer(packageURI, cid,
6179 getEncryptKey(), RES_FILE_NAME);
6180 } finally {
6181 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
6182 }
6183
Kenny Root85387d72010-08-26 10:13:11 -07006184 if (newCachePath != null) {
6185 setCachePath(newCachePath);
6186 return PackageManager.INSTALL_SUCCEEDED;
6187 } else {
6188 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
6189 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006190 }
6191
6192 @Override
6193 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07006194 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006195 }
6196
6197 @Override
6198 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07006199 return packagePath;
6200 }
6201
6202 @Override
6203 String getNativeLibraryPath() {
6204 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006205 }
6206
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006207 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006208 if (status != PackageManager.INSTALL_SUCCEEDED) {
6209 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08006210 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006211 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08006212 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006213 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07006214 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
6215 Process.SYSTEM_UID);
6216 if (newCachePath != null) {
6217 setCachePath(newCachePath);
6218 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006219 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
6220 }
6221 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006222 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006223 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006224 }
6225
6226 boolean doRename(int status, final String pkgName,
6227 String oldCodePath) {
6228 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006229 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006230 if (PackageHelper.isContainerMounted(cid)) {
6231 // Unmount the container
6232 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006233 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006234 return false;
6235 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006236 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006237 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07006238 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
6239 " which might be stale. Will try to clean up.");
6240 // Clean up the stale container and proceed to recreate.
6241 if (!PackageHelper.destroySdDir(newCacheId)) {
6242 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
6243 return false;
6244 }
6245 // Successfully cleaned up stale container. Try to rename again.
6246 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
6247 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
6248 + " inspite of cleaning it up.");
6249 return false;
6250 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006251 }
6252 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006253 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006254 newCachePath = PackageHelper.mountSdDir(newCacheId,
6255 getEncryptKey(), Process.SYSTEM_UID);
6256 } else {
6257 newCachePath = PackageHelper.getSdDir(newCacheId);
6258 }
6259 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006260 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006261 return false;
6262 }
6263 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07006264 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006265 " at new path: " + newCachePath);
6266 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07006267 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08006268 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006269 }
6270
Kenny Root85387d72010-08-26 10:13:11 -07006271 private void setCachePath(String newCachePath) {
6272 File cachePath = new File(newCachePath);
6273 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
6274 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
6275 }
6276
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006277 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006278 if (status != PackageManager.INSTALL_SUCCEEDED) {
6279 cleanUp();
6280 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08006281 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006282 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08006283 PackageHelper.mountSdDir(cid,
6284 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006285 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006286 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006287 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006288 }
6289
6290 private void cleanUp() {
6291 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08006292 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006293 }
6294
6295 void cleanUpResourcesLI() {
6296 String sourceFile = getCodePath();
6297 // Remove dex file
Jeff Brown5d6d90f2011-07-11 13:04:53 -07006298 int retCode = mInstaller.rmdex(sourceFile);
6299 if (retCode < 0) {
6300 Slog.w(TAG, "Couldn't remove dex file for package: "
6301 + " at location "
6302 + sourceFile.toString() + ", retcode=" + retCode);
6303 // we don't consider this to be a failure of the core package deletion
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006304 }
6305 cleanUp();
6306 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006307
6308 boolean matchContainer(String app) {
6309 if (cid.startsWith(app)) {
6310 return true;
6311 }
6312 return false;
6313 }
6314
6315 String getPackageName() {
6316 int idx = cid.lastIndexOf("-");
6317 if (idx == -1) {
6318 return cid;
6319 }
6320 return cid.substring(0, idx);
6321 }
6322
6323 boolean doPostDeleteLI(boolean delete) {
6324 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08006325 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006326 if (mounted) {
6327 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08006328 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006329 }
6330 if (ret && delete) {
6331 cleanUpResourcesLI();
6332 }
6333 return ret;
6334 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006335 };
6336
6337 // Utility method used to create code paths based on package name and available index.
6338 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
6339 String idxStr = "";
6340 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006341 // Fall back to default value of idx=1 if prefix is not
6342 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006343 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00006344 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006345 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00006346 if (subStr.endsWith(suffix)) {
6347 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006348 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006349 // If oldCodePath already contains prefix find out the
6350 // ending index to either increment or decrement.
6351 int sidx = subStr.lastIndexOf(prefix);
6352 if (sidx != -1) {
6353 subStr = subStr.substring(sidx + prefix.length());
6354 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006355 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
6356 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006357 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006358 try {
6359 idx = Integer.parseInt(subStr);
6360 if (idx <= 1) {
6361 idx++;
6362 } else {
6363 idx--;
6364 }
6365 } catch(NumberFormatException e) {
6366 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006367 }
6368 }
6369 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006370 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006371 return prefix + idxStr;
6372 }
6373
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006374 // Utility method used to ignore ADD/REMOVE events
6375 // by directory observer.
6376 private static boolean ignoreCodePath(String fullPathStr) {
6377 String apkName = getApkName(fullPathStr);
6378 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
6379 if (idx != -1 && ((idx+1) < apkName.length())) {
6380 // Make sure the package ends with a numeral
6381 String version = apkName.substring(idx+1);
6382 try {
6383 Integer.parseInt(version);
6384 return true;
6385 } catch (NumberFormatException e) {}
6386 }
6387 return false;
6388 }
6389
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006390 // Utility method that returns the relative package path with respect
6391 // to the installation directory. Like say for /data/data/com.test-1.apk
6392 // string com.test-1 is returned.
6393 static String getApkName(String codePath) {
6394 if (codePath == null) {
6395 return null;
6396 }
6397 int sidx = codePath.lastIndexOf("/");
6398 int eidx = codePath.lastIndexOf(".");
6399 if (eidx == -1) {
6400 eidx = codePath.length();
6401 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006402 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006403 return null;
6404 }
6405 return codePath.substring(sidx+1, eidx);
6406 }
6407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006408 class PackageInstalledInfo {
6409 String name;
6410 int uid;
6411 PackageParser.Package pkg;
6412 int returnCode;
6413 PackageRemovedInfo removedInfo;
6414 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 /*
6417 * Install a non-existing package.
6418 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006419 private void installNewPackageLI(PackageParser.Package pkg,
6420 int parseFlags,
6421 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02006422 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006423 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006424 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08006425
Amith Yamasani0b285492011-04-14 17:35:23 -07006426 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006427 res.name = pkgName;
6428 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07006429 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
6430 // A package with the same name is already installed, though
6431 // it has been renamed to an older name. The package we
6432 // are trying to install should be installed as an update to
6433 // the existing one, but that has not been requested, so bail.
6434 Slog.w(TAG, "Attempt to re-install " + pkgName
6435 + " without first uninstalling package running as "
6436 + mSettings.mRenamedPackages.get(pkgName));
6437 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
6438 return;
6439 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006440 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006441 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006442 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006443 + " without first uninstalling.");
6444 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
6445 return;
6446 }
6447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006448 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006449 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
6450 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006451 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006452 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006453 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
6454 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
6455 }
6456 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006457 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02006458 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006459 res);
6460 // delete the partially installed application. the data directory will have to be
6461 // restored if it was already existing
6462 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
6463 // remove package from internal structures. Note that we want deletePackageX to
6464 // delete the package data and cache directories that it created in
6465 // scanPackageLocked, unless those directories existed before we even tried to
6466 // install.
6467 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006468 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006469 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006470 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006471 }
6472 }
6473 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006474
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006475 private void replacePackageLI(PackageParser.Package pkg,
6476 int parseFlags,
6477 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02006478 String installerPackageName, PackageInstalledInfo res) {
6479
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006480 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006481 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006482 // First find the old package info and check signatures
6483 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006484 oldPackage = mPackages.get(pkgName);
Kenny Root447106f2011-03-23 11:00:15 -07006485 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07006486 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
6488 return;
6489 }
6490 }
Kenny Root85387d72010-08-26 10:13:11 -07006491 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006492 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006493 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006494 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006495 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006496 }
6497 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006499 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006500 PackageParser.Package pkg,
6501 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02006502 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006503 PackageParser.Package newPackage = null;
6504 String pkgName = deletedPackage.packageName;
6505 boolean deletedPkg = true;
6506 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006507
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006508 long origUpdateTime;
6509 if (pkg.mExtras != null) {
6510 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
6511 } else {
6512 origUpdateTime = 0;
6513 }
6514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006515 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006516 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006517 res.removedInfo, true)) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006518 // If the existing package wasn't successfully deleted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006519 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
6520 deletedPkg = false;
6521 } else {
6522 // Successfully deleted the old package. Now proceed with re-installation
6523 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006524 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
6525 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006526 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006527 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006528 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
6529 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08006530 }
6531 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006532 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02006533 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006534 res);
6535 updatedSettings = true;
6536 }
6537 }
6538
Suchi Amalapurapuae181712010-03-30 14:01:02 -07006539 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006540 // remove package from internal structures. Note that we want deletePackageX to
6541 // delete the package data and cache directories that it created in
6542 // scanPackageLocked, unless those directories existed before we even tried to
6543 // install.
6544 if(updatedSettings) {
6545 deletePackageLI(
6546 pkgName, true,
6547 PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006548 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006549 }
6550 // Since we failed to install the new package we need to restore the old
6551 // package that we deleted.
6552 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07006553 File restoreFile = new File(deletedPackage.mPath);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006554 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07006555 boolean oldOnSd = isExternal(deletedPackage);
6556 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
6557 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
6558 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006559 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
6560 | SCAN_UPDATE_TIME;
6561 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
6562 origUpdateTime) == null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07006563 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
6564 return;
6565 }
6566 // Restore of old package succeeded. Update permissions.
Kenny Root447106f2011-03-23 11:00:15 -07006567 // writer
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006568 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07006569 updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
Dianne Hackborne639da72012-02-21 15:11:13 -08006570 UPDATE_PERMISSIONS_ALL);
Kenny Root447106f2011-03-23 11:00:15 -07006571 // can downgrade to reader
6572 mSettings.writeLPr();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006573 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07006574 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006575 }
6576 }
6577 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006579 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006580 PackageParser.Package pkg,
6581 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02006582 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006583 PackageParser.Package newPackage = null;
6584 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006585 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006586 PackageParser.PARSE_IS_SYSTEM;
6587 String packageName = deletedPackage.packageName;
6588 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
6589 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006590 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006591 return;
6592 }
6593 PackageParser.Package oldPkg;
6594 PackageSetting oldPkgSetting;
Kenny Root447106f2011-03-23 11:00:15 -07006595 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006596 synchronized (mPackages) {
6597 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006598 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006599 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
6600 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006601 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006602 return;
6603 }
6604 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08006605
6606 killApplication(packageName, oldPkg.applicationInfo.uid);
6607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006608 res.removedInfo.uid = oldPkg.applicationInfo.uid;
6609 res.removedInfo.removedPackage = packageName;
6610 // Remove existing system package
6611 removePackageLI(oldPkg, true);
Kenny Root447106f2011-03-23 11:00:15 -07006612 // writer
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08006613 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07006614 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08006615 // We didn't need to disable the .apk as a current system package,
6616 // which means we are replacing another update that is already
6617 // installed. We need to make sure to delete the older one's .apk.
6618 res.removedInfo.args = createInstallArgs(isExternal(pkg)
6619 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL,
6620 deletedPackage.applicationInfo.sourceDir,
6621 deletedPackage.applicationInfo.publicSourceDir,
6622 deletedPackage.applicationInfo.nativeLibraryDir);
6623 } else {
6624 res.removedInfo.args = null;
6625 }
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08006626 }
6627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006628 // Successfully disabled the old package. Now proceed with re-installation
6629 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
6630 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006631 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006632 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006633 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006634 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
6635 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
6636 }
6637 } else {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006638 if (newPackage.mExtras != null) {
6639 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
6640 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
6641 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
6642 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006643 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006644 updatedSettings = true;
6645 }
6646
Suchi Amalapurapuae181712010-03-30 14:01:02 -07006647 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006648 // Re installation failed. Restore old information
6649 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07006650 if (newPackage != null) {
6651 removePackageLI(newPackage, true);
6652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006653 // Add back the old system package
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006654 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006655 // Restore the old system information in Settings
6656 synchronized(mPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006657 if (updatedSettings) {
Kenny Root447106f2011-03-23 11:00:15 -07006658 mSettings.enableSystemPackageLPw(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02006659 mSettings.setInstallerPackageName(packageName,
6660 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006661 }
Kenny Root447106f2011-03-23 11:00:15 -07006662 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006663 }
6664 }
6665 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006666
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006667 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07006668 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006669 int retCode;
6670 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
6671 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
6672 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07006673 if (mNoDexOpt) {
6674 /*
6675 * If we're in an engineering build, programs are lazily run
6676 * through dexopt. If the .dex file doesn't exist yet, it
6677 * will be created when the program is run next.
6678 */
6679 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
6680 } else {
6681 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
6682 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6683 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006684 }
6685 }
6686 return PackageManager.INSTALL_SUCCEEDED;
6687 }
6688
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006689 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02006690 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006691 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006692 synchronized (mPackages) {
6693 //write settings. the installStatus will be incomplete at this stage.
6694 //note that the new package setting would have already been
6695 //added to mPackages. It hasn't been persisted yet.
Kenny Rootcf0b38c2011-03-22 14:17:59 -07006696 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
Kenny Root447106f2011-03-23 11:00:15 -07006697 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006698 }
6699
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07006700 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006701 != PackageManager.INSTALL_SUCCEEDED) {
6702 // Discontinue if moving dex files failed.
6703 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006704 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006705 if((res.returnCode = setPermissionsLI(newPackage))
6706 != PackageManager.INSTALL_SUCCEEDED) {
Jeff Brown5d6d90f2011-07-11 13:04:53 -07006707 mInstaller.rmdex(newPackage.mScanPath);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006708 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006709 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006710 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006712 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07006713 updatePermissionsLPw(newPackage.packageName, newPackage,
Dianne Hackborne639da72012-02-21 15:11:13 -08006714 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
6715 ? UPDATE_PERMISSIONS_ALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006716 res.name = pkgName;
6717 res.uid = newPackage.applicationInfo.uid;
6718 res.pkg = newPackage;
Kenny Rootcf0b38c2011-03-22 14:17:59 -07006719 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02006720 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006721 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
6722 //to update install status
Kenny Root447106f2011-03-23 11:00:15 -07006723 mSettings.writeLPr();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006724 }
6725 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006726
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006727 private void installPackageLI(InstallArgs args,
6728 boolean newInstall, PackageInstalledInfo res) {
6729 int pFlags = args.flags;
6730 String installerPackageName = args.installerPackageName;
6731 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006732 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006733 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006734 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07006735 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006736 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07006737 // Result object to be returned
6738 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
6739
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006740 // Retrieve PackageSettings and parse package
6741 int parseFlags = PackageParser.PARSE_CHATTY |
6742 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
6743 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
6744 parseFlags |= mDefParseFlags;
6745 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
6746 pp.setSeparateProcesses(mSeparateProcesses);
6747 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
6748 null, mMetrics, parseFlags);
6749 if (pkg == null) {
6750 res.returnCode = pp.getParseError();
6751 return;
6752 }
6753 String pkgName = res.name = pkg.packageName;
6754 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
6755 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
6756 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
6757 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006758 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006759 }
6760 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
6761 res.returnCode = pp.getParseError();
6762 return;
6763 }
Kenny Root5ab21572011-07-27 11:11:19 -07006764
6765 /* If the installer passed in a manifest digest, compare it now. */
6766 if (args.manifestDigest != null) {
6767 if (DEBUG_INSTALL) {
6768 final String parsedManifest = pkg.manifestDigest == null ? "null"
6769 : pkg.manifestDigest.toString();
6770 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
6771 + parsedManifest);
6772 }
6773
6774 if (!args.manifestDigest.equals(pkg.manifestDigest)) {
6775 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
6776 return;
6777 }
6778 } else if (DEBUG_INSTALL) {
6779 final String parsedManifest = pkg.manifestDigest == null
6780 ? "null" : pkg.manifestDigest.toString();
6781 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
6782 }
6783
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006784 // Get rid of all references to package scan path via parser.
6785 pp = null;
6786 String oldCodePath = null;
6787 boolean systemApp = false;
6788 synchronized (mPackages) {
6789 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006790 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
6791 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08006792 if (pkg.mOriginalPackages != null
6793 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006794 && mPackages.containsKey(oldName)) {
6795 // This package is derived from an original package,
6796 // and this device has been updating from that original
6797 // name. We must continue using the original name, so
6798 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08006799 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006800 pkgName = pkg.packageName;
6801 replace = true;
6802 } else if (mPackages.containsKey(pkgName)) {
6803 // This package, under its official name, already exists
6804 // on the device; we should replace it.
6805 replace = true;
6806 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006807 }
6808 PackageSetting ps = mSettings.mPackages.get(pkgName);
6809 if (ps != null) {
6810 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
6811 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6812 systemApp = (ps.pkg.applicationInfo.flags &
6813 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07006814 }
6815 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006816 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006817
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006818 if (systemApp && onSd) {
6819 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006820 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006821 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
6822 return;
6823 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08006824
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006825 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
6826 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6827 return;
6828 }
6829 // Set application objects path explicitly after the rename
6830 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07006831 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006832 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006833 replacePackageLI(pkg, parseFlags, scanMode,
6834 installerPackageName, res);
6835 } else {
6836 installNewPackageLI(pkg, parseFlags, scanMode,
6837 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006838 }
6839 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006840
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006841 private int setPermissionsLI(PackageParser.Package newPackage) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006842 int retCode = 0;
6843 // TODO Gross hack but fix later. Ideally move this to be a post installation
6844 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07006845 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006846 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006847 try {
6848 extractPublicFiles(newPackage, destResourceFile);
6849 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006850 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006851 " forward-locked app.");
6852 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6853 } finally {
6854 //TODO clean up the extracted public files
6855 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07006856 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
6857 newPackage.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006858 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006859 // The permissions on the resource file was set when it was copied for
6860 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006861 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006863 if (retCode != 0) {
Kenny Root4dfe6ff2011-02-23 17:00:43 -08006864 Slog.e(TAG, "Couldn't set new package file permissions for " + newPackage.mPath
6865 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006866 // TODO Define new internal error
6867 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006868 }
6869 return PackageManager.INSTALL_SUCCEEDED;
6870 }
6871
Kenny Root85387d72010-08-26 10:13:11 -07006872 private static boolean isForwardLocked(PackageParser.Package pkg) {
6873 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006874 }
6875
Kenny Root85387d72010-08-26 10:13:11 -07006876 private static boolean isExternal(PackageParser.Package pkg) {
6877 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
6878 }
6879
6880 private static boolean isSystemApp(PackageParser.Package pkg) {
6881 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
6882 }
6883
Kenny Root502e9a42011-01-10 13:48:15 -08006884 private static boolean isSystemApp(ApplicationInfo info) {
6885 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
6886 }
6887
Kenny Root85387d72010-08-26 10:13:11 -07006888 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
6889 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07006890 }
6891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006892 private void extractPublicFiles(PackageParser.Package newPackage,
6893 File publicZipFile) throws IOException {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006894 final FileOutputStream fstr = new FileOutputStream(publicZipFile);
6895 final ZipOutputStream publicZipOutStream = new ZipOutputStream(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006896 final ZipFile privateZip = new ZipFile(newPackage.mPath);
6897
6898 // Copy manifest, resources.arsc and res directory to public zip
6899
6900 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
6901 while (privateZipEntries.hasMoreElements()) {
6902 final ZipEntry zipEntry = privateZipEntries.nextElement();
6903 final String zipEntryName = zipEntry.getName();
6904 if ("AndroidManifest.xml".equals(zipEntryName)
6905 || "resources.arsc".equals(zipEntryName)
6906 || zipEntryName.startsWith("res/")) {
6907 try {
6908 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
6909 } catch (IOException e) {
6910 try {
6911 publicZipOutStream.close();
6912 throw e;
6913 } finally {
6914 publicZipFile.delete();
6915 }
6916 }
6917 }
6918 }
6919
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006920 publicZipOutStream.finish();
6921 publicZipOutStream.flush();
6922 FileUtils.sync(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006923 publicZipOutStream.close();
6924 FileUtils.setPermissions(
6925 publicZipFile.getAbsolutePath(),
6926 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
6927 -1, -1);
6928 }
6929
6930 private static void copyZipEntry(ZipEntry zipEntry,
6931 ZipFile inZipFile,
6932 ZipOutputStream outZipStream) throws IOException {
6933 byte[] buffer = new byte[4096];
6934 int num;
6935
6936 ZipEntry newEntry;
6937 if (zipEntry.getMethod() == ZipEntry.STORED) {
6938 // Preserve the STORED method of the input entry.
6939 newEntry = new ZipEntry(zipEntry);
6940 } else {
6941 // Create a new entry so that the compressed len is recomputed.
6942 newEntry = new ZipEntry(zipEntry.getName());
6943 }
6944 outZipStream.putNextEntry(newEntry);
6945
6946 InputStream data = inZipFile.getInputStream(zipEntry);
6947 while ((num = data.read(buffer)) > 0) {
6948 outZipStream.write(buffer, 0, num);
6949 }
6950 outZipStream.flush();
6951 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006953 private void deleteTempPackageFiles() {
6954 FilenameFilter filter = new FilenameFilter() {
6955 public boolean accept(File dir, String name) {
6956 return name.startsWith("vmdl") && name.endsWith(".tmp");
6957 }
6958 };
6959 String tmpFilesList[] = mAppInstallDir.list(filter);
6960 if(tmpFilesList == null) {
6961 return;
6962 }
6963 for(int i = 0; i < tmpFilesList.length; i++) {
6964 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
6965 tmpFile.delete();
6966 }
6967 }
6968
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006969 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006970 File tmpPackageFile;
6971 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006972 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006973 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006974 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006975 return null;
6976 }
6977 try {
6978 FileUtils.setPermissions(
6979 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6980 -1, -1);
6981 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006982 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006983 return null;
6984 }
6985 return tmpPackageFile;
6986 }
6987
6988 public void deletePackage(final String packageName,
6989 final IPackageDeleteObserver observer,
6990 final int flags) {
6991 mContext.enforceCallingOrSelfPermission(
6992 android.Manifest.permission.DELETE_PACKAGES, null);
6993 // Queue up an async operation since the package deletion may take a little while.
6994 mHandler.post(new Runnable() {
6995 public void run() {
6996 mHandler.removeCallbacks(this);
Kenny Rootc39bb4a2011-02-28 13:27:19 -08006997 final int returnCode = deletePackageX(packageName, true, true, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006998 if (observer != null) {
6999 try {
Kenny Rootc39bb4a2011-02-28 13:27:19 -08007000 observer.packageDeleted(packageName, returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007001 } catch (RemoteException e) {
7002 Log.i(TAG, "Observer no longer exists.");
7003 } //end catch
7004 } //end if
7005 } //end run
7006 });
7007 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007009 /**
7010 * This method is an internal method that could be get invoked either
7011 * to delete an installed package or to clean up a failed installation.
7012 * After deleting an installed package, a broadcast is sent to notify any
7013 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007014 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007015 * installation wouldn't have sent the initial broadcast either
7016 * The key steps in deleting a package are
7017 * deleting the package information in internal structures like mPackages,
7018 * deleting the packages base directories through installd
7019 * updating mSettings to reflect current status
7020 * persisting settings for later use
7021 * sending a broadcast if necessary
7022 */
Kenny Rootc39bb4a2011-02-28 13:27:19 -08007023 private int deletePackageX(String packageName, boolean sendBroadCast,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007024 boolean deleteCodeAndResources, int flags) {
Kenny Rootc39bb4a2011-02-28 13:27:19 -08007025 final PackageRemovedInfo info = new PackageRemovedInfo();
7026 final boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007027
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007028 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
7029 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
7030 try {
7031 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007032 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Kenny Rootc39bb4a2011-02-28 13:27:19 -08007033 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007034 }
7035 } catch (RemoteException e) {
7036 }
7037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007038 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07007039 res = deletePackageLI(packageName, deleteCodeAndResources,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007040 flags | REMOVE_CHATTY, info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007041 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007042
Kenny Rootc39bb4a2011-02-28 13:27:19 -08007043 if (res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07007044 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07007045 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07007046
7047 // If the removed package was a system update, the old system packaged
7048 // was re-enabled; we need to broadcast this information
7049 if (systemUpdate) {
7050 Bundle extras = new Bundle(1);
7051 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
7052 extras.putBoolean(Intent.EXTRA_REPLACING, true);
7053
Dianne Hackborne7f97212011-02-24 14:40:20 -08007054 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
7055 extras, null, null);
7056 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
7057 extras, null, null);
7058 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
7059 null, packageName, null);
Romain Guy96f43572009-03-24 20:27:49 -07007060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007061 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07007062 // Force a gc here.
7063 Runtime.getRuntime().gc();
7064 // Delete the resources here after sending the broadcast to let
7065 // other processes clean up before deleting resources.
7066 if (info.args != null) {
7067 synchronized (mInstallLock) {
7068 info.args.doPostDeleteLI(deleteCodeAndResources);
7069 }
7070 }
Kenny Rootc39bb4a2011-02-28 13:27:19 -08007071
7072 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007073 }
7074
7075 static class PackageRemovedInfo {
7076 String removedPackage;
7077 int uid = -1;
7078 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07007079 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007080 // Clean up resources deleted packages.
7081 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07007082
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07007083 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007084 Bundle extras = new Bundle(1);
7085 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
7086 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
7087 if (replacing) {
7088 extras.putBoolean(Intent.EXTRA_REPLACING, true);
7089 }
7090 if (removedPackage != null) {
Dianne Hackborne7f97212011-02-24 14:40:20 -08007091 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7092 extras, null, null);
Dianne Hackbornf9abb402011-08-10 15:00:59 -07007093 if (fullRemove && !replacing) {
7094 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
7095 extras, null, null);
7096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007097 }
7098 if (removedUid >= 0) {
Dianne Hackborne7f97212011-02-24 14:40:20 -08007099 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007100 }
7101 }
7102 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007104 /*
7105 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
7106 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007107 * 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 -08007108 * delete a partially installed application.
7109 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007110 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007111 int flags, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007112 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007113 if (outInfo != null) {
7114 outInfo.removedPackage = packageName;
7115 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07007116 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007117 // Retrieve object to delete permissions for shared user later on
Kenny Root447106f2011-03-23 11:00:15 -07007118 final PackageSetting deletedPs;
7119 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007120 synchronized (mPackages) {
7121 deletedPs = mSettings.mPackages.get(packageName);
7122 }
7123 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Jeff Brown5d6d90f2011-07-11 13:04:53 -07007124 int retCode = mInstaller.remove(packageName, 0);
7125 if (retCode < 0) {
7126 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
7127 + packageName + ", retcode=" + retCode);
7128 // we don't consider this to be a failure of the core package deletion
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007129 } else {
Jeff Brown5d6d90f2011-07-11 13:04:53 -07007130 // TODO: Kill the processes first
7131 mUserManager.removePackageForAllUsers(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007132 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07007133 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007134 }
Kenny Root447106f2011-03-23 11:00:15 -07007135 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007136 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007137 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007138 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
7139 if (outInfo != null) {
Kenny Root447106f2011-03-23 11:00:15 -07007140 outInfo.removedUid = mSettings.removePackageLPw(packageName);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007141 }
7142 if (deletedPs != null) {
Dianne Hackborne639da72012-02-21 15:11:13 -08007143 updatePermissionsLPw(deletedPs.name, null, 0);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007144 if (deletedPs.sharedUser != null) {
7145 // remove permissions associated with package
Kenny Root447106f2011-03-23 11:00:15 -07007146 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007147 }
7148 }
Dianne Hackborn04505102012-02-29 12:34:04 -08007149 clearPackagePreferredActivitiesLPw(deletedPs.name);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007150 }
7151 }
Kenny Root447106f2011-03-23 11:00:15 -07007152 // can downgrade to reader
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007153 if (writeSettings) {
7154 // Save settings now
Kenny Root447106f2011-03-23 11:00:15 -07007155 mSettings.writeLPr();
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007157 }
7158 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007160 /*
7161 * Tries to delete system package.
7162 */
7163 private boolean deleteSystemPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007164 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007165 ApplicationInfo applicationInfo = p.applicationInfo;
7166 //applicable for non-partially installed applications only
7167 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007168 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007169 return false;
7170 }
7171 PackageSetting ps = null;
7172 // Confirm if the system package has been updated
7173 // An updated system app can be deleted. This will also have to restore
7174 // the system pkg from system partition
Kenny Root447106f2011-03-23 11:00:15 -07007175 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007176 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07007177 ps = mSettings.getDisabledSystemPkgLPr(p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007178 }
7179 if (ps == null) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007180 Slog.w(TAG, "Attempt to delete unknown system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007181 return false;
7182 } else {
7183 Log.i(TAG, "Deleting system pkg from data partition");
7184 }
7185 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07007186 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07007187 if (ps.versionCode < p.mVersionCode) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007188 // Delete data for downgrades
Kenny Root7c1bd7f2010-09-01 13:44:11 -07007189 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007190 } else {
7191 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07007192 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007193 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007194 boolean ret = deleteInstalledPackageLI(p, true, flags, outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007195 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007196 if (!ret) {
7197 return false;
7198 }
Kenny Root447106f2011-03-23 11:00:15 -07007199 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007200 synchronized (mPackages) {
7201 // Reinstate the old system package
Kenny Root447106f2011-03-23 11:00:15 -07007202 mSettings.enableSystemPackageLPw(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07007203 // Remove any native libraries from the upgraded package.
7204 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007205 }
7206 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007207 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007208 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007209 SCAN_MONITOR | SCAN_NO_PATHS, 0);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007211 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007212 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007213 return false;
7214 }
Kenny Root447106f2011-03-23 11:00:15 -07007215 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007216 synchronized (mPackages) {
Dianne Hackborne639da72012-02-21 15:11:13 -08007217 updatePermissionsLPw(newPkg.packageName, newPkg,
7218 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
Kenny Root447106f2011-03-23 11:00:15 -07007219 // can downgrade to reader here
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007220 if (writeSettings) {
Kenny Root447106f2011-03-23 11:00:15 -07007221 mSettings.writeLPr();
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007223 }
7224 return true;
7225 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007227 private boolean deleteInstalledPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007228 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
7229 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007230 ApplicationInfo applicationInfo = p.applicationInfo;
7231 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007232 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007233 return false;
7234 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007235 if (outInfo != null) {
7236 outInfo.uid = applicationInfo.uid;
7237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007238
7239 // Delete package data from internal structures and also remove data if flag is set
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007240 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007241
7242 // Delete application code and resources
7243 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007244 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07007245 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
7246 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
7247 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
7248 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007249 }
7250 return true;
7251 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007253 /*
7254 * This method handles package deletion in general
7255 */
7256 private boolean deletePackageLI(String packageName,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007257 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
7258 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007259 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007260 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007261 return false;
7262 }
7263 PackageParser.Package p;
7264 boolean dataOnly = false;
7265 synchronized (mPackages) {
7266 p = mPackages.get(packageName);
7267 if (p == null) {
7268 //this retrieves partially installed apps
7269 dataOnly = true;
7270 PackageSetting ps = mSettings.mPackages.get(packageName);
7271 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007272 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007273 return false;
7274 }
7275 p = ps.pkg;
7276 }
7277 }
7278 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007279 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007280 return false;
7281 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007283 if (dataOnly) {
7284 // Delete application data first
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007285 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007286 return true;
7287 }
7288 // At this point the package should have ApplicationInfo associated with it
7289 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007290 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007291 return false;
7292 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007293 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07007294 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007295 Log.i(TAG, "Removing system package:"+p.packageName);
7296 // When an updated system application is deleted we delete the existing resources as well and
7297 // fall back to existing code in system partition
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007298 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007299 } else {
7300 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007301 // Kill application pre-emptively especially for apps on sd.
7302 killApplication(packageName, p.applicationInfo.uid);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07007303 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
7304 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007305 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007306 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007307 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007309 public void clearApplicationUserData(final String packageName,
7310 final IPackageDataObserver observer) {
7311 mContext.enforceCallingOrSelfPermission(
7312 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
7313 // Queue up an async operation since the package deletion may take a little while.
7314 mHandler.post(new Runnable() {
7315 public void run() {
7316 mHandler.removeCallbacks(this);
7317 final boolean succeeded;
7318 synchronized (mInstallLock) {
7319 succeeded = clearApplicationUserDataLI(packageName);
7320 }
7321 if (succeeded) {
7322 // invoke DeviceStorageMonitor's update method to clear any notifications
7323 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
7324 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
7325 if (dsm != null) {
7326 dsm.updateMemory();
7327 }
7328 }
7329 if(observer != null) {
7330 try {
7331 observer.onRemoveCompleted(packageName, succeeded);
7332 } catch (RemoteException e) {
7333 Log.i(TAG, "Observer no longer exists.");
7334 }
7335 } //end if observer
7336 } //end run
7337 });
7338 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007340 private boolean clearApplicationUserDataLI(String packageName) {
7341 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007342 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007343 return false;
7344 }
7345 PackageParser.Package p;
7346 boolean dataOnly = false;
7347 synchronized (mPackages) {
7348 p = mPackages.get(packageName);
7349 if(p == null) {
7350 dataOnly = true;
7351 PackageSetting ps = mSettings.mPackages.get(packageName);
7352 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007353 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007354 return false;
7355 }
7356 p = ps.pkg;
7357 }
7358 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08007359
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08007360 if (!dataOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007361 //need to check this only for fully installed applications
7362 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007363 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007364 return false;
7365 }
7366 final ApplicationInfo applicationInfo = p.applicationInfo;
7367 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007368 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007369 return false;
7370 }
7371 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07007372 int retCode = mInstaller.clearUserData(packageName, 0); // TODO - correct userId
7373 if (retCode < 0) {
7374 Slog.w(TAG, "Couldn't remove cache files for package: "
7375 + packageName);
7376 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007377 }
7378 return true;
7379 }
7380
7381 public void deleteApplicationCacheFiles(final String packageName,
7382 final IPackageDataObserver observer) {
7383 mContext.enforceCallingOrSelfPermission(
7384 android.Manifest.permission.DELETE_CACHE_FILES, null);
7385 // Queue up an async operation since the package deletion may take a little while.
7386 mHandler.post(new Runnable() {
7387 public void run() {
7388 mHandler.removeCallbacks(this);
7389 final boolean succeded;
7390 synchronized (mInstallLock) {
7391 succeded = deleteApplicationCacheFilesLI(packageName);
7392 }
7393 if(observer != null) {
7394 try {
7395 observer.onRemoveCompleted(packageName, succeded);
7396 } catch (RemoteException e) {
7397 Log.i(TAG, "Observer no longer exists.");
7398 }
7399 } //end if observer
7400 } //end run
7401 });
7402 }
7403
7404 private boolean deleteApplicationCacheFilesLI(String packageName) {
7405 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007406 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007407 return false;
7408 }
7409 PackageParser.Package p;
7410 synchronized (mPackages) {
7411 p = mPackages.get(packageName);
7412 }
7413 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007414 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007415 return false;
7416 }
7417 final ApplicationInfo applicationInfo = p.applicationInfo;
7418 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007419 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007420 return false;
7421 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07007422 int retCode = mInstaller.deleteCacheFiles(packageName);
7423 if (retCode < 0) {
7424 Slog.w(TAG, "Couldn't remove cache files for package: "
7425 + packageName);
7426 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007427 }
7428 return true;
7429 }
7430
7431 public void getPackageSizeInfo(final String packageName,
7432 final IPackageStatsObserver observer) {
7433 mContext.enforceCallingOrSelfPermission(
7434 android.Manifest.permission.GET_PACKAGE_SIZE, null);
7435 // Queue up an async operation since the package deletion may take a little while.
7436 mHandler.post(new Runnable() {
7437 public void run() {
7438 mHandler.removeCallbacks(this);
Kenny Root366949c2011-01-14 17:18:14 -08007439 PackageStats stats = new PackageStats(packageName);
7440
7441 final boolean success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007442 synchronized (mInstallLock) {
Kenny Root366949c2011-01-14 17:18:14 -08007443 success = getPackageSizeInfoLI(packageName, stats);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007444 }
Kenny Root366949c2011-01-14 17:18:14 -08007445
7446 Message msg = mHandler.obtainMessage(INIT_COPY);
7447 msg.obj = new MeasureParams(stats, success, observer);
7448 mHandler.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007449 } //end run
7450 });
7451 }
7452
7453 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
7454 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007455 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007456 return false;
7457 }
7458 PackageParser.Package p;
7459 boolean dataOnly = false;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07007460 String asecPath = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007461 synchronized (mPackages) {
7462 p = mPackages.get(packageName);
7463 if(p == null) {
7464 dataOnly = true;
7465 PackageSetting ps = mSettings.mPackages.get(packageName);
7466 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007467 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007468 return false;
7469 }
7470 p = ps.pkg;
7471 }
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07007472 if (p != null && isExternal(p)) {
7473 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
7474 if (secureContainerId != null) {
7475 asecPath = PackageHelper.getSdFilesystem(secureContainerId);
7476 }
7477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007478 }
7479 String publicSrcDir = null;
7480 if(!dataOnly) {
7481 final ApplicationInfo applicationInfo = p.applicationInfo;
7482 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007483 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007484 return false;
7485 }
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07007486 if (isForwardLocked(p)) {
7487 publicSrcDir = applicationInfo.publicSourceDir;
7488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007489 }
Jeff Brown5d6d90f2011-07-11 13:04:53 -07007490 int res = mInstaller.getSizeInfo(packageName, p.mPath, publicSrcDir,
7491 asecPath, pStats);
7492 if (res < 0) {
7493 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007494 }
7495 return true;
7496 }
7497
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007499 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07007500 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007501 }
7502
7503 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07007504 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007505 }
7506
7507 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08007508 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007509 }
7510
Kenny Root447106f2011-03-23 11:00:15 -07007511 private int getUidTargetSdkVersionLockedLPr(int uid) {
7512 Object obj = mSettings.getUserIdLPr(uid);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007513 if (obj instanceof SharedUserSetting) {
Kenny Root60f7ad82011-03-22 12:49:06 -07007514 final SharedUserSetting sus = (SharedUserSetting) obj;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007515 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
Kenny Root60f7ad82011-03-22 12:49:06 -07007516 final Iterator<PackageSetting> it = sus.packages.iterator();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007517 while (it.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07007518 final PackageSetting ps = it.next();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007519 if (ps.pkg != null) {
7520 int v = ps.pkg.applicationInfo.targetSdkVersion;
7521 if (v < vers) vers = v;
7522 }
7523 }
7524 return vers;
7525 } else if (obj instanceof PackageSetting) {
Kenny Root60f7ad82011-03-22 12:49:06 -07007526 final PackageSetting ps = (PackageSetting) obj;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007527 if (ps.pkg != null) {
7528 return ps.pkg.applicationInfo.targetSdkVersion;
7529 }
7530 }
7531 return Build.VERSION_CODES.CUR_DEVELOPMENT;
7532 }
7533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007534 public void addPreferredActivity(IntentFilter filter, int match,
7535 ComponentName[] set, ComponentName activity) {
Kenny Root447106f2011-03-23 11:00:15 -07007536 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007537 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007538 if (mContext.checkCallingOrSelfPermission(
7539 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
7540 != PackageManager.PERMISSION_GRANTED) {
Kenny Root447106f2011-03-23 11:00:15 -07007541 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007542 < Build.VERSION_CODES.FROYO) {
7543 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
7544 + Binder.getCallingUid());
7545 return;
7546 }
7547 mContext.enforceCallingOrSelfPermission(
7548 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
7549 }
7550
7551 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007552 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
7553 mSettings.mPreferredActivities.addFilter(
7554 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007555 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007556 }
7557 }
7558
Satish Sampath8dbe6122009-06-02 23:35:54 +01007559 public void replacePreferredActivity(IntentFilter filter, int match,
7560 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01007561 if (filter.countActions() != 1) {
7562 throw new IllegalArgumentException(
7563 "replacePreferredActivity expects filter to have only 1 action.");
7564 }
7565 if (filter.countCategories() != 1) {
7566 throw new IllegalArgumentException(
7567 "replacePreferredActivity expects filter to have only 1 category.");
7568 }
7569 if (filter.countDataAuthorities() != 0
7570 || filter.countDataPaths() != 0
7571 || filter.countDataSchemes() != 0
7572 || filter.countDataTypes() != 0) {
7573 throw new IllegalArgumentException(
7574 "replacePreferredActivity expects filter to have no data authorities, " +
7575 "paths, schemes or types.");
7576 }
7577 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007578 if (mContext.checkCallingOrSelfPermission(
7579 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
7580 != PackageManager.PERMISSION_GRANTED) {
Kenny Root447106f2011-03-23 11:00:15 -07007581 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007582 < Build.VERSION_CODES.FROYO) {
7583 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
7584 + Binder.getCallingUid());
7585 return;
7586 }
7587 mContext.enforceCallingOrSelfPermission(
7588 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
7589 }
7590
Dianne Hackborn04505102012-02-29 12:34:04 -08007591 ArrayList<PreferredActivity> removed = null;
Satish Sampath8dbe6122009-06-02 23:35:54 +01007592 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
7593 String action = filter.getAction(0);
7594 String category = filter.getCategory(0);
7595 while (it.hasNext()) {
7596 PreferredActivity pa = it.next();
7597 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
Dianne Hackborn04505102012-02-29 12:34:04 -08007598 if (removed == null) {
7599 removed = new ArrayList<PreferredActivity>();
7600 }
7601 removed.add(pa);
7602 Log.i(TAG, "Removing preferred activity " + pa.mPref.mComponent + ":");
Satish Sampath8dbe6122009-06-02 23:35:54 +01007603 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
7604 }
7605 }
Dianne Hackborn04505102012-02-29 12:34:04 -08007606 if (removed != null) {
7607 for (int i=0; i<removed.size(); i++) {
7608 PreferredActivity pa = removed.get(i);
7609 mSettings.mPreferredActivities.removeFilter(pa);
7610 }
7611 }
Satish Sampath8dbe6122009-06-02 23:35:54 +01007612 addPreferredActivity(filter, match, set, activity);
7613 }
7614 }
7615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007616 public void clearPackagePreferredActivities(String packageName) {
Kenny Root447106f2011-03-23 11:00:15 -07007617 final int uid = Binder.getCallingUid();
7618 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007619 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08007620 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007621 if (pkg == null || pkg.applicationInfo.uid != uid) {
7622 if (mContext.checkCallingOrSelfPermission(
7623 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
7624 != PackageManager.PERMISSION_GRANTED) {
Kenny Root447106f2011-03-23 11:00:15 -07007625 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007626 < Build.VERSION_CODES.FROYO) {
7627 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
7628 + Binder.getCallingUid());
7629 return;
7630 }
7631 mContext.enforceCallingOrSelfPermission(
7632 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
7633 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08007634 }
7635
Kenny Root447106f2011-03-23 11:00:15 -07007636 if (clearPackagePreferredActivitiesLPw(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007637 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007638 }
7639 }
7640 }
7641
Kenny Root447106f2011-03-23 11:00:15 -07007642 boolean clearPackagePreferredActivitiesLPw(String packageName) {
Dianne Hackborn04505102012-02-29 12:34:04 -08007643 ArrayList<PreferredActivity> removed = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007644 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
7645 while (it.hasNext()) {
7646 PreferredActivity pa = it.next();
Dianne Hackbornf8b8a3f2011-03-04 00:05:31 -08007647 if (pa.mPref.mComponent.getPackageName().equals(packageName)) {
Dianne Hackborn04505102012-02-29 12:34:04 -08007648 if (removed == null) {
7649 removed = new ArrayList<PreferredActivity>();
7650 }
7651 removed.add(pa);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007652 }
7653 }
Dianne Hackborn04505102012-02-29 12:34:04 -08007654 if (removed != null) {
7655 for (int i=0; i<removed.size(); i++) {
7656 PreferredActivity pa = removed.get(i);
7657 mSettings.mPreferredActivities.removeFilter(pa);
7658 }
7659 return true;
7660 }
7661 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007662 }
7663
7664 public int getPreferredActivities(List<IntentFilter> outFilters,
7665 List<ComponentName> outActivities, String packageName) {
7666
7667 int num = 0;
Kenny Root447106f2011-03-23 11:00:15 -07007668 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007669 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07007670 final Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007671 while (it.hasNext()) {
Kenny Root447106f2011-03-23 11:00:15 -07007672 final PreferredActivity pa = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007673 if (packageName == null
Dianne Hackbornf8b8a3f2011-03-04 00:05:31 -08007674 || pa.mPref.mComponent.getPackageName().equals(packageName)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007675 if (outFilters != null) {
7676 outFilters.add(new IntentFilter(pa));
7677 }
7678 if (outActivities != null) {
Dianne Hackbornf8b8a3f2011-03-04 00:05:31 -08007679 outActivities.add(pa.mPref.mComponent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007680 }
7681 }
7682 }
7683 }
7684
7685 return num;
7686 }
7687
7688 public void setApplicationEnabledSetting(String appPackageName,
7689 int newState, int flags) {
7690 setEnabledSetting(appPackageName, null, newState, flags);
7691 }
7692
7693 public void setComponentEnabledSetting(ComponentName componentName,
7694 int newState, int flags) {
7695 setEnabledSetting(componentName.getPackageName(),
7696 componentName.getClassName(), newState, flags);
7697 }
7698
7699 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007700 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007701 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
7702 || newState == COMPONENT_ENABLED_STATE_ENABLED
Dianne Hackborn0ac30312011-06-17 14:49:23 -07007703 || newState == COMPONENT_ENABLED_STATE_DISABLED
7704 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007705 throw new IllegalArgumentException("Invalid new component state: "
7706 + newState);
7707 }
7708 PackageSetting pkgSetting;
7709 final int uid = Binder.getCallingUid();
7710 final int permission = mContext.checkCallingPermission(
7711 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
7712 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007713 boolean sendNow = false;
7714 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08007715 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007716 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08007717 ArrayList<String> components;
Kenny Root447106f2011-03-23 11:00:15 -07007718
7719 // writer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007720 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007721 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007722 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007723 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007724 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007725 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007726 }
7727 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007728 "Unknown component: " + packageName
7729 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007730 }
Amith Yamasani742a6712011-05-04 14:49:28 -07007731 if (!allowedByPermission && (!UserId.isSameApp(uid, pkgSetting.userId))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007732 throw new SecurityException(
7733 "Permission Denial: attempt to change component state from pid="
7734 + Binder.getCallingPid()
7735 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
7736 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007737 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007738 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007739 if (pkgSetting.enabled == newState) {
7740 // Nothing to do
7741 return;
7742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007743 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07007744 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007745 } else {
7746 // We're dealing with a component level state change
Dianne Hackborn65696252012-03-05 18:49:21 -08007747 // First, verify that this is a valid class name.
7748 PackageParser.Package pkg = pkgSetting.pkg;
7749 if (pkg == null || !pkg.hasComponentClassName(className)) {
7750 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
7751 throw new IllegalArgumentException("Component class " + className
7752 + " does not exist in " + packageName);
7753 } else {
7754 Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
7755 + className + " does not exist in " + packageName);
7756 }
7757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007758 switch (newState) {
7759 case COMPONENT_ENABLED_STATE_ENABLED:
Kenny Root447106f2011-03-23 11:00:15 -07007760 if (!pkgSetting.enableComponentLPw(className)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007761 return;
7762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007763 break;
7764 case COMPONENT_ENABLED_STATE_DISABLED:
Kenny Root447106f2011-03-23 11:00:15 -07007765 if (!pkgSetting.disableComponentLPw(className)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007766 return;
7767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007768 break;
7769 case COMPONENT_ENABLED_STATE_DEFAULT:
Kenny Root447106f2011-03-23 11:00:15 -07007770 if (!pkgSetting.restoreComponentLPw(className)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007771 return;
7772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007773 break;
7774 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007775 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007776 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007777 }
7778 }
Kenny Root447106f2011-03-23 11:00:15 -07007779 mSettings.writeLPr();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007780 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08007781 components = mPendingBroadcasts.get(packageName);
Kenny Root447106f2011-03-23 11:00:15 -07007782 final boolean newPackage = components == null;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08007783 if (newPackage) {
7784 components = new ArrayList<String>();
7785 }
7786 if (!components.contains(componentName)) {
7787 components.add(componentName);
7788 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007789 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
7790 sendNow = true;
7791 // Purge entry from pending broadcast list if another one exists already
7792 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08007793 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007794 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08007795 if (newPackage) {
7796 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007797 }
7798 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
7799 // Schedule a message
7800 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
7801 }
7802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007803 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007805 long callingId = Binder.clearCallingIdentity();
7806 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007807 if (sendNow) {
7808 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08007809 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007810 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007811 } finally {
7812 Binder.restoreCallingIdentity(callingId);
7813 }
7814 }
7815
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007816 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08007817 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
Kenny Root4dfe6ff2011-02-23 17:00:43 -08007818 if (DEBUG_INSTALL)
7819 Log.v(TAG, "Sending package changed: package=" + packageName + " components="
7820 + componentNames);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08007821 Bundle extras = new Bundle(4);
7822 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
7823 String nameList[] = new String[componentNames.size()];
7824 componentNames.toArray(nameList);
7825 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007826 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
7827 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007828 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null);
7829 }
7830
7831 public void setPackageStoppedState(String packageName, boolean stopped) {
Dianne Hackborne7f97212011-02-24 14:40:20 -08007832 final int uid = Binder.getCallingUid();
7833 final int permission = mContext.checkCallingOrSelfPermission(
7834 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
7835 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root447106f2011-03-23 11:00:15 -07007836 // writer
Dianne Hackborne7f97212011-02-24 14:40:20 -08007837 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07007838 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
7839 uid)) {
Dianne Hackborne7f97212011-02-24 14:40:20 -08007840 scheduleWriteStoppedPackagesLocked();
7841 }
7842 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007843 }
7844
Jacek Surazski65e13172009-04-28 15:26:38 +02007845 public String getInstallerPackageName(String packageName) {
Kenny Root447106f2011-03-23 11:00:15 -07007846 // reader
Jacek Surazski65e13172009-04-28 15:26:38 +02007847 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07007848 return mSettings.getInstallerPackageNameLPr(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02007849 }
7850 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007851
Kenny Root447106f2011-03-23 11:00:15 -07007852 public int getApplicationEnabledSetting(String packageName) {
7853 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007854 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07007855 return mSettings.getApplicationEnabledSettingLPr(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007856 }
7857 }
7858
7859 public int getComponentEnabledSetting(ComponentName componentName) {
Kenny Root447106f2011-03-23 11:00:15 -07007860 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007861 synchronized (mPackages) {
Kenny Root447106f2011-03-23 11:00:15 -07007862 return mSettings.getComponentEnabledSettingLPr(componentName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007863 }
7864 }
7865
7866 public void enterSafeMode() {
Kenny Root461ff1f2011-08-09 09:43:03 -07007867 enforceSystemOrRoot("Only the system can request entering safe mode");
7868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007869 if (!mSystemReady) {
7870 mSafeMode = true;
7871 }
7872 }
7873
7874 public void systemReady() {
7875 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007876
7877 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07007878 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007879 mContext.getContentResolver(),
7880 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07007881 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007882 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07007883 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007885 }
7886
7887 public boolean isSafeMode() {
7888 return mSafeMode;
7889 }
7890
7891 public boolean hasSystemUidErrors() {
7892 return mHasSystemUidErrors;
7893 }
7894
7895 static String arrayToString(int[] array) {
7896 StringBuffer buf = new StringBuffer(128);
7897 buf.append('[');
7898 if (array != null) {
7899 for (int i=0; i<array.length; i++) {
7900 if (i > 0) buf.append(", ");
7901 buf.append(array[i]);
7902 }
7903 }
7904 buf.append(']');
7905 return buf.toString();
7906 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007907
Kenny Root447106f2011-03-23 11:00:15 -07007908 static class DumpState {
7909 public static final int DUMP_LIBS = 1 << 0;
7910
7911 public static final int DUMP_FEATURES = 1 << 1;
7912
7913 public static final int DUMP_RESOLVERS = 1 << 2;
7914
7915 public static final int DUMP_PERMISSIONS = 1 << 3;
7916
7917 public static final int DUMP_PACKAGES = 1 << 4;
7918
7919 public static final int DUMP_SHARED_USERS = 1 << 5;
7920
7921 public static final int DUMP_MESSAGES = 1 << 6;
7922
7923 public static final int DUMP_PROVIDERS = 1 << 7;
7924
Kenny Root05ca4c92011-09-15 10:36:25 -07007925 public static final int DUMP_VERIFIERS = 1 << 8;
7926
Kenny Root447106f2011-03-23 11:00:15 -07007927 public static final int OPTION_SHOW_FILTERS = 1 << 0;
7928
7929 private int mTypes;
7930
7931 private int mOptions;
7932
7933 private boolean mTitlePrinted;
7934
7935 private SharedUserSetting mSharedUser;
7936
7937 public boolean isDumping(int type) {
7938 if (mTypes == 0) {
7939 return true;
7940 }
7941
7942 return (mTypes & type) != 0;
7943 }
7944
7945 public void setDump(int type) {
7946 mTypes |= type;
7947 }
7948
7949 public boolean isOptionEnabled(int option) {
7950 return (mOptions & option) != 0;
7951 }
7952
7953 public void setOptionEnabled(int option) {
7954 mOptions |= option;
7955 }
7956
7957 public boolean onTitlePrinted() {
7958 final boolean printed = mTitlePrinted;
7959 mTitlePrinted = true;
7960 return printed;
7961 }
7962
7963 public boolean getTitlePrinted() {
7964 return mTitlePrinted;
7965 }
7966
7967 public void setTitlePrinted(boolean enabled) {
7968 mTitlePrinted = enabled;
7969 }
7970
7971 public SharedUserSetting getSharedUser() {
7972 return mSharedUser;
7973 }
7974
7975 public void setSharedUser(SharedUserSetting user) {
7976 mSharedUser = user;
7977 }
7978 }
7979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007980 @Override
7981 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
7982 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
7983 != PackageManager.PERMISSION_GRANTED) {
7984 pw.println("Permission Denial: can't dump ActivityManager from from pid="
7985 + Binder.getCallingPid()
7986 + ", uid=" + Binder.getCallingUid()
7987 + " without permission "
7988 + android.Manifest.permission.DUMP);
7989 return;
7990 }
7991
Kenny Root447106f2011-03-23 11:00:15 -07007992 DumpState dumpState = new DumpState();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007993
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007994 String packageName = null;
7995
7996 int opti = 0;
7997 while (opti < args.length) {
7998 String opt = args[opti];
7999 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8000 break;
8001 }
8002 opti++;
8003 if ("-a".equals(opt)) {
8004 // Right now we only know how to print all.
8005 } else if ("-h".equals(opt)) {
8006 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008007 pw.println(" [-h] [-f] [cmd] ...");
8008 pw.println(" -f: print details of intent filters");
8009 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008010 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008011 pw.println(" l[ibraries]: list known shared libraries");
8012 pw.println(" f[ibraries]: list device features");
8013 pw.println(" r[esolvers]: dump intent resolvers");
8014 pw.println(" perm[issions]: dump permissions");
8015 pw.println(" prov[iders]: dump content providers");
8016 pw.println(" p[ackages]: dump installed packages");
8017 pw.println(" s[hared-users]: dump shared user IDs");
8018 pw.println(" m[essages]: print collected runtime messages");
Kenny Root05ca4c92011-09-15 10:36:25 -07008019 pw.println(" v[erifiers]: print package verifier info");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008020 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008021 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008022 } else if ("-f".equals(opt)) {
Kenny Root447106f2011-03-23 11:00:15 -07008023 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008024 } else {
8025 pw.println("Unknown argument: " + opt + "; use -h for help");
8026 }
8027 }
8028
8029 // Is the caller requesting to dump a particular piece of data?
8030 if (opti < args.length) {
8031 String cmd = args[opti];
8032 opti++;
8033 // Is this a package name?
8034 if ("android".equals(cmd) || cmd.contains(".")) {
8035 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008036 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07008037 dumpState.setDump(DumpState.DUMP_LIBS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008038 } else if ("f".equals(cmd) || "features".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07008039 dumpState.setDump(DumpState.DUMP_FEATURES);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008040 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07008041 dumpState.setDump(DumpState.DUMP_RESOLVERS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008042 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07008043 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008044 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07008045 dumpState.setDump(DumpState.DUMP_PACKAGES);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008046 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07008047 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008048 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07008049 dumpState.setDump(DumpState.DUMP_PROVIDERS);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008050 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
Kenny Root447106f2011-03-23 11:00:15 -07008051 dumpState.setDump(DumpState.DUMP_MESSAGES);
Kenny Root05ca4c92011-09-15 10:36:25 -07008052 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
8053 dumpState.setDump(DumpState.DUMP_VERIFIERS);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008054 }
8055 }
Kenny Root447106f2011-03-23 11:00:15 -07008056
8057 // reader
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008058 synchronized (mPackages) {
Kenny Root05ca4c92011-09-15 10:36:25 -07008059 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
8060 if (dumpState.onTitlePrinted())
8061 pw.println(" ");
8062 pw.println("Verifiers:");
8063 pw.print(" Required: ");
8064 pw.print(mRequiredVerifierPackage);
8065 pw.print(" (uid=");
8066 pw.print(getPackageUid(mRequiredVerifierPackage));
8067 pw.println(")");
8068 }
8069
Kenny Root447106f2011-03-23 11:00:15 -07008070 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
8071 if (dumpState.onTitlePrinted())
8072 pw.println(" ");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008073 pw.println("Libraries:");
Kenny Root447106f2011-03-23 11:00:15 -07008074 final Iterator<String> it = mSharedLibraries.keySet().iterator();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008075 while (it.hasNext()) {
8076 String name = it.next();
8077 pw.print(" ");
8078 pw.print(name);
8079 pw.print(" -> ");
8080 pw.println(mSharedLibraries.get(name));
8081 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008082 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008083
Kenny Root447106f2011-03-23 11:00:15 -07008084 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
8085 if (dumpState.onTitlePrinted())
8086 pw.println(" ");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008087 pw.println("Features:");
8088 Iterator<String> it = mAvailableFeatures.keySet().iterator();
8089 while (it.hasNext()) {
8090 String name = it.next();
8091 pw.print(" ");
8092 pw.println(name);
8093 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008094 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008095
Kenny Root447106f2011-03-23 11:00:15 -07008096 if (dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
8097 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
8098 : "Activity Resolver Table:", " ", packageName,
8099 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
8100 dumpState.setTitlePrinted(true);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008101 }
Kenny Root447106f2011-03-23 11:00:15 -07008102 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
8103 : "Receiver Resolver Table:", " ", packageName,
8104 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
8105 dumpState.setTitlePrinted(true);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008106 }
Kenny Root447106f2011-03-23 11:00:15 -07008107 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
8108 : "Service Resolver Table:", " ", packageName,
8109 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
8110 dumpState.setTitlePrinted(true);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008111 }
Kenny Root447106f2011-03-23 11:00:15 -07008112 if (mSettings.mPreferredActivities.dump(pw,
8113 dumpState.getTitlePrinted() ? "\nPreferred Activities:"
8114 : "Preferred Activities:", " ",
8115 packageName, dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
8116 dumpState.setTitlePrinted(true);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008117 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008118 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008119
Kenny Root447106f2011-03-23 11:00:15 -07008120 if (dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
8121 mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008122 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008123
Kenny Root447106f2011-03-23 11:00:15 -07008124 if (dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
8125 boolean printedSomething = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008126 for (PackageParser.Provider p : mProvidersByComponent.values()) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008127 if (packageName != null && !packageName.equals(p.info.packageName)) {
8128 continue;
8129 }
8130 if (!printedSomething) {
Kenny Root447106f2011-03-23 11:00:15 -07008131 if (dumpState.onTitlePrinted())
8132 pw.println(" ");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008133 pw.println("Registered ContentProviders:");
8134 printedSomething = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008135 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008136 pw.print(" "); pw.print(p.getComponentShortName()); pw.println(":");
8137 pw.print(" "); pw.println(p.toString());
8138 }
8139 printedSomething = false;
8140 for (Map.Entry<String, PackageParser.Provider> entry : mProviders.entrySet()) {
8141 PackageParser.Provider p = entry.getValue();
8142 if (packageName != null && !packageName.equals(p.info.packageName)) {
8143 continue;
8144 }
8145 if (!printedSomething) {
8146 if (dumpState.onTitlePrinted())
8147 pw.println(" ");
8148 pw.println("ContentProvider Authorities:");
8149 printedSomething = true;
8150 }
8151 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:");
8152 pw.print(" "); pw.println(p.toString());
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008153 }
8154 }
8155
Kenny Root447106f2011-03-23 11:00:15 -07008156 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
8157 mSettings.dumpPackagesLPr(pw, packageName, dumpState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008158 }
Kenny Root447106f2011-03-23 11:00:15 -07008159
8160 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
8161 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008162 }
Kenny Root447106f2011-03-23 11:00:15 -07008163
8164 if (dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
8165 if (dumpState.onTitlePrinted())
8166 pw.println(" ");
8167 mSettings.dumpReadMessagesLPr(pw, dumpState);
8168
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008169 pw.println(" ");
8170 pw.println("Package warning messages:");
Kenny Root447106f2011-03-23 11:00:15 -07008171 final File fname = getSettingsProblemFile();
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -08008172 FileInputStream in = null;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008173 try {
8174 in = new FileInputStream(fname);
Kenny Root447106f2011-03-23 11:00:15 -07008175 final int avail = in.available();
8176 final byte[] data = new byte[avail];
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008177 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008178 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008179 } catch (FileNotFoundException e) {
8180 } catch (IOException e) {
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -08008181 } finally {
8182 if (in != null) {
8183 try {
8184 in.close();
Kenny Root447106f2011-03-23 11:00:15 -07008185 } catch (IOException e) {
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -08008186 }
8187 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008188 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008190 }
8191 }
8192
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008193 // ------- apps on sdcard specific code -------
8194 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root447106f2011-03-23 11:00:15 -07008195
Kenny Root305bcbf2010-09-03 07:56:38 -07008196 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
Kenny Root447106f2011-03-23 11:00:15 -07008197
Kenny Root305bcbf2010-09-03 07:56:38 -07008198 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
Kenny Root447106f2011-03-23 11:00:15 -07008199
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008200 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008201
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008202 private String getEncryptKey() {
8203 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07008204 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
8205 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008206 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07008207 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
8208 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008209 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008210 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008211 return null;
8212 }
8213 }
8214 return sdEncKey;
8215 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008216 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008217 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07008218 } catch (IOException ioe) {
Kenny Root447106f2011-03-23 11:00:15 -07008219 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
Rich Cannings8d578832010-09-09 15:12:40 -07008220 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008221 }
Rich Cannings8d578832010-09-09 15:12:40 -07008222
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008223 }
8224
Kenny Root447106f2011-03-23 11:00:15 -07008225 /* package */static String getTempContainerId() {
Kenny Rootc78a8072010-07-27 15:18:38 -07008226 int tmpIdx = 1;
8227 String list[] = PackageHelper.getSecureContainerList();
8228 if (list != null) {
8229 for (final String name : list) {
8230 // Ignore null and non-temporary container entries
8231 if (name == null || !name.startsWith(mTempContainerPrefix)) {
8232 continue;
8233 }
8234
8235 String subStr = name.substring(mTempContainerPrefix.length());
8236 try {
8237 int cid = Integer.parseInt(subStr);
8238 if (cid >= tmpIdx) {
8239 tmpIdx = cid + 1;
8240 }
8241 } catch (NumberFormatException e) {
8242 }
8243 }
8244 }
8245 return mTempContainerPrefix + tmpIdx;
8246 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008247
Kenny Root447106f2011-03-23 11:00:15 -07008248 /*
8249 * Update media status on PackageManager.
8250 */
8251 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
8252 int callingUid = Binder.getCallingUid();
8253 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
8254 throw new SecurityException("Media status can only be updated by the system");
8255 }
8256 // reader; this apparently protects mMediaMounted, but should probably
8257 // be a different lock in that case.
8258 synchronized (mPackages) {
8259 Log.i(TAG, "Updating external media status from "
8260 + (mMediaMounted ? "mounted" : "unmounted") + " to "
8261 + (mediaStatus ? "mounted" : "unmounted"));
8262 if (DEBUG_SD_INSTALL)
8263 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
8264 + ", mMediaMounted=" + mMediaMounted);
8265 if (mediaStatus == mMediaMounted) {
8266 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
8267 : 0, -1);
8268 mHandler.sendMessage(msg);
8269 return;
8270 }
8271 mMediaMounted = mediaStatus;
8272 }
8273 // Queue up an async operation since the package installation may take a
8274 // little while.
8275 mHandler.post(new Runnable() {
8276 public void run() {
8277 // TODO fix this; this does nothing.
8278 mHandler.removeCallbacks(this);
8279 updateExternalMediaStatusInner(mediaStatus, reportStatus);
8280 }
8281 });
8282 }
8283
8284 /*
8285 * Collect information of applications on external media, map them against
8286 * existing containers and update information based on current mount status.
8287 * Please note that we always have to report status if reportStatus has been
8288 * set to true especially when unloading packages.
8289 */
8290 private void updateExternalMediaStatusInner(boolean mediaStatus, boolean reportStatus) {
8291 // Collection of uids
8292 int uidArr[] = null;
8293 // Collection of stale containers
8294 HashSet<String> removeCids = new HashSet<String>();
8295 // Collection of packages on external media with valid containers.
8296 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
8297 // Get list of secure containers.
8298 final String list[] = PackageHelper.getSecureContainerList();
8299 if (list == null || list.length == 0) {
8300 Log.i(TAG, "No secure containers on sdcard");
8301 } else {
8302 // Process list of secure containers and categorize them
8303 // as active or stale based on their package internal state.
8304 int uidList[] = new int[list.length];
8305 int num = 0;
8306 // reader
8307 synchronized (mPackages) {
8308 for (String cid : list) {
8309 SdInstallArgs args = new SdInstallArgs(cid);
8310 if (DEBUG_SD_INSTALL)
8311 Log.i(TAG, "Processing container " + cid);
8312 String pkgName = args.getPackageName();
8313 if (pkgName == null) {
8314 if (DEBUG_SD_INSTALL)
8315 Log.i(TAG, "Container : " + cid + " stale");
8316 removeCids.add(cid);
8317 continue;
8318 }
8319 if (DEBUG_SD_INSTALL)
8320 Log.i(TAG, "Looking for pkg : " + pkgName);
8321 PackageSetting ps = mSettings.mPackages.get(pkgName);
8322 // The package status is changed only if the code path
8323 // matches between settings and the container id.
8324 if (ps != null && ps.codePathString != null
8325 && ps.codePathString.equals(args.getCodePath())) {
8326 if (DEBUG_SD_INSTALL)
8327 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
8328 + " at code path: " + ps.codePathString);
8329 // We do have a valid package installed on sdcard
8330 processCids.put(args, ps.codePathString);
8331 int uid = ps.userId;
8332 if (uid != -1) {
8333 uidList[num++] = uid;
8334 }
8335 } else {
8336 // Stale container on sdcard. Just delete
8337 if (DEBUG_SD_INSTALL)
8338 Log.i(TAG, "Container : " + cid + " stale");
8339 removeCids.add(cid);
8340 }
8341 }
8342 }
8343
8344 if (num > 0) {
8345 // Sort uid list
8346 Arrays.sort(uidList, 0, num);
8347 // Throw away duplicates
8348 uidArr = new int[num];
8349 uidArr[0] = uidList[0];
8350 int di = 0;
8351 for (int i = 1; i < num; i++) {
8352 if (uidList[i - 1] != uidList[i]) {
8353 uidArr[di++] = uidList[i];
8354 }
8355 }
8356 }
8357 }
8358 // Process packages with valid entries.
8359 if (mediaStatus) {
8360 if (DEBUG_SD_INSTALL)
8361 Log.i(TAG, "Loading packages");
8362 loadMediaPackages(processCids, uidArr, removeCids);
8363 startCleaningPackages();
8364 } else {
8365 if (DEBUG_SD_INSTALL)
8366 Log.i(TAG, "Unloading packages");
8367 unloadMediaPackages(processCids, uidArr, reportStatus);
8368 }
8369 }
8370
8371 private void sendResourcesChangedBroadcast(boolean mediaStatus, ArrayList<String> pkgList,
8372 int uidArr[], IIntentReceiver finishedReceiver) {
8373 int size = pkgList.size();
8374 if (size > 0) {
8375 // Send broadcasts here
8376 Bundle extras = new Bundle();
8377 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
8378 .toArray(new String[size]));
8379 if (uidArr != null) {
8380 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
8381 }
8382 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
8383 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
8384 sendPackageBroadcast(action, null, extras, null, finishedReceiver);
8385 }
8386 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008387
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07008388 /*
Kenny Root447106f2011-03-23 11:00:15 -07008389 * Look at potentially valid container ids from processCids If package
8390 * information doesn't match the one on record or package scanning fails,
8391 * the cid is added to list of removeCids. We currently don't delete stale
8392 * containers.
8393 */
8394 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[],
8395 HashSet<String> removeCids) {
8396 ArrayList<String> pkgList = new ArrayList<String>();
8397 Set<SdInstallArgs> keys = processCids.keySet();
8398 boolean doGc = false;
8399 for (SdInstallArgs args : keys) {
8400 String codePath = processCids.get(args);
8401 if (DEBUG_SD_INSTALL)
8402 Log.i(TAG, "Loading container : " + args.cid);
8403 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8404 try {
8405 // Make sure there are no container errors first.
8406 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
8407 Slog.e(TAG, "Failed to mount cid : " + args.cid
8408 + " when installing from sdcard");
8409 continue;
8410 }
8411 // Check code path here.
8412 if (codePath == null || !codePath.equals(args.getCodePath())) {
8413 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
8414 + " does not match one in settings " + codePath);
8415 continue;
8416 }
8417 // Parse package
8418 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
8419 doGc = true;
8420 synchronized (mInstallLock) {
8421 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
8422 0, 0);
8423 // Scan the package
8424 if (pkg != null) {
8425 /*
8426 * TODO why is the lock being held? doPostInstall is
8427 * called in other places without the lock. This needs
8428 * to be straightened out.
8429 */
8430 // writer
8431 synchronized (mPackages) {
8432 retCode = PackageManager.INSTALL_SUCCEEDED;
8433 pkgList.add(pkg.packageName);
8434 // Post process args
8435 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
8436 }
8437 } else {
8438 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard");
8439 }
8440 }
8441
8442 } finally {
8443 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
8444 // Don't destroy container here. Wait till gc clears things
8445 // up.
8446 removeCids.add(args.cid);
8447 }
8448 }
8449 }
8450 // writer
8451 synchronized (mPackages) {
8452 // If the platform SDK has changed since the last time we booted,
8453 // we need to re-grant app permission to catch any new ones that
8454 // appear. This is really a hack, and means that apps can in some
8455 // cases get permissions that the user didn't initially explicitly
8456 // allow... it would be nice to have some better way to handle
8457 // this situation.
8458 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
8459 if (regrantPermissions)
8460 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
8461 + mSdkVersion + "; regranting permissions for external storage");
8462 mSettings.mExternalSdkPlatform = mSdkVersion;
8463
8464 // Make sure group IDs have been assigned, and any permission
8465 // changes in other apps are accounted for
Dianne Hackborne639da72012-02-21 15:11:13 -08008466 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
8467 | (regrantPermissions
8468 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
8469 : 0));
Kenny Root447106f2011-03-23 11:00:15 -07008470 // can downgrade to reader
8471 // Persist settings
8472 mSettings.writeLPr();
8473 }
8474 // Send a broadcast to let everyone know we are done processing
8475 if (pkgList.size() > 0) {
8476 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
8477 }
8478 // Force gc to avoid any stale parser references that we might have.
8479 if (doGc) {
8480 Runtime.getRuntime().gc();
8481 }
8482 // List stale containers and destroy stale temporary containers.
8483 if (removeCids != null) {
8484 for (String cid : removeCids) {
8485 if (cid.startsWith(mTempContainerPrefix)) {
8486 Log.i(TAG, "Destroying stale temporary container " + cid);
8487 PackageHelper.destroySdDir(cid);
8488 } else {
8489 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008490 }
8491 }
Kenny Root447106f2011-03-23 11:00:15 -07008492 }
8493 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008494
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08008495 /*
Kenny Root447106f2011-03-23 11:00:15 -07008496 * Utility method to unload a list of specified containers
8497 */
8498 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
8499 // Just unmount all valid containers.
8500 for (SdInstallArgs arg : cidArgs) {
8501 synchronized (mInstallLock) {
8502 arg.doPostDeleteLI(false);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08008503 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008504 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008505 }
8506
Kenny Root447106f2011-03-23 11:00:15 -07008507 /*
8508 * Unload packages mounted on external media. This involves deleting package
8509 * data from internal structures, sending broadcasts about diabled packages,
8510 * gc'ing to free up references, unmounting all secure containers
8511 * corresponding to packages on external media, and posting a
8512 * UPDATED_MEDIA_STATUS message if status has been requested. Please note
8513 * that we always have to post this message if status has been requested no
8514 * matter what.
8515 */
8516 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[],
8517 final boolean reportStatus) {
8518 if (DEBUG_SD_INSTALL)
8519 Log.i(TAG, "unloading media packages");
8520 ArrayList<String> pkgList = new ArrayList<String>();
8521 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
8522 final Set<SdInstallArgs> keys = processCids.keySet();
8523 for (SdInstallArgs args : keys) {
8524 String pkgName = args.getPackageName();
8525 if (DEBUG_SD_INSTALL)
8526 Log.i(TAG, "Trying to unload pkg : " + pkgName);
8527 // Delete package internally
8528 PackageRemovedInfo outInfo = new PackageRemovedInfo();
8529 synchronized (mInstallLock) {
8530 boolean res = deletePackageLI(pkgName, false, PackageManager.DONT_DELETE_DATA,
8531 outInfo, false);
8532 if (res) {
8533 pkgList.add(pkgName);
8534 } else {
8535 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
8536 failedList.add(args);
8537 }
8538 }
8539 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07008540
Kenny Root447106f2011-03-23 11:00:15 -07008541 // reader
8542 synchronized (mPackages) {
8543 // We didn't update the settings after removing each package;
8544 // write them now for all packages.
8545 mSettings.writeLPr();
8546 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008547
Kenny Root447106f2011-03-23 11:00:15 -07008548 // We have to absolutely send UPDATED_MEDIA_STATUS only
8549 // after confirming that all the receivers processed the ordered
8550 // broadcast when packages get disabled, force a gc to clean things up.
8551 // and unload all the containers.
8552 if (pkgList.size() > 0) {
8553 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
8554 public void performReceive(Intent intent, int resultCode, String data,
8555 Bundle extras, boolean ordered, boolean sticky) throws RemoteException {
8556 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
8557 reportStatus ? 1 : 0, 1, keys);
8558 mHandler.sendMessage(msg);
8559 }
8560 });
8561 } else {
8562 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
8563 keys);
8564 mHandler.sendMessage(msg);
8565 }
8566 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07008567
Kenny Root447106f2011-03-23 11:00:15 -07008568 public void movePackage(final String packageName, final IPackageMoveObserver observer,
8569 final int flags) {
8570 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
8571 int returnCode = PackageManager.MOVE_SUCCEEDED;
8572 int currFlags = 0;
8573 int newFlags = 0;
8574 // reader
8575 synchronized (mPackages) {
8576 PackageParser.Package pkg = mPackages.get(packageName);
8577 if (pkg == null) {
8578 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
8579 } else {
8580 // Disable moving fwd locked apps and system packages
8581 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
8582 Slog.w(TAG, "Cannot move system application");
8583 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
8584 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
8585 Slog.w(TAG, "Cannot move forward locked app.");
8586 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
8587 } else if (pkg.mOperationPending) {
8588 Slog.w(TAG, "Attempt to move package which has pending operations");
8589 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
8590 } else {
8591 // Find install location first
8592 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
8593 && (flags & PackageManager.MOVE_INTERNAL) != 0) {
8594 Slog.w(TAG, "Ambigous flags specified for move location.");
8595 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
8596 } else {
8597 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
8598 : PackageManager.INSTALL_INTERNAL;
8599 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
8600 : PackageManager.INSTALL_INTERNAL;
8601 if (newFlags == currFlags) {
8602 Slog.w(TAG, "No move required. Trying to move to same location");
8603 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
8604 }
8605 }
8606 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
8607 pkg.mOperationPending = true;
8608 }
8609 }
8610 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08008611
Kenny Root447106f2011-03-23 11:00:15 -07008612 /*
8613 * TODO this next block probably shouldn't be inside the lock. We
8614 * can't guarantee these won't change after this is fired off
8615 * anyway.
8616 */
8617 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -07008618 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Kenny Root447106f2011-03-23 11:00:15 -07008619 } else {
8620 Message msg = mHandler.obtainMessage(INIT_COPY);
8621 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -07008622 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
Kenny Root447106f2011-03-23 11:00:15 -07008623 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
Kenny Root85387d72010-08-26 10:13:11 -07008624 pkg.applicationInfo.dataDir);
Kenny Root447106f2011-03-23 11:00:15 -07008625 msg.obj = mp;
8626 mHandler.sendMessage(msg);
8627 }
8628 }
8629 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08008630
Kenny Root447106f2011-03-23 11:00:15 -07008631 private void processPendingMove(final MoveParams mp, final int currentStatus) {
8632 // Queue up an async operation since the package deletion may take a
8633 // little while.
8634 mHandler.post(new Runnable() {
8635 public void run() {
8636 // TODO fix this; this does nothing.
8637 mHandler.removeCallbacks(this);
8638 int returnCode = currentStatus;
8639 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
8640 int uidArr[] = null;
8641 ArrayList<String> pkgList = null;
8642 synchronized (mPackages) {
8643 PackageParser.Package pkg = mPackages.get(mp.packageName);
8644 if (pkg == null) {
8645 Slog.w(TAG, " Package " + mp.packageName
8646 + " doesn't exist. Aborting move");
8647 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
8648 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
8649 Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
8650 + mp.srcArgs.getCodePath() + " to "
8651 + pkg.applicationInfo.sourceDir
8652 + " Aborting move and returning error");
8653 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8654 } else {
8655 uidArr = new int[] {
8656 pkg.applicationInfo.uid
8657 };
8658 pkgList = new ArrayList<String>();
8659 pkgList.add(mp.packageName);
8660 }
8661 }
8662 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
8663 // Send resources unavailable broadcast
8664 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
8665 // Update package code and resource paths
8666 synchronized (mInstallLock) {
8667 synchronized (mPackages) {
8668 PackageParser.Package pkg = mPackages.get(mp.packageName);
8669 // Recheck for package again.
Kenny Root6a6b0072010-10-07 16:46:10 -07008670 if (pkg == null) {
8671 Slog.w(TAG, " Package " + mp.packageName
8672 + " doesn't exist. Aborting move");
8673 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Kenny Root447106f2011-03-23 11:00:15 -07008674 } else if (!mp.srcArgs.getCodePath().equals(
8675 pkg.applicationInfo.sourceDir)) {
8676 Slog.w(TAG, "Package " + mp.packageName
8677 + " code path changed from " + mp.srcArgs.getCodePath()
8678 + " to " + pkg.applicationInfo.sourceDir
8679 + " Aborting move and returning error");
8680 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8681 } else {
8682 final String oldCodePath = pkg.mPath;
8683 final String newCodePath = mp.targetArgs.getCodePath();
8684 final String newResPath = mp.targetArgs.getResourcePath();
8685 final String newNativePath = mp.targetArgs
8686 .getNativeLibraryPath();
Kenny Root6a6b0072010-10-07 16:46:10 -07008687
8688 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) == 0) {
8689 if (mInstaller
8690 .unlinkNativeLibraryDirectory(pkg.applicationInfo.dataDir) < 0) {
8691 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8692 } else {
Kenny Root66269ea2011-07-12 14:14:01 -07008693 NativeLibraryHelper.copyNativeBinariesIfNeededLI(new File(
Kenny Root447106f2011-03-23 11:00:15 -07008694 newCodePath), new File(newNativePath));
Kenny Root6a6b0072010-10-07 16:46:10 -07008695 }
8696 } else {
8697 if (mInstaller.linkNativeLibraryDirectory(
8698 pkg.applicationInfo.dataDir, newNativePath) < 0) {
8699 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8700 }
8701 }
8702
8703 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
8704 pkg.mPath = newCodePath;
8705 // Move dex files around
8706 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
8707 // Moving of dex files failed. Set
8708 // error code and abort move.
8709 pkg.mPath = pkg.mScanPath;
8710 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8711 }
8712 }
8713
8714 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
Kenny Root447106f2011-03-23 11:00:15 -07008715 pkg.mScanPath = newCodePath;
8716 pkg.applicationInfo.sourceDir = newCodePath;
8717 pkg.applicationInfo.publicSourceDir = newResPath;
8718 pkg.applicationInfo.nativeLibraryDir = newNativePath;
8719 PackageSetting ps = (PackageSetting) pkg.mExtras;
8720 ps.codePath = new File(pkg.applicationInfo.sourceDir);
8721 ps.codePathString = ps.codePath.getPath();
8722 ps.resourcePath = new File(
8723 pkg.applicationInfo.publicSourceDir);
8724 ps.resourcePathString = ps.resourcePath.getPath();
8725 ps.nativeLibraryPathString = newNativePath;
8726 // Set the application info flag
8727 // correctly.
8728 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8729 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
8730 } else {
8731 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
8732 }
8733 ps.setFlags(pkg.applicationInfo.flags);
8734 mAppDirs.remove(oldCodePath);
8735 mAppDirs.put(newCodePath, pkg);
8736 // Persist settings
8737 mSettings.writeLPr();
8738 }
8739 }
8740 }
8741 }
8742 // Send resources available broadcast
8743 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
8744 }
8745 }
8746 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
8747 // Clean up failed installation
8748 if (mp.targetArgs != null) {
8749 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
8750 }
8751 } else {
8752 // Force a gc to clear things up.
8753 Runtime.getRuntime().gc();
8754 // Delete older code
8755 synchronized (mInstallLock) {
8756 mp.srcArgs.doPostDeleteLI(true);
8757 }
8758 }
Kenny Rootdeb11262010-08-02 11:36:21 -07008759
Kenny Root447106f2011-03-23 11:00:15 -07008760 // Allow more operations on this file if we didn't fail because
8761 // an operation was already pending for this package.
8762 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
8763 synchronized (mPackages) {
8764 PackageParser.Package pkg = mPackages.get(mp.packageName);
8765 if (pkg != null) {
8766 pkg.mOperationPending = false;
Kenny Rootdeb11262010-08-02 11:36:21 -07008767 }
8768 }
Kenny Root447106f2011-03-23 11:00:15 -07008769 }
Kenny Rootdeb11262010-08-02 11:36:21 -07008770
Kenny Root447106f2011-03-23 11:00:15 -07008771 IPackageMoveObserver observer = mp.observer;
8772 if (observer != null) {
8773 try {
8774 observer.packageMoved(mp.packageName, returnCode);
8775 } catch (RemoteException e) {
8776 Log.i(TAG, "Observer no longer exists.");
8777 }
8778 }
8779 }
8780 });
8781 }
8782
8783 public boolean setInstallLocation(int loc) {
8784 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
8785 null);
8786 if (getInstallLocation() == loc) {
8787 return true;
8788 }
8789 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
8790 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
8791 android.provider.Settings.System.putInt(mContext.getContentResolver(),
8792 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
8793 return true;
8794 }
8795 return false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08008796 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07008797
Kenny Root447106f2011-03-23 11:00:15 -07008798 public int getInstallLocation() {
8799 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
8800 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION,
8801 PackageHelper.APP_INSTALL_AUTO);
8802 }
Amith Yamasani0b285492011-04-14 17:35:23 -07008803
8804 public UserInfo createUser(String name, int flags) {
Kenny Root461ff1f2011-08-09 09:43:03 -07008805 // TODO(kroot): Add a real permission for creating users
8806 enforceSystemOrRoot("Only the system can create users");
8807
Kenny Roota51b6fd62011-05-19 15:02:18 -07008808 // TODO(kroot): fix this API
8809 UserInfo userInfo = mUserManager.createUser(name, flags, new ArrayList<ApplicationInfo>());
Amith Yamasani0b285492011-04-14 17:35:23 -07008810 return userInfo;
8811 }
8812
8813 public boolean removeUser(int userId) {
Kenny Root461ff1f2011-08-09 09:43:03 -07008814 // TODO(kroot): Add a real permission for removing users
8815 enforceSystemOrRoot("Only the system can remove users");
8816
Amith Yamasani0b285492011-04-14 17:35:23 -07008817 if (userId == 0) {
8818 return false;
8819 }
8820 mUserManager.removeUser(userId);
8821 return true;
8822 }
Kenny Root0aaa0d92011-09-12 16:42:55 -07008823
8824 @Override
8825 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
8826 mContext.enforceCallingOrSelfPermission(
8827 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8828 "Only package verification agents can read the verifier device identity");
8829
8830 synchronized (mPackages) {
8831 return mSettings.getVerifierDeviceIdentityLPw();
8832 }
8833 }
Amith Yamasani742a6712011-05-04 14:49:28 -07008834
8835 public List<UserInfo> getUsers() {
8836 return mUserManager.getUsers();
8837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008838}