blob: 139c05f120a68e9ee9415548858bcda25d416792 [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
17package com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080021import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080022import com.android.internal.util.FastXmlSerializer;
23import com.android.internal.util.XmlUtils;
David 'Digit' Turneradd13762010-02-03 17:34:58 -080024import com.android.server.JournaledFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025
26import org.xmlpull.v1.XmlPullParser;
27import org.xmlpull.v1.XmlPullParserException;
28import org.xmlpull.v1.XmlSerializer;
29
30import android.app.ActivityManagerNative;
31import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080032import android.app.admin.DevicePolicyManager;
33import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080034import android.app.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.content.Context;
37import android.content.Intent;
38import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070039import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080040import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070041import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.pm.ActivityInfo;
43import android.content.pm.ApplicationInfo;
44import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070045import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.pm.IPackageDataObserver;
47import android.content.pm.IPackageDeleteObserver;
48import android.content.pm.IPackageInstallObserver;
49import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080050import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.content.pm.IPackageStatsObserver;
52import android.content.pm.InstrumentationInfo;
53import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080054import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.content.pm.PackageManager;
56import android.content.pm.PackageStats;
57import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
59import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.content.pm.PackageParser;
61import android.content.pm.PermissionInfo;
62import android.content.pm.PermissionGroupInfo;
63import android.content.pm.ProviderInfo;
64import android.content.pm.ResolveInfo;
65import android.content.pm.ServiceInfo;
66import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.net.Uri;
68import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070069import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080071import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080073import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070074import android.os.Looper;
75import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.os.Parcel;
77import android.os.RemoteException;
78import android.os.Environment;
79import android.os.FileObserver;
80import android.os.FileUtils;
81import android.os.Handler;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080082import android.os.StatFs;
San Mehatb1043402010-02-05 08:26:50 -080083import android.os.storage.StorageResultCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.os.ParcelFileDescriptor;
85import android.os.Process;
86import android.os.ServiceManager;
87import android.os.SystemClock;
88import android.os.SystemProperties;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080089import android.provider.Settings;
Oscar Montemayord02546b2010-01-14 16:38:40 -080090import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.util.*;
92import android.view.Display;
93import android.view.WindowManager;
94
95import java.io.File;
96import java.io.FileDescriptor;
97import java.io.FileInputStream;
98import java.io.FileNotFoundException;
99import java.io.FileOutputStream;
100import java.io.FileReader;
101import java.io.FilenameFilter;
102import java.io.IOException;
103import java.io.InputStream;
104import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800105import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800106import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.ArrayList;
108import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700109import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.Collections;
111import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800112import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import java.util.Enumeration;
114import java.util.HashMap;
115import java.util.HashSet;
116import java.util.Iterator;
117import java.util.List;
118import java.util.Map;
119import java.util.Set;
120import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800121import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import java.util.zip.ZipFile;
123import java.util.zip.ZipOutputStream;
124
125class PackageManagerService extends IPackageManager.Stub {
126 private static final String TAG = "PackageManager";
127 private static final boolean DEBUG_SETTINGS = false;
128 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800129 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800130 private static final boolean DEBUG_INSTALL = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131
132 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
133 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400134 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 private static final int FIRST_APPLICATION_UID =
136 Process.FIRST_APPLICATION_UID;
137 private static final int MAX_APPLICATION_UIDS = 1000;
138
139 private static final boolean SHOW_INFO = false;
140
141 private static final boolean GET_CERTIFICATES = true;
142
Oscar Montemayora8529f62009-11-18 10:14:20 -0800143 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 private static final int REMOVE_EVENTS =
146 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
147 private static final int ADD_EVENTS =
148 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
149
150 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800151 // Suffix used during package installation when copying/moving
152 // package apks to install directory.
153 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800155 /**
156 * Indicates the state of installation. Used by PackageManager to
157 * figure out incomplete installations. Say a package is being installed
158 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
159 * the package installation is successful or unsuccesful lin which case
160 * the PackageManager will no longer maintain state information associated
161 * with the package. If some exception(like device freeze or battery being
162 * pulled out) occurs during installation of a package, the PackageManager
163 * needs this information to clean up the previously failed installation.
164 */
165 private static final int PKG_INSTALL_INCOMPLETE = 0;
166 private static final int PKG_INSTALL_COMPLETE = 1;
167
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 static final int SCAN_MONITOR = 1<<0;
169 static final int SCAN_NO_DEX = 1<<1;
170 static final int SCAN_FORCE_DEX = 1<<2;
171 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800172 static final int SCAN_NEW_INSTALL = 1<<4;
173 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800175 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
176 "com.android.defcontainer",
177 "com.android.defcontainer.DefaultContainerService");
178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
180 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700181 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182
Dianne Hackborn851a5412009-05-08 12:06:44 -0700183 final int mSdkVersion = Build.VERSION.SDK_INT;
184 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
185 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 final Context mContext;
188 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700189 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 final DisplayMetrics mMetrics;
191 final int mDefParseFlags;
192 final String[] mSeparateProcesses;
193
194 // This is where all application persistent data goes.
195 final File mAppDataDir;
196
Oscar Montemayora8529f62009-11-18 10:14:20 -0800197 // If Encrypted File System feature is enabled, all application persistent data
198 // should go here instead.
199 final File mSecureAppDataDir;
200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 // This is the object monitoring the framework dir.
202 final FileObserver mFrameworkInstallObserver;
203
204 // This is the object monitoring the system app dir.
205 final FileObserver mSystemInstallObserver;
206
207 // This is the object monitoring mAppInstallDir.
208 final FileObserver mAppInstallObserver;
209
210 // This is the object monitoring mDrmAppPrivateInstallDir.
211 final FileObserver mDrmAppInstallObserver;
212
213 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
214 // LOCK HELD. Can be called with mInstallLock held.
215 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 final File mFrameworkDir;
218 final File mSystemAppDir;
219 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700220 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221
222 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
223 // apps.
224 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 // Lock for state used when installing and doing other long running
229 // operations. Methods that must be called with this lock held have
230 // the prefix "LI".
231 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 // These are the directories in the 3rd party applications installed dir
234 // that we have currently loaded packages from. Keys are the application's
235 // installed zip file (absolute codePath), and values are Package.
236 final HashMap<String, PackageParser.Package> mAppDirs =
237 new HashMap<String, PackageParser.Package>();
238
239 // Information for the parser to write more useful error messages.
240 File mScanningPath;
241 int mLastScanError;
242
243 final int[] mOutPermissions = new int[3];
244
245 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 // Keys are String (package name), values are Package. This also serves
248 // as the lock for the global state. Methods that must be called with
249 // this lock held have the prefix "LP".
250 final HashMap<String, PackageParser.Package> mPackages =
251 new HashMap<String, PackageParser.Package>();
252
253 final Settings mSettings;
254 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255
256 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
257 int[] mGlobalGids;
258
259 // These are the built-in uid -> permission mappings that were read from the
260 // etc/permissions.xml file.
261 final SparseArray<HashSet<String>> mSystemPermissions =
262 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 // These are the built-in shared libraries that were read from the
265 // etc/permissions.xml file.
266 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800267
Dianne Hackborn49237342009-08-27 20:08:01 -0700268 // Temporary for building the final shared libraries for an .apk.
269 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800270
Dianne Hackborn49237342009-08-27 20:08:01 -0700271 // These are the features this devices supports that were read from the
272 // etc/permissions.xml file.
273 final HashMap<String, FeatureInfo> mAvailableFeatures =
274 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 // All available activities, for your resolving pleasure.
277 final ActivityIntentResolver mActivities =
278 new ActivityIntentResolver();
279
280 // All available receivers, for your resolving pleasure.
281 final ActivityIntentResolver mReceivers =
282 new ActivityIntentResolver();
283
284 // All available services, for your resolving pleasure.
285 final ServiceIntentResolver mServices = new ServiceIntentResolver();
286
287 // Keys are String (provider class name), values are Provider.
288 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
289 new HashMap<ComponentName, PackageParser.Provider>();
290
291 // Mapping from provider base names (first directory in content URI codePath)
292 // to the provider information.
293 final HashMap<String, PackageParser.Provider> mProviders =
294 new HashMap<String, PackageParser.Provider>();
295
296 // Mapping from instrumentation class names to info about them.
297 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
298 new HashMap<ComponentName, PackageParser.Instrumentation>();
299
300 // Mapping from permission names to info about them.
301 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
302 new HashMap<String, PackageParser.PermissionGroup>();
303
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800304 // Packages whose data we have transfered into another package, thus
305 // should no longer exist.
306 final HashSet<String> mTransferedPackages = new HashSet<String>();
307
Dianne Hackborn854060af2009-07-09 18:14:31 -0700308 // Broadcast actions that are only available to the system.
309 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 boolean mSystemReady;
312 boolean mSafeMode;
313 boolean mHasSystemUidErrors;
314
315 ApplicationInfo mAndroidApplication;
316 final ActivityInfo mResolveActivity = new ActivityInfo();
317 final ResolveInfo mResolveInfo = new ResolveInfo();
318 ComponentName mResolveComponentName;
319 PackageParser.Package mPlatformPackage;
320
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700321 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800322 final HashMap<String, ArrayList<String>> mPendingBroadcasts
323 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800324 // Service Connection to remote media container service to copy
325 // package uri's from external media onto secure containers
326 // or internal storage.
327 private IMediaContainerService mContainerService = null;
328
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700329 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800330 static final int MCS_BOUND = 3;
331 static final int END_COPY = 4;
332 static final int INIT_COPY = 5;
333 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800334 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800335 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800336 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800337 static final int MCS_RECONNECT = 10;
338 static final int MCS_GIVE_UP = 11;
339
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700340 // Delay time in millisecs
341 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800342 final private DefaultContainerConnection mDefContainerConn =
343 new DefaultContainerConnection();
344 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800345 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800346 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800347 IMediaContainerService imcs =
348 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800349 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800350 }
351
352 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800353 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800354 }
355 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700356
Christopher Tate1bb69062010-02-19 17:02:12 -0800357 // Recordkeeping of restore-after-install operations that are currently in flight
358 // between the Package Manager and the Backup Manager
359 class PostInstallData {
360 public InstallArgs args;
361 public PackageInstalledInfo res;
362
363 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
364 args = _a;
365 res = _r;
366 }
367 };
368 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
369 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
370
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700371 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800372 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800373 final ArrayList<HandlerParams> mPendingInstalls =
374 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800375
376 private boolean connectToService() {
377 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
378 " DefaultContainerService");
379 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
380 if (mContext.bindService(service, mDefContainerConn,
381 Context.BIND_AUTO_CREATE)) {
382 mBound = true;
383 return true;
384 }
385 return false;
386 }
387
388 private void disconnectService() {
389 mContainerService = null;
390 mBound = false;
391 mContext.unbindService(mDefContainerConn);
392 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800393
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700394 PackageHandler(Looper looper) {
395 super(looper);
396 }
397 public void handleMessage(Message msg) {
398 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800399 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800400 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800401 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800402 int idx = mPendingInstalls.size();
403 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
404 // If a bind was already initiated we dont really
405 // need to do anything. The pending install
406 // will be processed later on.
407 if (!mBound) {
408 // If this is the only one pending we might
409 // have to bind to the service again.
410 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800411 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800412 params.serviceError();
413 return;
414 } else {
415 // Once we bind to the service, the first
416 // pending request will be processed.
417 mPendingInstalls.add(idx, params);
418 }
419 } else {
420 mPendingInstalls.add(idx, params);
421 // Already bound to the service. Just make
422 // sure we trigger off processing the first request.
423 if (idx == 0) {
424 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800425 }
426 }
427 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800428 }
429 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800430 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800431 if (msg.obj != null) {
432 mContainerService = (IMediaContainerService) msg.obj;
433 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800434 if (mContainerService == null) {
435 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800436 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800437 for (HandlerParams params : mPendingInstalls) {
438 mPendingInstalls.remove(0);
439 // Indicate service bind error
440 params.serviceError();
441 }
442 mPendingInstalls.clear();
443 } else if (mPendingInstalls.size() > 0) {
444 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800445 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800446 params.startCopy();
447 }
448 } else {
449 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800450 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800451 }
452 break;
453 }
454 case MCS_RECONNECT : {
455 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
456 if (mPendingInstalls.size() > 0) {
457 if (mBound) {
458 disconnectService();
459 }
460 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800461 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800462 for (HandlerParams params : mPendingInstalls) {
463 mPendingInstalls.remove(0);
464 // Indicate service bind error
465 params.serviceError();
466 }
467 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800468 }
469 }
470 break;
471 }
472 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800473 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
474 // Delete pending install
475 if (mPendingInstalls.size() > 0) {
476 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800477 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800478 if (mPendingInstalls.size() == 0) {
479 if (mBound) {
480 disconnectService();
481 }
482 } else {
483 // There are more pending requests in queue.
484 // Just post MCS_BOUND message to trigger processing
485 // of next pending install.
486 mHandler.sendEmptyMessage(MCS_BOUND);
487 }
488 break;
489 }
490 case MCS_GIVE_UP: {
491 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
492 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800493 break;
494 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700495 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800496 String packages[];
497 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700498 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700499 int uids[];
500 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800501 if (mPendingBroadcasts == null) {
502 return;
503 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700504 size = mPendingBroadcasts.size();
505 if (size <= 0) {
506 // Nothing to be done. Just return
507 return;
508 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800509 packages = new String[size];
510 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700511 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800512 Iterator<HashMap.Entry<String, ArrayList<String>>>
513 it = mPendingBroadcasts.entrySet().iterator();
514 int i = 0;
515 while (it.hasNext() && i < size) {
516 HashMap.Entry<String, ArrayList<String>> ent = it.next();
517 packages[i] = ent.getKey();
518 components[i] = ent.getValue();
519 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700520 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800521 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700522 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800523 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700524 mPendingBroadcasts.clear();
525 }
526 // Send broadcasts
527 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800528 sendPackageChangedBroadcast(packages[i], true,
529 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700530 }
531 break;
532 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800533 case START_CLEANING_PACKAGE: {
534 String packageName = (String)msg.obj;
535 synchronized (mPackages) {
536 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
537 mSettings.mPackagesToBeCleaned.add(packageName);
538 }
539 }
540 startCleaningPackages();
541 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800542 case POST_INSTALL: {
543 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
544 PostInstallData data = mRunningInstalls.get(msg.arg1);
545 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800546 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800547
548 if (data != null) {
549 InstallArgs args = data.args;
550 PackageInstalledInfo res = data.res;
551
552 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
553 res.removedInfo.sendBroadcast(false, true);
554 Bundle extras = new Bundle(1);
555 extras.putInt(Intent.EXTRA_UID, res.uid);
556 final boolean update = res.removedInfo.removedPackage != null;
557 if (update) {
558 extras.putBoolean(Intent.EXTRA_REPLACING, true);
559 }
560 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
561 res.pkg.applicationInfo.packageName,
562 extras);
563 if (update) {
564 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
565 res.pkg.applicationInfo.packageName,
566 extras);
567 }
568 if (res.removedInfo.args != null) {
569 // Remove the replaced package's older resources safely now
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800570 deleteOld = true;
Christopher Tate1bb69062010-02-19 17:02:12 -0800571 }
572 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800573 // Force a gc to clear up things
Christopher Tate1bb69062010-02-19 17:02:12 -0800574 Runtime.getRuntime().gc();
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800575 // We delete after a gc for applications on sdcard.
576 if (deleteOld) {
577 synchronized (mInstallLock) {
578 res.removedInfo.args.doPostDeleteLI(true);
579 }
580 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800581 if (args.observer != null) {
582 try {
583 args.observer.packageInstalled(res.name, res.returnCode);
584 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800585 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800586 }
587 }
588 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800589 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800590 }
591 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700592 }
593 }
594 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800595
596 static boolean installOnSd(int flags) {
597 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800598 ((flags & PackageManager.INSTALL_EXTERNAL) == 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800599 return false;
600 }
601 return true;
602 }
603
604 static boolean isFwdLocked(int flags) {
605 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
606 return true;
607 }
608 return false;
609 }
610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 public static final IPackageManager main(Context context, boolean factoryTest) {
612 PackageManagerService m = new PackageManagerService(context, factoryTest);
613 ServiceManager.addService("package", m);
614 return m;
615 }
616
617 static String[] splitString(String str, char sep) {
618 int count = 1;
619 int i = 0;
620 while ((i=str.indexOf(sep, i)) >= 0) {
621 count++;
622 i++;
623 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 String[] res = new String[count];
626 i=0;
627 count = 0;
628 int lastI=0;
629 while ((i=str.indexOf(sep, i)) >= 0) {
630 res[count] = str.substring(lastI, i);
631 count++;
632 i++;
633 lastI = i;
634 }
635 res[count] = str.substring(lastI, str.length());
636 return res;
637 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800640 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800644 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 mContext = context;
648 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700649 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 mMetrics = new DisplayMetrics();
651 mSettings = new Settings();
652 mSettings.addSharedUserLP("android.uid.system",
653 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
654 mSettings.addSharedUserLP("android.uid.phone",
655 MULTIPLE_APPLICATION_UIDS
656 ? RADIO_UID : FIRST_APPLICATION_UID,
657 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400658 mSettings.addSharedUserLP("android.uid.log",
659 MULTIPLE_APPLICATION_UIDS
660 ? LOG_UID : FIRST_APPLICATION_UID,
661 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662
663 String separateProcesses = SystemProperties.get("debug.separate_processes");
664 if (separateProcesses != null && separateProcesses.length() > 0) {
665 if ("*".equals(separateProcesses)) {
666 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
667 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800668 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 } else {
670 mDefParseFlags = 0;
671 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800672 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 + separateProcesses);
674 }
675 } else {
676 mDefParseFlags = 0;
677 mSeparateProcesses = null;
678 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 Installer installer = new Installer();
681 // Little hacky thing to check if installd is here, to determine
682 // whether we are running on the simulator and thus need to take
683 // care of building the /data file structure ourself.
684 // (apparently the sim now has a working installer)
685 if (installer.ping() && Process.supportsProcesses()) {
686 mInstaller = installer;
687 } else {
688 mInstaller = null;
689 }
690
691 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
692 Display d = wm.getDefaultDisplay();
693 d.getMetrics(mMetrics);
694
695 synchronized (mInstallLock) {
696 synchronized (mPackages) {
697 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700698 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 File dataDir = Environment.getDataDirectory();
701 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800702 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
704
705 if (mInstaller == null) {
706 // Make sure these dirs exist, when we are running in
707 // the simulator.
708 // Make a wide-open directory for random misc stuff.
709 File miscDir = new File(dataDir, "misc");
710 miscDir.mkdirs();
711 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800712 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 mDrmAppPrivateInstallDir.mkdirs();
714 }
715
716 readPermissions();
717
718 mRestoredSettings = mSettings.readLP();
719 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800720
721 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800723
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800724 // Set flag to monitor and not change apk file paths when
725 // scanning install directories.
726 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700727 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800728 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800729 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700730 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700735 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700738 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 /**
741 * Out of paranoia, ensure that everything in the boot class
742 * path has been dexed.
743 */
744 String bootClassPath = System.getProperty("java.boot.class.path");
745 if (bootClassPath != null) {
746 String[] paths = splitString(bootClassPath, ':');
747 for (int i=0; i<paths.length; i++) {
748 try {
749 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
750 libFiles.add(paths[i]);
751 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700752 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 }
754 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800755 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800757 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 }
759 }
760 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800761 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 /**
765 * Also ensure all external libraries have had dexopt run on them.
766 */
767 if (mSharedLibraries.size() > 0) {
768 Iterator<String> libs = mSharedLibraries.values().iterator();
769 while (libs.hasNext()) {
770 String lib = libs.next();
771 try {
772 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
773 libFiles.add(lib);
774 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700775 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 }
777 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800778 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800780 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 }
782 }
783 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 // Gross hack for now: we know this file doesn't contain any
786 // code, so don't dexopt it to avoid the resulting log spew.
787 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 /**
790 * And there are a number of commands implemented in Java, which
791 * we currently need to do the dexopt on so that they can be
792 * run from a non-root shell.
793 */
794 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700795 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 for (int i=0; i<frameworkFiles.length; i++) {
797 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
798 String path = libPath.getPath();
799 // Skip the file if we alrady did it.
800 if (libFiles.contains(path)) {
801 continue;
802 }
803 // Skip the file if it is not a type we want to dexopt.
804 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
805 continue;
806 }
807 try {
808 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
809 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700810 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 }
812 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800813 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800815 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 }
817 }
818 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800819
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700820 if (didDexOpt) {
821 // If we had to do a dexopt of one of the previous
822 // things, then something on the system has changed.
823 // Consider this significant, and wipe away all other
824 // existing dexopt files to ensure we don't leave any
825 // dangling around.
826 String[] files = mDalvikCacheDir.list();
827 if (files != null) {
828 for (int i=0; i<files.length; i++) {
829 String fn = files[i];
830 if (fn.startsWith("data@app@")
831 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800832 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700833 (new File(mDalvikCacheDir, fn)).delete();
834 }
835 }
836 }
837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800839
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800840 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 mFrameworkInstallObserver = new AppDirObserver(
842 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
843 mFrameworkInstallObserver.startWatching();
844 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800845 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800846
847 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
849 mSystemInstallObserver = new AppDirObserver(
850 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
851 mSystemInstallObserver.startWatching();
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800852 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800853
854 if (mInstaller != null) {
855 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
856 mInstaller.moveFiles();
857 }
858
859 // Prune any system packages that no longer exist.
860 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
861 while (psit.hasNext()) {
862 PackageSetting ps = psit.next();
863 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800864 && !mPackages.containsKey(ps.name)
865 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800866 psit.remove();
867 String msg = "System package " + ps.name
868 + " no longer exists; wiping its data";
869 reportSettingsProblem(Log.WARN, msg);
870 if (mInstaller != null) {
871 // XXX how to set useEncryptedFSDir for packages that
872 // are not encrypted?
873 mInstaller.remove(ps.name, true);
874 }
875 }
876 }
877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 mAppInstallDir = new File(dataDir, "app");
879 if (mInstaller == null) {
880 // Make sure these dirs exist, when we are running in
881 // the simulator.
882 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
883 }
884 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800885 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 //clean up list
887 for(int i = 0; i < deletePkgsList.size(); i++) {
888 //clean up here
889 cleanupInstallFailedPackage(deletePkgsList.get(i));
890 }
891 //delete tmp files
892 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800893
894 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 SystemClock.uptimeMillis());
896 mAppInstallObserver = new AppDirObserver(
897 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
898 mAppInstallObserver.startWatching();
899 scanDirLI(mAppInstallDir, 0, scanMode);
900
901 mDrmAppInstallObserver = new AppDirObserver(
902 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
903 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800904 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800906 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800908 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 + ((SystemClock.uptimeMillis()-startTime)/1000f)
910 + " seconds");
911
912 updatePermissionsLP();
913
914 mSettings.writeLP();
915
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800916 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 // Now after opening every single application zip, make sure they
920 // are all flushed. Not really needed, but keeps things nice and
921 // tidy.
922 Runtime.getRuntime().gc();
923 } // synchronized (mPackages)
924 } // synchronized (mInstallLock)
925 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 @Override
928 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
929 throws RemoteException {
930 try {
931 return super.onTransact(code, data, reply, flags);
932 } catch (RuntimeException e) {
933 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800934 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 }
936 throw e;
937 }
938 }
939
Dianne Hackborne6620b22010-01-22 14:46:21 -0800940 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800941 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800943 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
944 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800946 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800947 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 }
949 } else {
950 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800951 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 File dataDir = new File(pkg.applicationInfo.dataDir);
953 dataDir.delete();
954 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800955 if (ps.codePath != null) {
956 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800957 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -0800958 }
959 }
960 if (ps.resourcePath != null) {
961 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800962 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -0800963 }
964 }
965 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 }
967
968 void readPermissions() {
969 // Read permissions from .../etc/permission directory.
970 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
971 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800972 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 return;
974 }
975 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800976 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 return;
978 }
979
980 // Iterate over the files in the directory and scan .xml files
981 for (File f : libraryDir.listFiles()) {
982 // We'll read platform.xml last
983 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
984 continue;
985 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800988 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 continue;
990 }
991 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800992 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 continue;
994 }
995
996 readPermissionsFromXml(f);
997 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1000 final File permFile = new File(Environment.getRootDirectory(),
1001 "etc/permissions/platform.xml");
1002 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001003
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001004 StringBuilder sb = new StringBuilder(128);
1005 sb.append("Libs:");
1006 Iterator<String> it = mSharedLibraries.keySet().iterator();
1007 while (it.hasNext()) {
1008 sb.append(' ');
1009 String name = it.next();
1010 sb.append(name);
1011 sb.append(':');
1012 sb.append(mSharedLibraries.get(name));
1013 }
1014 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001015
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001016 sb.setLength(0);
1017 sb.append("Features:");
1018 it = mAvailableFeatures.keySet().iterator();
1019 while (it.hasNext()) {
1020 sb.append(' ');
1021 sb.append(it.next());
1022 }
1023 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001025
1026 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 FileReader permReader = null;
1028 try {
1029 permReader = new FileReader(permFile);
1030 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001031 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 return;
1033 }
1034
1035 try {
1036 XmlPullParser parser = Xml.newPullParser();
1037 parser.setInput(permReader);
1038
1039 XmlUtils.beginDocument(parser, "permissions");
1040
1041 while (true) {
1042 XmlUtils.nextElement(parser);
1043 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1044 break;
1045 }
1046
1047 String name = parser.getName();
1048 if ("group".equals(name)) {
1049 String gidStr = parser.getAttributeValue(null, "gid");
1050 if (gidStr != null) {
1051 int gid = Integer.parseInt(gidStr);
1052 mGlobalGids = appendInt(mGlobalGids, gid);
1053 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001054 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 + parser.getPositionDescription());
1056 }
1057
1058 XmlUtils.skipCurrentTag(parser);
1059 continue;
1060 } else if ("permission".equals(name)) {
1061 String perm = parser.getAttributeValue(null, "name");
1062 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001063 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 + parser.getPositionDescription());
1065 XmlUtils.skipCurrentTag(parser);
1066 continue;
1067 }
1068 perm = perm.intern();
1069 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 } else if ("assign-permission".equals(name)) {
1072 String perm = parser.getAttributeValue(null, "name");
1073 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001074 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 + parser.getPositionDescription());
1076 XmlUtils.skipCurrentTag(parser);
1077 continue;
1078 }
1079 String uidStr = parser.getAttributeValue(null, "uid");
1080 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001081 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 + parser.getPositionDescription());
1083 XmlUtils.skipCurrentTag(parser);
1084 continue;
1085 }
1086 int uid = Process.getUidForName(uidStr);
1087 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001088 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 + uidStr + "\" at "
1090 + parser.getPositionDescription());
1091 XmlUtils.skipCurrentTag(parser);
1092 continue;
1093 }
1094 perm = perm.intern();
1095 HashSet<String> perms = mSystemPermissions.get(uid);
1096 if (perms == null) {
1097 perms = new HashSet<String>();
1098 mSystemPermissions.put(uid, perms);
1099 }
1100 perms.add(perm);
1101 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 } else if ("library".equals(name)) {
1104 String lname = parser.getAttributeValue(null, "name");
1105 String lfile = parser.getAttributeValue(null, "file");
1106 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001107 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 + parser.getPositionDescription());
1109 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001110 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 + parser.getPositionDescription());
1112 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001113 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001114 mSharedLibraries.put(lname, lfile);
1115 }
1116 XmlUtils.skipCurrentTag(parser);
1117 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001118
Dianne Hackborn49237342009-08-27 20:08:01 -07001119 } else if ("feature".equals(name)) {
1120 String fname = parser.getAttributeValue(null, "name");
1121 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001122 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001123 + parser.getPositionDescription());
1124 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001125 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001126 FeatureInfo fi = new FeatureInfo();
1127 fi.name = fname;
1128 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 }
1130 XmlUtils.skipCurrentTag(parser);
1131 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 } else {
1134 XmlUtils.skipCurrentTag(parser);
1135 continue;
1136 }
1137
1138 }
1139 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001140 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001142 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 }
1144 }
1145
1146 void readPermission(XmlPullParser parser, String name)
1147 throws IOException, XmlPullParserException {
1148
1149 name = name.intern();
1150
1151 BasePermission bp = mSettings.mPermissions.get(name);
1152 if (bp == null) {
1153 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1154 mSettings.mPermissions.put(name, bp);
1155 }
1156 int outerDepth = parser.getDepth();
1157 int type;
1158 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1159 && (type != XmlPullParser.END_TAG
1160 || parser.getDepth() > outerDepth)) {
1161 if (type == XmlPullParser.END_TAG
1162 || type == XmlPullParser.TEXT) {
1163 continue;
1164 }
1165
1166 String tagName = parser.getName();
1167 if ("group".equals(tagName)) {
1168 String gidStr = parser.getAttributeValue(null, "gid");
1169 if (gidStr != null) {
1170 int gid = Process.getGidForName(gidStr);
1171 bp.gids = appendInt(bp.gids, gid);
1172 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001173 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 + parser.getPositionDescription());
1175 }
1176 }
1177 XmlUtils.skipCurrentTag(parser);
1178 }
1179 }
1180
1181 static int[] appendInt(int[] cur, int val) {
1182 if (cur == null) {
1183 return new int[] { val };
1184 }
1185 final int N = cur.length;
1186 for (int i=0; i<N; i++) {
1187 if (cur[i] == val) {
1188 return cur;
1189 }
1190 }
1191 int[] ret = new int[N+1];
1192 System.arraycopy(cur, 0, ret, 0, N);
1193 ret[N] = val;
1194 return ret;
1195 }
1196
1197 static int[] appendInts(int[] cur, int[] add) {
1198 if (add == null) return cur;
1199 if (cur == null) return add;
1200 final int N = add.length;
1201 for (int i=0; i<N; i++) {
1202 cur = appendInt(cur, add[i]);
1203 }
1204 return cur;
1205 }
1206
1207 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001208 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1209 // The package has been uninstalled but has retained data and resources.
1210 return PackageParser.generatePackageInfo(p, null, flags);
1211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 final PackageSetting ps = (PackageSetting)p.mExtras;
1213 if (ps == null) {
1214 return null;
1215 }
1216 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1217 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1218 }
1219
1220 public PackageInfo getPackageInfo(String packageName, int flags) {
1221 synchronized (mPackages) {
1222 PackageParser.Package p = mPackages.get(packageName);
1223 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001224 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 + ": " + p);
1226 if (p != null) {
1227 return generatePackageInfo(p, flags);
1228 }
1229 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1230 return generatePackageInfoFromSettingsLP(packageName, flags);
1231 }
1232 }
1233 return null;
1234 }
1235
Dianne Hackborn47096932010-02-11 15:57:09 -08001236 public String[] currentToCanonicalPackageNames(String[] names) {
1237 String[] out = new String[names.length];
1238 synchronized (mPackages) {
1239 for (int i=names.length-1; i>=0; i--) {
1240 PackageSetting ps = mSettings.mPackages.get(names[i]);
1241 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1242 }
1243 }
1244 return out;
1245 }
1246
1247 public String[] canonicalToCurrentPackageNames(String[] names) {
1248 String[] out = new String[names.length];
1249 synchronized (mPackages) {
1250 for (int i=names.length-1; i>=0; i--) {
1251 String cur = mSettings.mRenamedPackages.get(names[i]);
1252 out[i] = cur != null ? cur : names[i];
1253 }
1254 }
1255 return out;
1256 }
1257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 public int getPackageUid(String packageName) {
1259 synchronized (mPackages) {
1260 PackageParser.Package p = mPackages.get(packageName);
1261 if(p != null) {
1262 return p.applicationInfo.uid;
1263 }
1264 PackageSetting ps = mSettings.mPackages.get(packageName);
1265 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1266 return -1;
1267 }
1268 p = ps.pkg;
1269 return p != null ? p.applicationInfo.uid : -1;
1270 }
1271 }
1272
1273 public int[] getPackageGids(String packageName) {
1274 synchronized (mPackages) {
1275 PackageParser.Package p = mPackages.get(packageName);
1276 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001277 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 + ": " + p);
1279 if (p != null) {
1280 final PackageSetting ps = (PackageSetting)p.mExtras;
1281 final SharedUserSetting suid = ps.sharedUser;
1282 return suid != null ? suid.gids : ps.gids;
1283 }
1284 }
1285 // stupid thing to indicate an error.
1286 return new int[0];
1287 }
1288
1289 public PermissionInfo getPermissionInfo(String name, int flags) {
1290 synchronized (mPackages) {
1291 final BasePermission p = mSettings.mPermissions.get(name);
1292 if (p != null && p.perm != null) {
1293 return PackageParser.generatePermissionInfo(p.perm, flags);
1294 }
1295 return null;
1296 }
1297 }
1298
1299 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1300 synchronized (mPackages) {
1301 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1302 for (BasePermission p : mSettings.mPermissions.values()) {
1303 if (group == null) {
1304 if (p.perm.info.group == null) {
1305 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1306 }
1307 } else {
1308 if (group.equals(p.perm.info.group)) {
1309 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1310 }
1311 }
1312 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 if (out.size() > 0) {
1315 return out;
1316 }
1317 return mPermissionGroups.containsKey(group) ? out : null;
1318 }
1319 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1322 synchronized (mPackages) {
1323 return PackageParser.generatePermissionGroupInfo(
1324 mPermissionGroups.get(name), flags);
1325 }
1326 }
1327
1328 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1329 synchronized (mPackages) {
1330 final int N = mPermissionGroups.size();
1331 ArrayList<PermissionGroupInfo> out
1332 = new ArrayList<PermissionGroupInfo>(N);
1333 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1334 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1335 }
1336 return out;
1337 }
1338 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1341 PackageSetting ps = mSettings.mPackages.get(packageName);
1342 if(ps != null) {
1343 if(ps.pkg == null) {
1344 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1345 if(pInfo != null) {
1346 return pInfo.applicationInfo;
1347 }
1348 return null;
1349 }
1350 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1351 }
1352 return null;
1353 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1356 PackageSetting ps = mSettings.mPackages.get(packageName);
1357 if(ps != null) {
1358 if(ps.pkg == null) {
1359 ps.pkg = new PackageParser.Package(packageName);
1360 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001361 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1362 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1363 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1364 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 }
1366 return generatePackageInfo(ps.pkg, flags);
1367 }
1368 return null;
1369 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1372 synchronized (mPackages) {
1373 PackageParser.Package p = mPackages.get(packageName);
1374 if (Config.LOGV) Log.v(
1375 TAG, "getApplicationInfo " + packageName
1376 + ": " + p);
1377 if (p != null) {
1378 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001379 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 }
1381 if ("android".equals(packageName)||"system".equals(packageName)) {
1382 return mAndroidApplication;
1383 }
1384 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1385 return generateApplicationInfoFromSettingsLP(packageName, flags);
1386 }
1387 }
1388 return null;
1389 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001390
1391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1393 mContext.enforceCallingOrSelfPermission(
1394 android.Manifest.permission.CLEAR_APP_CACHE, null);
1395 // Queue up an async operation since clearing cache may take a little while.
1396 mHandler.post(new Runnable() {
1397 public void run() {
1398 mHandler.removeCallbacks(this);
1399 int retCode = -1;
1400 if (mInstaller != null) {
1401 retCode = mInstaller.freeCache(freeStorageSize);
1402 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001403 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 }
1405 } //end if mInstaller
1406 if (observer != null) {
1407 try {
1408 observer.onRemoveCompleted(null, (retCode >= 0));
1409 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001410 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 }
1412 }
1413 }
1414 });
1415 }
1416
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001417 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001418 mContext.enforceCallingOrSelfPermission(
1419 android.Manifest.permission.CLEAR_APP_CACHE, null);
1420 // Queue up an async operation since clearing cache may take a little while.
1421 mHandler.post(new Runnable() {
1422 public void run() {
1423 mHandler.removeCallbacks(this);
1424 int retCode = -1;
1425 if (mInstaller != null) {
1426 retCode = mInstaller.freeCache(freeStorageSize);
1427 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001428 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001429 }
1430 }
1431 if(pi != null) {
1432 try {
1433 // Callback via pending intent
1434 int code = (retCode >= 0) ? 1 : 0;
1435 pi.sendIntent(null, code, null,
1436 null, null);
1437 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001438 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001439 }
1440 }
1441 }
1442 });
1443 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1446 synchronized (mPackages) {
1447 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001448
1449 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001451 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 }
1453 if (mResolveComponentName.equals(component)) {
1454 return mResolveActivity;
1455 }
1456 }
1457 return null;
1458 }
1459
1460 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1461 synchronized (mPackages) {
1462 PackageParser.Activity a = mReceivers.mActivities.get(component);
1463 if (Config.LOGV) Log.v(
1464 TAG, "getReceiverInfo " + component + ": " + a);
1465 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1466 return PackageParser.generateActivityInfo(a, flags);
1467 }
1468 }
1469 return null;
1470 }
1471
1472 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1473 synchronized (mPackages) {
1474 PackageParser.Service s = mServices.mServices.get(component);
1475 if (Config.LOGV) Log.v(
1476 TAG, "getServiceInfo " + component + ": " + s);
1477 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1478 return PackageParser.generateServiceInfo(s, flags);
1479 }
1480 }
1481 return null;
1482 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 public String[] getSystemSharedLibraryNames() {
1485 Set<String> libSet;
1486 synchronized (mPackages) {
1487 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001488 int size = libSet.size();
1489 if (size > 0) {
1490 String[] libs = new String[size];
1491 libSet.toArray(libs);
1492 return libs;
1493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001495 return null;
1496 }
1497
1498 public FeatureInfo[] getSystemAvailableFeatures() {
1499 Collection<FeatureInfo> featSet;
1500 synchronized (mPackages) {
1501 featSet = mAvailableFeatures.values();
1502 int size = featSet.size();
1503 if (size > 0) {
1504 FeatureInfo[] features = new FeatureInfo[size+1];
1505 featSet.toArray(features);
1506 FeatureInfo fi = new FeatureInfo();
1507 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1508 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1509 features[size] = fi;
1510 return features;
1511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 }
1513 return null;
1514 }
1515
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001516 public boolean hasSystemFeature(String name) {
1517 synchronized (mPackages) {
1518 return mAvailableFeatures.containsKey(name);
1519 }
1520 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 public int checkPermission(String permName, String pkgName) {
1523 synchronized (mPackages) {
1524 PackageParser.Package p = mPackages.get(pkgName);
1525 if (p != null && p.mExtras != null) {
1526 PackageSetting ps = (PackageSetting)p.mExtras;
1527 if (ps.sharedUser != null) {
1528 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1529 return PackageManager.PERMISSION_GRANTED;
1530 }
1531 } else if (ps.grantedPermissions.contains(permName)) {
1532 return PackageManager.PERMISSION_GRANTED;
1533 }
1534 }
1535 }
1536 return PackageManager.PERMISSION_DENIED;
1537 }
1538
1539 public int checkUidPermission(String permName, int uid) {
1540 synchronized (mPackages) {
1541 Object obj = mSettings.getUserIdLP(uid);
1542 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001543 GrantedPermissions gp = (GrantedPermissions)obj;
1544 if (gp.grantedPermissions.contains(permName)) {
1545 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 }
1547 } else {
1548 HashSet<String> perms = mSystemPermissions.get(uid);
1549 if (perms != null && perms.contains(permName)) {
1550 return PackageManager.PERMISSION_GRANTED;
1551 }
1552 }
1553 }
1554 return PackageManager.PERMISSION_DENIED;
1555 }
1556
1557 private BasePermission findPermissionTreeLP(String permName) {
1558 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1559 if (permName.startsWith(bp.name) &&
1560 permName.length() > bp.name.length() &&
1561 permName.charAt(bp.name.length()) == '.') {
1562 return bp;
1563 }
1564 }
1565 return null;
1566 }
1567
1568 private BasePermission checkPermissionTreeLP(String permName) {
1569 if (permName != null) {
1570 BasePermission bp = findPermissionTreeLP(permName);
1571 if (bp != null) {
1572 if (bp.uid == Binder.getCallingUid()) {
1573 return bp;
1574 }
1575 throw new SecurityException("Calling uid "
1576 + Binder.getCallingUid()
1577 + " is not allowed to add to permission tree "
1578 + bp.name + " owned by uid " + bp.uid);
1579 }
1580 }
1581 throw new SecurityException("No permission tree found for " + permName);
1582 }
1583
1584 public boolean addPermission(PermissionInfo info) {
1585 synchronized (mPackages) {
1586 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1587 throw new SecurityException("Label must be specified in permission");
1588 }
1589 BasePermission tree = checkPermissionTreeLP(info.name);
1590 BasePermission bp = mSettings.mPermissions.get(info.name);
1591 boolean added = bp == null;
1592 if (added) {
1593 bp = new BasePermission(info.name, tree.sourcePackage,
1594 BasePermission.TYPE_DYNAMIC);
1595 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1596 throw new SecurityException(
1597 "Not allowed to modify non-dynamic permission "
1598 + info.name);
1599 }
1600 bp.perm = new PackageParser.Permission(tree.perm.owner,
1601 new PermissionInfo(info));
1602 bp.perm.info.packageName = tree.perm.info.packageName;
1603 bp.uid = tree.uid;
1604 if (added) {
1605 mSettings.mPermissions.put(info.name, bp);
1606 }
1607 mSettings.writeLP();
1608 return added;
1609 }
1610 }
1611
1612 public void removePermission(String name) {
1613 synchronized (mPackages) {
1614 checkPermissionTreeLP(name);
1615 BasePermission bp = mSettings.mPermissions.get(name);
1616 if (bp != null) {
1617 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1618 throw new SecurityException(
1619 "Not allowed to modify non-dynamic permission "
1620 + name);
1621 }
1622 mSettings.mPermissions.remove(name);
1623 mSettings.writeLP();
1624 }
1625 }
1626 }
1627
Dianne Hackborn854060af2009-07-09 18:14:31 -07001628 public boolean isProtectedBroadcast(String actionName) {
1629 synchronized (mPackages) {
1630 return mProtectedBroadcasts.contains(actionName);
1631 }
1632 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 public int checkSignatures(String pkg1, String pkg2) {
1635 synchronized (mPackages) {
1636 PackageParser.Package p1 = mPackages.get(pkg1);
1637 PackageParser.Package p2 = mPackages.get(pkg2);
1638 if (p1 == null || p1.mExtras == null
1639 || p2 == null || p2.mExtras == null) {
1640 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1641 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001642 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 }
1644 }
1645
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001646 public int checkUidSignatures(int uid1, int uid2) {
1647 synchronized (mPackages) {
1648 Signature[] s1;
1649 Signature[] s2;
1650 Object obj = mSettings.getUserIdLP(uid1);
1651 if (obj != null) {
1652 if (obj instanceof SharedUserSetting) {
1653 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1654 } else if (obj instanceof PackageSetting) {
1655 s1 = ((PackageSetting)obj).signatures.mSignatures;
1656 } else {
1657 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1658 }
1659 } else {
1660 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1661 }
1662 obj = mSettings.getUserIdLP(uid2);
1663 if (obj != null) {
1664 if (obj instanceof SharedUserSetting) {
1665 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1666 } else if (obj instanceof PackageSetting) {
1667 s2 = ((PackageSetting)obj).signatures.mSignatures;
1668 } else {
1669 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1670 }
1671 } else {
1672 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1673 }
1674 return checkSignaturesLP(s1, s2);
1675 }
1676 }
1677
1678 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1679 if (s1 == null) {
1680 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1682 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1683 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001684 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1686 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001687 final int N1 = s1.length;
1688 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 for (int i=0; i<N1; i++) {
1690 boolean match = false;
1691 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001692 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 match = true;
1694 break;
1695 }
1696 }
1697 if (!match) {
1698 return PackageManager.SIGNATURE_NO_MATCH;
1699 }
1700 }
1701 return PackageManager.SIGNATURE_MATCH;
1702 }
1703
1704 public String[] getPackagesForUid(int uid) {
1705 synchronized (mPackages) {
1706 Object obj = mSettings.getUserIdLP(uid);
1707 if (obj instanceof SharedUserSetting) {
1708 SharedUserSetting sus = (SharedUserSetting)obj;
1709 final int N = sus.packages.size();
1710 String[] res = new String[N];
1711 Iterator<PackageSetting> it = sus.packages.iterator();
1712 int i=0;
1713 while (it.hasNext()) {
1714 res[i++] = it.next().name;
1715 }
1716 return res;
1717 } else if (obj instanceof PackageSetting) {
1718 PackageSetting ps = (PackageSetting)obj;
1719 return new String[] { ps.name };
1720 }
1721 }
1722 return null;
1723 }
1724
1725 public String getNameForUid(int uid) {
1726 synchronized (mPackages) {
1727 Object obj = mSettings.getUserIdLP(uid);
1728 if (obj instanceof SharedUserSetting) {
1729 SharedUserSetting sus = (SharedUserSetting)obj;
1730 return sus.name + ":" + sus.userId;
1731 } else if (obj instanceof PackageSetting) {
1732 PackageSetting ps = (PackageSetting)obj;
1733 return ps.name;
1734 }
1735 }
1736 return null;
1737 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 public int getUidForSharedUser(String sharedUserName) {
1740 if(sharedUserName == null) {
1741 return -1;
1742 }
1743 synchronized (mPackages) {
1744 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1745 if(suid == null) {
1746 return -1;
1747 }
1748 return suid.userId;
1749 }
1750 }
1751
1752 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1753 int flags) {
1754 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001755 return chooseBestActivity(intent, resolvedType, flags, query);
1756 }
1757
Mihai Predaeae850c2009-05-13 10:13:48 +02001758 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1759 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 if (query != null) {
1761 final int N = query.size();
1762 if (N == 1) {
1763 return query.get(0);
1764 } else if (N > 1) {
1765 // If there is more than one activity with the same priority,
1766 // then let the user decide between them.
1767 ResolveInfo r0 = query.get(0);
1768 ResolveInfo r1 = query.get(1);
1769 if (false) {
1770 System.out.println(r0.activityInfo.name +
1771 "=" + r0.priority + " vs " +
1772 r1.activityInfo.name +
1773 "=" + r1.priority);
1774 }
1775 // If the first activity has a higher priority, or a different
1776 // default, then it is always desireable to pick it.
1777 if (r0.priority != r1.priority
1778 || r0.preferredOrder != r1.preferredOrder
1779 || r0.isDefault != r1.isDefault) {
1780 return query.get(0);
1781 }
1782 // If we have saved a preference for a preferred activity for
1783 // this Intent, use that.
1784 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1785 flags, query, r0.priority);
1786 if (ri != null) {
1787 return ri;
1788 }
1789 return mResolveInfo;
1790 }
1791 }
1792 return null;
1793 }
1794
1795 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1796 int flags, List<ResolveInfo> query, int priority) {
1797 synchronized (mPackages) {
1798 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1799 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001800 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1802 if (prefs != null && prefs.size() > 0) {
1803 // First figure out how good the original match set is.
1804 // We will only allow preferred activities that came
1805 // from the same match quality.
1806 int match = 0;
1807 final int N = query.size();
1808 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1809 for (int j=0; j<N; j++) {
1810 ResolveInfo ri = query.get(j);
1811 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1812 + ": 0x" + Integer.toHexString(match));
1813 if (ri.match > match) match = ri.match;
1814 }
1815 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1816 + Integer.toHexString(match));
1817 match &= IntentFilter.MATCH_CATEGORY_MASK;
1818 final int M = prefs.size();
1819 for (int i=0; i<M; i++) {
1820 PreferredActivity pa = prefs.get(i);
1821 if (pa.mMatch != match) {
1822 continue;
1823 }
1824 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1825 if (DEBUG_PREFERRED) {
1826 Log.v(TAG, "Got preferred activity:");
1827 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1828 }
1829 if (ai != null) {
1830 for (int j=0; j<N; j++) {
1831 ResolveInfo ri = query.get(j);
1832 if (!ri.activityInfo.applicationInfo.packageName
1833 .equals(ai.applicationInfo.packageName)) {
1834 continue;
1835 }
1836 if (!ri.activityInfo.name.equals(ai.name)) {
1837 continue;
1838 }
1839
1840 // Okay we found a previously set preferred app.
1841 // If the result set is different from when this
1842 // was created, we need to clear it and re-ask the
1843 // user their preference.
1844 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001845 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 + intent + " type " + resolvedType);
1847 mSettings.mPreferredActivities.removeFilter(pa);
1848 return null;
1849 }
1850
1851 // Yay!
1852 return ri;
1853 }
1854 }
1855 }
1856 }
1857 }
1858 return null;
1859 }
1860
1861 public List<ResolveInfo> queryIntentActivities(Intent intent,
1862 String resolvedType, int flags) {
1863 ComponentName comp = intent.getComponent();
1864 if (comp != null) {
1865 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1866 ActivityInfo ai = getActivityInfo(comp, flags);
1867 if (ai != null) {
1868 ResolveInfo ri = new ResolveInfo();
1869 ri.activityInfo = ai;
1870 list.add(ri);
1871 }
1872 return list;
1873 }
1874
1875 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001876 String pkgName = intent.getPackage();
1877 if (pkgName == null) {
1878 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1879 resolvedType, flags);
1880 }
1881 PackageParser.Package pkg = mPackages.get(pkgName);
1882 if (pkg != null) {
1883 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1884 resolvedType, flags, pkg.activities);
1885 }
1886 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 }
1888 }
1889
1890 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1891 Intent[] specifics, String[] specificTypes, Intent intent,
1892 String resolvedType, int flags) {
1893 final String resultsAction = intent.getAction();
1894
1895 List<ResolveInfo> results = queryIntentActivities(
1896 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1897 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1898
1899 int specificsPos = 0;
1900 int N;
1901
1902 // todo: note that the algorithm used here is O(N^2). This
1903 // isn't a problem in our current environment, but if we start running
1904 // into situations where we have more than 5 or 10 matches then this
1905 // should probably be changed to something smarter...
1906
1907 // First we go through and resolve each of the specific items
1908 // that were supplied, taking care of removing any corresponding
1909 // duplicate items in the generic resolve list.
1910 if (specifics != null) {
1911 for (int i=0; i<specifics.length; i++) {
1912 final Intent sintent = specifics[i];
1913 if (sintent == null) {
1914 continue;
1915 }
1916
1917 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1918 String action = sintent.getAction();
1919 if (resultsAction != null && resultsAction.equals(action)) {
1920 // If this action was explicitly requested, then don't
1921 // remove things that have it.
1922 action = null;
1923 }
1924 ComponentName comp = sintent.getComponent();
1925 ResolveInfo ri = null;
1926 ActivityInfo ai = null;
1927 if (comp == null) {
1928 ri = resolveIntent(
1929 sintent,
1930 specificTypes != null ? specificTypes[i] : null,
1931 flags);
1932 if (ri == null) {
1933 continue;
1934 }
1935 if (ri == mResolveInfo) {
1936 // ACK! Must do something better with this.
1937 }
1938 ai = ri.activityInfo;
1939 comp = new ComponentName(ai.applicationInfo.packageName,
1940 ai.name);
1941 } else {
1942 ai = getActivityInfo(comp, flags);
1943 if (ai == null) {
1944 continue;
1945 }
1946 }
1947
1948 // Look for any generic query activities that are duplicates
1949 // of this specific one, and remove them from the results.
1950 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1951 N = results.size();
1952 int j;
1953 for (j=specificsPos; j<N; j++) {
1954 ResolveInfo sri = results.get(j);
1955 if ((sri.activityInfo.name.equals(comp.getClassName())
1956 && sri.activityInfo.applicationInfo.packageName.equals(
1957 comp.getPackageName()))
1958 || (action != null && sri.filter.matchAction(action))) {
1959 results.remove(j);
1960 if (Config.LOGV) Log.v(
1961 TAG, "Removing duplicate item from " + j
1962 + " due to specific " + specificsPos);
1963 if (ri == null) {
1964 ri = sri;
1965 }
1966 j--;
1967 N--;
1968 }
1969 }
1970
1971 // Add this specific item to its proper place.
1972 if (ri == null) {
1973 ri = new ResolveInfo();
1974 ri.activityInfo = ai;
1975 }
1976 results.add(specificsPos, ri);
1977 ri.specificIndex = i;
1978 specificsPos++;
1979 }
1980 }
1981
1982 // Now we go through the remaining generic results and remove any
1983 // duplicate actions that are found here.
1984 N = results.size();
1985 for (int i=specificsPos; i<N-1; i++) {
1986 final ResolveInfo rii = results.get(i);
1987 if (rii.filter == null) {
1988 continue;
1989 }
1990
1991 // Iterate over all of the actions of this result's intent
1992 // filter... typically this should be just one.
1993 final Iterator<String> it = rii.filter.actionsIterator();
1994 if (it == null) {
1995 continue;
1996 }
1997 while (it.hasNext()) {
1998 final String action = it.next();
1999 if (resultsAction != null && resultsAction.equals(action)) {
2000 // If this action was explicitly requested, then don't
2001 // remove things that have it.
2002 continue;
2003 }
2004 for (int j=i+1; j<N; j++) {
2005 final ResolveInfo rij = results.get(j);
2006 if (rij.filter != null && rij.filter.hasAction(action)) {
2007 results.remove(j);
2008 if (Config.LOGV) Log.v(
2009 TAG, "Removing duplicate item from " + j
2010 + " due to action " + action + " at " + i);
2011 j--;
2012 N--;
2013 }
2014 }
2015 }
2016
2017 // If the caller didn't request filter information, drop it now
2018 // so we don't have to marshall/unmarshall it.
2019 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2020 rii.filter = null;
2021 }
2022 }
2023
2024 // Filter out the caller activity if so requested.
2025 if (caller != null) {
2026 N = results.size();
2027 for (int i=0; i<N; i++) {
2028 ActivityInfo ainfo = results.get(i).activityInfo;
2029 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2030 && caller.getClassName().equals(ainfo.name)) {
2031 results.remove(i);
2032 break;
2033 }
2034 }
2035 }
2036
2037 // If the caller didn't request filter information,
2038 // drop them now so we don't have to
2039 // marshall/unmarshall it.
2040 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2041 N = results.size();
2042 for (int i=0; i<N; i++) {
2043 results.get(i).filter = null;
2044 }
2045 }
2046
2047 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2048 return results;
2049 }
2050
2051 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2052 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002053 ComponentName comp = intent.getComponent();
2054 if (comp != null) {
2055 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2056 ActivityInfo ai = getReceiverInfo(comp, flags);
2057 if (ai != null) {
2058 ResolveInfo ri = new ResolveInfo();
2059 ri.activityInfo = ai;
2060 list.add(ri);
2061 }
2062 return list;
2063 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002066 String pkgName = intent.getPackage();
2067 if (pkgName == null) {
2068 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2069 resolvedType, flags);
2070 }
2071 PackageParser.Package pkg = mPackages.get(pkgName);
2072 if (pkg != null) {
2073 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2074 resolvedType, flags, pkg.receivers);
2075 }
2076 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 }
2078 }
2079
2080 public ResolveInfo resolveService(Intent intent, String resolvedType,
2081 int flags) {
2082 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2083 flags);
2084 if (query != null) {
2085 if (query.size() >= 1) {
2086 // If there is more than one service with the same priority,
2087 // just arbitrarily pick the first one.
2088 return query.get(0);
2089 }
2090 }
2091 return null;
2092 }
2093
2094 public List<ResolveInfo> queryIntentServices(Intent intent,
2095 String resolvedType, int flags) {
2096 ComponentName comp = intent.getComponent();
2097 if (comp != null) {
2098 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2099 ServiceInfo si = getServiceInfo(comp, flags);
2100 if (si != null) {
2101 ResolveInfo ri = new ResolveInfo();
2102 ri.serviceInfo = si;
2103 list.add(ri);
2104 }
2105 return list;
2106 }
2107
2108 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002109 String pkgName = intent.getPackage();
2110 if (pkgName == null) {
2111 return (List<ResolveInfo>)mServices.queryIntent(intent,
2112 resolvedType, flags);
2113 }
2114 PackageParser.Package pkg = mPackages.get(pkgName);
2115 if (pkg != null) {
2116 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2117 resolvedType, flags, pkg.services);
2118 }
2119 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 }
2121 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 public List<PackageInfo> getInstalledPackages(int flags) {
2124 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2125
2126 synchronized (mPackages) {
2127 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2128 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2129 while (i.hasNext()) {
2130 final PackageSetting ps = i.next();
2131 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2132 if(psPkg != null) {
2133 finalList.add(psPkg);
2134 }
2135 }
2136 }
2137 else {
2138 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2139 while (i.hasNext()) {
2140 final PackageParser.Package p = i.next();
2141 if (p.applicationInfo != null) {
2142 PackageInfo pi = generatePackageInfo(p, flags);
2143 if(pi != null) {
2144 finalList.add(pi);
2145 }
2146 }
2147 }
2148 }
2149 }
2150 return finalList;
2151 }
2152
2153 public List<ApplicationInfo> getInstalledApplications(int flags) {
2154 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2155 synchronized(mPackages) {
2156 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2157 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2158 while (i.hasNext()) {
2159 final PackageSetting ps = i.next();
2160 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2161 if(ai != null) {
2162 finalList.add(ai);
2163 }
2164 }
2165 }
2166 else {
2167 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2168 while (i.hasNext()) {
2169 final PackageParser.Package p = i.next();
2170 if (p.applicationInfo != null) {
2171 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2172 if(ai != null) {
2173 finalList.add(ai);
2174 }
2175 }
2176 }
2177 }
2178 }
2179 return finalList;
2180 }
2181
2182 public List<ApplicationInfo> getPersistentApplications(int flags) {
2183 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2184
2185 synchronized (mPackages) {
2186 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2187 while (i.hasNext()) {
2188 PackageParser.Package p = i.next();
2189 if (p.applicationInfo != null
2190 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2191 && (!mSafeMode || (p.applicationInfo.flags
2192 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2193 finalList.add(p.applicationInfo);
2194 }
2195 }
2196 }
2197
2198 return finalList;
2199 }
2200
2201 public ProviderInfo resolveContentProvider(String name, int flags) {
2202 synchronized (mPackages) {
2203 final PackageParser.Provider provider = mProviders.get(name);
2204 return provider != null
2205 && mSettings.isEnabledLP(provider.info, flags)
2206 && (!mSafeMode || (provider.info.applicationInfo.flags
2207 &ApplicationInfo.FLAG_SYSTEM) != 0)
2208 ? PackageParser.generateProviderInfo(provider, flags)
2209 : null;
2210 }
2211 }
2212
Fred Quintana718d8a22009-04-29 17:53:20 -07002213 /**
2214 * @deprecated
2215 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 public void querySyncProviders(List outNames, List outInfo) {
2217 synchronized (mPackages) {
2218 Iterator<Map.Entry<String, PackageParser.Provider>> i
2219 = mProviders.entrySet().iterator();
2220
2221 while (i.hasNext()) {
2222 Map.Entry<String, PackageParser.Provider> entry = i.next();
2223 PackageParser.Provider p = entry.getValue();
2224
2225 if (p.syncable
2226 && (!mSafeMode || (p.info.applicationInfo.flags
2227 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2228 outNames.add(entry.getKey());
2229 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2230 }
2231 }
2232 }
2233 }
2234
2235 public List<ProviderInfo> queryContentProviders(String processName,
2236 int uid, int flags) {
2237 ArrayList<ProviderInfo> finalList = null;
2238
2239 synchronized (mPackages) {
2240 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2241 while (i.hasNext()) {
2242 PackageParser.Provider p = i.next();
2243 if (p.info.authority != null
2244 && (processName == null ||
2245 (p.info.processName.equals(processName)
2246 && p.info.applicationInfo.uid == uid))
2247 && mSettings.isEnabledLP(p.info, flags)
2248 && (!mSafeMode || (p.info.applicationInfo.flags
2249 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2250 if (finalList == null) {
2251 finalList = new ArrayList<ProviderInfo>(3);
2252 }
2253 finalList.add(PackageParser.generateProviderInfo(p,
2254 flags));
2255 }
2256 }
2257 }
2258
2259 if (finalList != null) {
2260 Collections.sort(finalList, mProviderInitOrderSorter);
2261 }
2262
2263 return finalList;
2264 }
2265
2266 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2267 int flags) {
2268 synchronized (mPackages) {
2269 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2270 return PackageParser.generateInstrumentationInfo(i, flags);
2271 }
2272 }
2273
2274 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2275 int flags) {
2276 ArrayList<InstrumentationInfo> finalList =
2277 new ArrayList<InstrumentationInfo>();
2278
2279 synchronized (mPackages) {
2280 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2281 while (i.hasNext()) {
2282 PackageParser.Instrumentation p = i.next();
2283 if (targetPackage == null
2284 || targetPackage.equals(p.info.targetPackage)) {
2285 finalList.add(PackageParser.generateInstrumentationInfo(p,
2286 flags));
2287 }
2288 }
2289 }
2290
2291 return finalList;
2292 }
2293
2294 private void scanDirLI(File dir, int flags, int scanMode) {
2295 Log.d(TAG, "Scanning app dir " + dir);
2296
2297 String[] files = dir.list();
2298
2299 int i;
2300 for (i=0; i<files.length; i++) {
2301 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002302 if (!isPackageFilename(files[i])) {
2303 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002304 continue;
2305 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002306 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002307 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002308 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002309 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2310 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002311 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002312 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002313 file.delete();
2314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 }
2316 }
2317
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002318 private static File getSettingsProblemFile() {
2319 File dataDir = Environment.getDataDirectory();
2320 File systemDir = new File(dataDir, "system");
2321 File fname = new File(systemDir, "uiderrors.txt");
2322 return fname;
2323 }
2324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 private static void reportSettingsProblem(int priority, String msg) {
2326 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002327 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328 FileOutputStream out = new FileOutputStream(fname, true);
2329 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002330 SimpleDateFormat formatter = new SimpleDateFormat();
2331 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2332 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333 pw.close();
2334 FileUtils.setPermissions(
2335 fname.toString(),
2336 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2337 -1, -1);
2338 } catch (java.io.IOException e) {
2339 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002340 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002341 }
2342
2343 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2344 PackageParser.Package pkg, File srcFile, int parseFlags) {
2345 if (GET_CERTIFICATES) {
2346 if (ps == null || !ps.codePath.equals(srcFile)
2347 || ps.getTimeStamp() != srcFile.lastModified()) {
2348 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2349 if (!pp.collectCertificates(pkg, parseFlags)) {
2350 mLastScanError = pp.getParseError();
2351 return false;
2352 }
2353 }
2354 }
2355 return true;
2356 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002358 /*
2359 * Scan a package and return the newly parsed package.
2360 * Returns null in case of errors and the error code is stored in mLastScanError
2361 */
2362 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002363 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002365 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002367 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002370 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 if (pkg == null) {
2372 mLastScanError = pp.getParseError();
2373 return null;
2374 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002375 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 PackageSetting updatedPkg;
2377 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002378 // Look to see if we already know about this package.
2379 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002380 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002381 // This package has been renamed to its original name. Let's
2382 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002383 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002384 }
2385 // If there was no original package, see one for the real package name.
2386 if (ps == null) {
2387 ps = mSettings.peekPackageLP(pkg.packageName);
2388 }
2389 // Check to see if this package could be hiding/updating a system
2390 // package. Must look for it either under the original or real
2391 // package name depending on our state.
2392 updatedPkg = mSettings.mDisabledSysPackages.get(
2393 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002395 // First check if this is a system package that may involve an update
2396 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2397 if (!ps.codePath.equals(scanFile)) {
2398 // The path has changed from what was last scanned... check the
2399 // version of the new path against what we have stored to determine
2400 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002401 if (pkg.mVersionCode < ps.versionCode) {
2402 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002403 // Ignore entry. Skip it.
2404 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2405 + "ignored: updated version " + ps.versionCode
2406 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002407 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2408 return null;
2409 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002410 // The current app on the system partion is better than
2411 // what we have updated to on the data partition; switch
2412 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002413 // At this point, its safely assumed that package installation for
2414 // apps in system partition will go through. If not there won't be a working
2415 // version of the app
2416 synchronized (mPackages) {
2417 // Just remove the loaded entries from package lists.
2418 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002419 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002420 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002421 + "reverting from " + ps.codePathString
2422 + ": new version " + pkg.mVersionCode
2423 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002424 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2425 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002426 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 }
2429 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002430 if (updatedPkg != null) {
2431 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2432 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2433 }
2434 // Verify certificates against what was last scanned
2435 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002436 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002437 return null;
2438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 // The apk is forward locked (not public) if its code and resources
2440 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002441 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002443 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002444 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002445
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002446 String codePath = null;
2447 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002448 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2449 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002450 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002451 } else {
2452 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002453 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002454 }
2455 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002456 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002457 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002458 codePath = pkg.mScanPath;
2459 // Set application objects path explicitly.
2460 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002462 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002463 }
2464
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002465 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2466 String destCodePath, String destResPath) {
2467 pkg.mPath = pkg.mScanPath = destCodePath;
2468 pkg.applicationInfo.sourceDir = destCodePath;
2469 pkg.applicationInfo.publicSourceDir = destResPath;
2470 }
2471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472 private static String fixProcessName(String defProcessName,
2473 String processName, int uid) {
2474 if (processName == null) {
2475 return defProcessName;
2476 }
2477 return processName;
2478 }
2479
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002480 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2482 if (pkg.mSignatures != null) {
2483 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2484 updateSignature)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002485 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 + " signatures do not match the previously installed version; ignoring!");
2487 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2488 return false;
2489 }
2490
2491 if (pkgSetting.sharedUser != null) {
2492 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2493 pkg.mSignatures, updateSignature)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002494 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 + " has no signatures that match those in shared user "
2496 + pkgSetting.sharedUser.name + "; ignoring!");
2497 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2498 return false;
2499 }
2500 }
2501 } else {
2502 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2503 }
2504 return true;
2505 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002506
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002507 public boolean performDexOpt(String packageName) {
2508 if (!mNoDexOpt) {
2509 return false;
2510 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002511
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002512 PackageParser.Package p;
2513 synchronized (mPackages) {
2514 p = mPackages.get(packageName);
2515 if (p == null || p.mDidDexOpt) {
2516 return false;
2517 }
2518 }
2519 synchronized (mInstallLock) {
2520 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2521 }
2522 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002523
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002524 static final int DEX_OPT_SKIPPED = 0;
2525 static final int DEX_OPT_PERFORMED = 1;
2526 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002527
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002528 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2529 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002530 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002531 String path = pkg.mScanPath;
2532 int ret = 0;
2533 try {
2534 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002535 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002536 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002537 pkg.mDidDexOpt = true;
2538 performed = true;
2539 }
2540 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002541 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002542 ret = -1;
2543 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002544 Slog.w(TAG, "Exception reading apk: " + path, e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002545 ret = -1;
2546 }
2547 if (ret < 0) {
2548 //error from installer
2549 return DEX_OPT_FAILED;
2550 }
2551 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002552
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002553 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2554 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002555
2556 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2557 return Environment.isEncryptedFilesystemEnabled() &&
2558 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2559 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002560
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002561 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2562 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002563 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002564 + " to " + newPkg.packageName
2565 + ": old package not in system partition");
2566 return false;
2567 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002568 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002569 + " to " + newPkg.packageName
2570 + ": old package still exists");
2571 return false;
2572 }
2573 return true;
2574 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002575
2576 private File getDataPathForPackage(PackageParser.Package pkg) {
2577 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2578 File dataPath;
2579 if (useEncryptedFSDir) {
2580 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2581 } else {
2582 dataPath = new File(mAppDataDir, pkg.packageName);
2583 }
2584 return dataPath;
2585 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002586
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002587 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2588 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002589 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002590 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2591 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002592 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002593 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002594 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2595 return null;
2596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597 mScanningPath = scanFile;
2598 if (pkg == null) {
2599 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2600 return null;
2601 }
2602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2604 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2605 }
2606
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002607 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 synchronized (mPackages) {
2609 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002610 Slog.w(TAG, "*************************************************");
2611 Slog.w(TAG, "Core android package being redefined. Skipping.");
2612 Slog.w(TAG, " file=" + mScanningPath);
2613 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2615 return null;
2616 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002618 // Set up information for our fall-back user intent resolution
2619 // activity.
2620 mPlatformPackage = pkg;
2621 pkg.mVersionCode = mSdkVersion;
2622 mAndroidApplication = pkg.applicationInfo;
2623 mResolveActivity.applicationInfo = mAndroidApplication;
2624 mResolveActivity.name = ResolverActivity.class.getName();
2625 mResolveActivity.packageName = mAndroidApplication.packageName;
2626 mResolveActivity.processName = mAndroidApplication.processName;
2627 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2628 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2629 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2630 mResolveActivity.exported = true;
2631 mResolveActivity.enabled = true;
2632 mResolveInfo.activityInfo = mResolveActivity;
2633 mResolveInfo.priority = 0;
2634 mResolveInfo.preferredOrder = 0;
2635 mResolveInfo.match = 0;
2636 mResolveComponentName = new ComponentName(
2637 mAndroidApplication.packageName, mResolveActivity.name);
2638 }
2639 }
2640
2641 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002642 TAG, "Scanning package " + pkg.packageName);
2643 if (mPackages.containsKey(pkg.packageName)
2644 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002645 Slog.w(TAG, "*************************************************");
2646 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002648 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2650 return null;
2651 }
2652
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002653 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002654 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2655 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002657 SharedUserSetting suid = null;
2658 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002661
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002662 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2663 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002664 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002665 pkg.mRealPackage = null;
2666 pkg.mAdoptPermissions = null;
2667 }
2668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 synchronized (mPackages) {
2670 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002671 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2672 if (mTmpSharedLibraries == null ||
2673 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2674 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2675 }
2676 int num = 0;
2677 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2678 for (int i=0; i<N; i++) {
2679 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002681 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002683 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2685 return null;
2686 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002687 mTmpSharedLibraries[num] = file;
2688 num++;
2689 }
2690 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2691 for (int i=0; i<N; i++) {
2692 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2693 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002694 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002695 + " desires unavailable shared library "
2696 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2697 } else {
2698 mTmpSharedLibraries[num] = file;
2699 num++;
2700 }
2701 }
2702 if (num > 0) {
2703 pkg.usesLibraryFiles = new String[num];
2704 System.arraycopy(mTmpSharedLibraries, 0,
2705 pkg.usesLibraryFiles, 0, num);
2706 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002707
Dianne Hackborn49237342009-08-27 20:08:01 -07002708 if (pkg.reqFeatures != null) {
2709 N = pkg.reqFeatures.size();
2710 for (int i=0; i<N; i++) {
2711 FeatureInfo fi = pkg.reqFeatures.get(i);
2712 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2713 // Don't care.
2714 continue;
2715 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002716
Dianne Hackborn49237342009-08-27 20:08:01 -07002717 if (fi.name != null) {
2718 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002719 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002720 + " requires unavailable feature "
2721 + fi.name + "; failing!");
2722 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2723 return null;
2724 }
2725 }
2726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002727 }
2728 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730 if (pkg.mSharedUserId != null) {
2731 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2732 pkg.applicationInfo.flags, true);
2733 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002734 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 + " for shared user failed");
2736 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2737 return null;
2738 }
2739 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2740 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2741 + suid.userId + "): packages=" + suid.packages);
2742 }
2743 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002744
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002745 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002746 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002747 Log.w(TAG, "WAITING FOR DEBUGGER");
2748 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002749 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2750 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002751 }
2752 }
2753
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002754 // Check if we are renaming from an original package name.
2755 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002756 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002757 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002758 // This package may need to be renamed to a previously
2759 // installed name. Let's check on that...
2760 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002761 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002762 // This package had originally been installed as the
2763 // original name, and we have already taken care of
2764 // transitioning to the new one. Just update the new
2765 // one to continue using the old name.
2766 realName = pkg.mRealPackage;
2767 if (!pkg.packageName.equals(renamed)) {
2768 // Callers into this function may have already taken
2769 // care of renaming the package; only do it here if
2770 // it is not already done.
2771 pkg.setPackageName(renamed);
2772 }
2773
Dianne Hackbornc1552392010-03-03 16:19:01 -08002774 } else {
2775 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2776 if ((origPackage=mSettings.peekPackageLP(
2777 pkg.mOriginalPackages.get(i))) != null) {
2778 // We do have the package already installed under its
2779 // original name... should we use it?
2780 if (!verifyPackageUpdate(origPackage, pkg)) {
2781 // New package is not compatible with original.
2782 origPackage = null;
2783 continue;
2784 } else if (origPackage.sharedUser != null) {
2785 // Make sure uid is compatible between packages.
2786 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002787 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002788 + " to " + pkg.packageName + ": old uid "
2789 + origPackage.sharedUser.name
2790 + " differs from " + pkg.mSharedUserId);
2791 origPackage = null;
2792 continue;
2793 }
2794 } else {
2795 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2796 + pkg.packageName + " to old name " + origPackage.name);
2797 }
2798 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002799 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002800 }
2801 }
2802 }
2803
2804 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002805 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002806 + " was transferred to another, but its .apk remains");
2807 }
2808
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002809 // Just create the setting, don't add it yet. For already existing packages
2810 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002811 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 destResourceFile, pkg.applicationInfo.flags, true, false);
2813 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002814 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2816 return null;
2817 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002818
2819 if (pkgSetting.origPackage != null) {
2820 // If we are first transitioning from an original package,
2821 // fix up the new package's name now. We need to do this after
2822 // looking up the package under its new name, so getPackageLP
2823 // can take care of fiddling things correctly.
2824 pkg.setPackageName(origPackage.name);
2825
2826 // File a report about this.
2827 String msg = "New package " + pkgSetting.realName
2828 + " renamed to replace old package " + pkgSetting.name;
2829 reportSettingsProblem(Log.WARN, msg);
2830
2831 // Make a note of it.
2832 mTransferedPackages.add(origPackage.name);
2833
2834 // No longer need to retain this.
2835 pkgSetting.origPackage = null;
2836 }
2837
2838 if (realName != null) {
2839 // Make a note of it.
2840 mTransferedPackages.add(pkg.packageName);
2841 }
2842
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002843 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2845 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002847 pkg.applicationInfo.uid = pkgSetting.userId;
2848 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002849
2850 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2852 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2853 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2854 return null;
2855 }
2856 // The signature has changed, but this package is in the system
2857 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002858 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 // However... if this package is part of a shared user, but it
2860 // doesn't match the signature of the shared user, let's fail.
2861 // What this means is that you can't change the signatures
2862 // associated with an overall shared user, which doesn't seem all
2863 // that unreasonable.
2864 if (pkgSetting.sharedUser != null) {
2865 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2866 pkg.mSignatures, false)) {
2867 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2868 return null;
2869 }
2870 }
2871 removeExisting = true;
2872 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002873
The Android Open Source Project10592532009-03-18 17:39:46 -07002874 // Verify that this new package doesn't have any content providers
2875 // that conflict with existing packages. Only do this if the
2876 // package isn't already installed, since we don't want to break
2877 // things that are installed.
2878 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2879 int N = pkg.providers.size();
2880 int i;
2881 for (i=0; i<N; i++) {
2882 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08002883 if (p.info.authority != null) {
2884 String names[] = p.info.authority.split(";");
2885 for (int j = 0; j < names.length; j++) {
2886 if (mProviders.containsKey(names[j])) {
2887 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002888 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08002889 " (in package " + pkg.applicationInfo.packageName +
2890 ") is already used by "
2891 + ((other != null && other.getComponentName() != null)
2892 ? other.getComponentName().getPackageName() : "?"));
2893 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2894 return null;
2895 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002896 }
2897 }
2898 }
2899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 }
2901
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002902 final String pkgName = pkg.packageName;
2903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002905 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002907 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908 if (ret != 0) {
2909 String msg = "System package " + pkg.packageName
2910 + " could not have data directory erased after signature change.";
2911 reportSettingsProblem(Log.WARN, msg);
2912 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2913 return null;
2914 }
2915 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002916 Slog.w(TAG, "System package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 + " signature changed: existing data removed.");
2918 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2919 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002920
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002921 if (pkg.mAdoptPermissions != null) {
2922 // This package wants to adopt ownership of permissions from
2923 // another package.
2924 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2925 String origName = pkg.mAdoptPermissions.get(i);
2926 PackageSetting orig = mSettings.peekPackageLP(origName);
2927 if (orig != null) {
2928 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002929 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002930 + origName + " to " + pkg.packageName);
2931 mSettings.transferPermissions(origName, pkg.packageName);
2932 }
2933 }
2934 }
2935 }
2936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 long scanFileTime = scanFile.lastModified();
2938 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2939 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2940 pkg.applicationInfo.processName = fixProcessName(
2941 pkg.applicationInfo.packageName,
2942 pkg.applicationInfo.processName,
2943 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944
2945 File dataPath;
2946 if (mPlatformPackage == pkg) {
2947 // The system package is special.
2948 dataPath = new File (Environment.getDataDirectory(), "system");
2949 pkg.applicationInfo.dataDir = dataPath.getPath();
2950 } else {
2951 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002952 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002953 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002954
2955 boolean uidError = false;
2956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 if (dataPath.exists()) {
2958 mOutPermissions[1] = 0;
2959 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2960 if (mOutPermissions[1] == pkg.applicationInfo.uid
2961 || !Process.supportsProcesses()) {
2962 pkg.applicationInfo.dataDir = dataPath.getPath();
2963 } else {
2964 boolean recovered = false;
2965 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2966 // If this is a system app, we can at least delete its
2967 // current data so the application will still work.
2968 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002969 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002970 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 // Old data gone!
2972 String msg = "System package " + pkg.packageName
2973 + " has changed from uid: "
2974 + mOutPermissions[1] + " to "
2975 + pkg.applicationInfo.uid + "; old data erased";
2976 reportSettingsProblem(Log.WARN, msg);
2977 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002980 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002981 pkg.applicationInfo.uid);
2982 if (ret == -1) {
2983 // Ack should not happen!
2984 msg = "System package " + pkg.packageName
2985 + " could not have data directory re-created after delete.";
2986 reportSettingsProblem(Log.WARN, msg);
2987 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2988 return null;
2989 }
2990 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 if (!recovered) {
2993 mHasSystemUidErrors = true;
2994 }
2995 }
2996 if (!recovered) {
2997 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2998 + pkg.applicationInfo.uid + "/fs_"
2999 + mOutPermissions[1];
3000 String msg = "Package " + pkg.packageName
3001 + " has mismatched uid: "
3002 + mOutPermissions[1] + " on disk, "
3003 + pkg.applicationInfo.uid + " in settings";
3004 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003005 mSettings.mReadMessages.append(msg);
3006 mSettings.mReadMessages.append('\n');
3007 uidError = true;
3008 if (!pkgSetting.uidError) {
3009 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003011 }
3012 }
3013 }
3014 pkg.applicationInfo.dataDir = dataPath.getPath();
3015 } else {
3016 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3017 Log.v(TAG, "Want this data dir: " + dataPath);
3018 //invoke installer to do the actual installation
3019 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003020 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 pkg.applicationInfo.uid);
3022 if(ret < 0) {
3023 // Error from installer
3024 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3025 return null;
3026 }
3027 } else {
3028 dataPath.mkdirs();
3029 if (dataPath.exists()) {
3030 FileUtils.setPermissions(
3031 dataPath.toString(),
3032 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3033 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3034 }
3035 }
3036 if (dataPath.exists()) {
3037 pkg.applicationInfo.dataDir = dataPath.getPath();
3038 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003039 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 pkg.applicationInfo.dataDir = null;
3041 }
3042 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003043
3044 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003045 }
3046
3047 // Perform shared library installation and dex validation and
3048 // optimization, if this is not a system app.
3049 if (mInstaller != null) {
3050 String path = scanFile.getPath();
3051 if (scanFileNewer) {
3052 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003053 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3054 if (err != PackageManager.INSTALL_SUCCEEDED) {
3055 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056 return null;
3057 }
3058 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003059 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003060
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003061 if ((scanMode&SCAN_NO_DEX) == 0) {
3062 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003063 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3064 return null;
3065 }
3066 }
3067 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003069 if (mFactoryTest && pkg.requestedPermissions.contains(
3070 android.Manifest.permission.FACTORY_TEST)) {
3071 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3072 }
3073
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003074 // Request the ActivityManager to kill the process(only for existing packages)
3075 // so that we do not end up in a confused state while the user is still using the older
3076 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003077 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003078 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003079 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003080 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003082 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003083 // We don't expect installation to fail beyond this point,
3084 if ((scanMode&SCAN_MONITOR) != 0) {
3085 mAppDirs.put(pkg.mPath, pkg);
3086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003088 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003089 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003090 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003091 // Make sure we don't accidentally delete its data.
3092 mSettings.mPackagesToBeCleaned.remove(pkgName);
3093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003094 int N = pkg.providers.size();
3095 StringBuilder r = null;
3096 int i;
3097 for (i=0; i<N; i++) {
3098 PackageParser.Provider p = pkg.providers.get(i);
3099 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3100 p.info.processName, pkg.applicationInfo.uid);
3101 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3102 p.info.name), p);
3103 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003104 if (p.info.authority != null) {
3105 String names[] = p.info.authority.split(";");
3106 p.info.authority = null;
3107 for (int j = 0; j < names.length; j++) {
3108 if (j == 1 && p.syncable) {
3109 // We only want the first authority for a provider to possibly be
3110 // syncable, so if we already added this provider using a different
3111 // authority clear the syncable flag. We copy the provider before
3112 // changing it because the mProviders object contains a reference
3113 // to a provider that we don't want to change.
3114 // Only do this for the second authority since the resulting provider
3115 // object can be the same for all future authorities for this provider.
3116 p = new PackageParser.Provider(p);
3117 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003118 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003119 if (!mProviders.containsKey(names[j])) {
3120 mProviders.put(names[j], p);
3121 if (p.info.authority == null) {
3122 p.info.authority = names[j];
3123 } else {
3124 p.info.authority = p.info.authority + ";" + names[j];
3125 }
3126 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3127 Log.d(TAG, "Registered content provider: " + names[j] +
3128 ", className = " + p.info.name +
3129 ", isSyncable = " + p.info.isSyncable);
3130 } else {
3131 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003132 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003133 " (in package " + pkg.applicationInfo.packageName +
3134 "): name already used by "
3135 + ((other != null && other.getComponentName() != null)
3136 ? other.getComponentName().getPackageName() : "?"));
3137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003138 }
3139 }
3140 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3141 if (r == null) {
3142 r = new StringBuilder(256);
3143 } else {
3144 r.append(' ');
3145 }
3146 r.append(p.info.name);
3147 }
3148 }
3149 if (r != null) {
3150 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3151 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003153 N = pkg.services.size();
3154 r = null;
3155 for (i=0; i<N; i++) {
3156 PackageParser.Service s = pkg.services.get(i);
3157 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3158 s.info.processName, pkg.applicationInfo.uid);
3159 mServices.addService(s);
3160 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3161 if (r == null) {
3162 r = new StringBuilder(256);
3163 } else {
3164 r.append(' ');
3165 }
3166 r.append(s.info.name);
3167 }
3168 }
3169 if (r != null) {
3170 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3171 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003173 N = pkg.receivers.size();
3174 r = null;
3175 for (i=0; i<N; i++) {
3176 PackageParser.Activity a = pkg.receivers.get(i);
3177 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3178 a.info.processName, pkg.applicationInfo.uid);
3179 mReceivers.addActivity(a, "receiver");
3180 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3181 if (r == null) {
3182 r = new StringBuilder(256);
3183 } else {
3184 r.append(' ');
3185 }
3186 r.append(a.info.name);
3187 }
3188 }
3189 if (r != null) {
3190 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3191 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193 N = pkg.activities.size();
3194 r = null;
3195 for (i=0; i<N; i++) {
3196 PackageParser.Activity a = pkg.activities.get(i);
3197 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3198 a.info.processName, pkg.applicationInfo.uid);
3199 mActivities.addActivity(a, "activity");
3200 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3201 if (r == null) {
3202 r = new StringBuilder(256);
3203 } else {
3204 r.append(' ');
3205 }
3206 r.append(a.info.name);
3207 }
3208 }
3209 if (r != null) {
3210 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3211 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213 N = pkg.permissionGroups.size();
3214 r = null;
3215 for (i=0; i<N; i++) {
3216 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3217 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3218 if (cur == null) {
3219 mPermissionGroups.put(pg.info.name, pg);
3220 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3221 if (r == null) {
3222 r = new StringBuilder(256);
3223 } else {
3224 r.append(' ');
3225 }
3226 r.append(pg.info.name);
3227 }
3228 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003229 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 + pg.info.packageName + " ignored: original from "
3231 + cur.info.packageName);
3232 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3233 if (r == null) {
3234 r = new StringBuilder(256);
3235 } else {
3236 r.append(' ');
3237 }
3238 r.append("DUP:");
3239 r.append(pg.info.name);
3240 }
3241 }
3242 }
3243 if (r != null) {
3244 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3245 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247 N = pkg.permissions.size();
3248 r = null;
3249 for (i=0; i<N; i++) {
3250 PackageParser.Permission p = pkg.permissions.get(i);
3251 HashMap<String, BasePermission> permissionMap =
3252 p.tree ? mSettings.mPermissionTrees
3253 : mSettings.mPermissions;
3254 p.group = mPermissionGroups.get(p.info.group);
3255 if (p.info.group == null || p.group != null) {
3256 BasePermission bp = permissionMap.get(p.info.name);
3257 if (bp == null) {
3258 bp = new BasePermission(p.info.name, p.info.packageName,
3259 BasePermission.TYPE_NORMAL);
3260 permissionMap.put(p.info.name, bp);
3261 }
3262 if (bp.perm == null) {
3263 if (bp.sourcePackage == null
3264 || bp.sourcePackage.equals(p.info.packageName)) {
3265 BasePermission tree = findPermissionTreeLP(p.info.name);
3266 if (tree == null
3267 || tree.sourcePackage.equals(p.info.packageName)) {
3268 bp.perm = p;
3269 bp.uid = pkg.applicationInfo.uid;
3270 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3271 if (r == null) {
3272 r = new StringBuilder(256);
3273 } else {
3274 r.append(' ');
3275 }
3276 r.append(p.info.name);
3277 }
3278 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003279 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003280 + p.info.packageName + " ignored: base tree "
3281 + tree.name + " is from package "
3282 + tree.sourcePackage);
3283 }
3284 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003285 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003286 + p.info.packageName + " ignored: original from "
3287 + bp.sourcePackage);
3288 }
3289 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3290 if (r == null) {
3291 r = new StringBuilder(256);
3292 } else {
3293 r.append(' ');
3294 }
3295 r.append("DUP:");
3296 r.append(p.info.name);
3297 }
3298 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003299 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 + p.info.packageName + " ignored: no group "
3301 + p.group);
3302 }
3303 }
3304 if (r != null) {
3305 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3306 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 N = pkg.instrumentation.size();
3309 r = null;
3310 for (i=0; i<N; i++) {
3311 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3312 a.info.packageName = pkg.applicationInfo.packageName;
3313 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3314 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3315 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003316 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3318 if (r == null) {
3319 r = new StringBuilder(256);
3320 } else {
3321 r.append(' ');
3322 }
3323 r.append(a.info.name);
3324 }
3325 }
3326 if (r != null) {
3327 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3328 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003329
Dianne Hackborn854060af2009-07-09 18:14:31 -07003330 if (pkg.protectedBroadcasts != null) {
3331 N = pkg.protectedBroadcasts.size();
3332 for (i=0; i<N; i++) {
3333 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3334 }
3335 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337 pkgSetting.setTimeStamp(scanFileTime);
3338 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003340 return pkg;
3341 }
3342
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003343 private void killApplication(String pkgName, int uid) {
3344 // Request the ActivityManager to kill the process(only for existing packages)
3345 // so that we do not end up in a confused state while the user is still using the older
3346 // version of the application while the new one gets installed.
3347 IActivityManager am = ActivityManagerNative.getDefault();
3348 if (am != null) {
3349 try {
3350 am.killApplicationWithUid(pkgName, uid);
3351 } catch (RemoteException e) {
3352 }
3353 }
3354 }
3355
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003356 // The following constants are returned by cachePackageSharedLibsForAbiLI
3357 // to indicate if native shared libraries were found in the package.
3358 // Values are:
3359 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3360 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3361 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3362 // in package (and not installed)
3363 //
3364 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3365 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3366 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003367
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003368 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3369 // and automatically copy them to /data/data/<appname>/lib if present.
3370 //
3371 // NOTE: this method may throw an IOException if the library cannot
3372 // be copied to its final destination, e.g. if there isn't enough
3373 // room left on the data partition, or a ZipException if the package
3374 // file is malformed.
3375 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003376 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3377 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003378 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3379 final String apkLib = "lib/";
3380 final int apkLibLen = apkLib.length();
3381 final int cpuAbiLen = cpuAbi.length();
3382 final String libPrefix = "lib";
3383 final int libPrefixLen = libPrefix.length();
3384 final String libSuffix = ".so";
3385 final int libSuffixLen = libSuffix.length();
3386 boolean hasNativeLibraries = false;
3387 boolean installedNativeLibraries = false;
3388
3389 // the minimum length of a valid native shared library of the form
3390 // lib/<something>/lib<name>.so.
3391 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3392
3393 ZipFile zipFile = new ZipFile(scanFile);
3394 Enumeration<ZipEntry> entries =
3395 (Enumeration<ZipEntry>) zipFile.entries();
3396
3397 while (entries.hasMoreElements()) {
3398 ZipEntry entry = entries.nextElement();
3399 // skip directories
3400 if (entry.isDirectory()) {
3401 continue;
3402 }
3403 String entryName = entry.getName();
3404
3405 // check that the entry looks like lib/<something>/lib<name>.so
3406 // here, but don't check the ABI just yet.
3407 //
3408 // - must be sufficiently long
3409 // - must end with libSuffix, i.e. ".so"
3410 // - must start with apkLib, i.e. "lib/"
3411 if (entryName.length() < minEntryLen ||
3412 !entryName.endsWith(libSuffix) ||
3413 !entryName.startsWith(apkLib) ) {
3414 continue;
3415 }
3416
3417 // file name must start with libPrefix, i.e. "lib"
3418 int lastSlash = entryName.lastIndexOf('/');
3419
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003420 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003421 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3422 continue;
3423 }
3424
3425 hasNativeLibraries = true;
3426
3427 // check the cpuAbi now, between lib/ and /lib<name>.so
3428 //
3429 if (lastSlash != apkLibLen + cpuAbiLen ||
3430 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3431 continue;
3432
3433 // extract the library file name, ensure it doesn't contain
3434 // weird characters. we're guaranteed here that it doesn't contain
3435 // a directory separator though.
3436 String libFileName = entryName.substring(lastSlash+1);
3437 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3438 continue;
3439 }
3440
3441 installedNativeLibraries = true;
3442
3443 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3444 File.separator + libFileName;
3445 File sharedLibraryFile = new File(sharedLibraryFilePath);
3446 if (! sharedLibraryFile.exists() ||
3447 sharedLibraryFile.length() != entry.getSize() ||
3448 sharedLibraryFile.lastModified() != entry.getTime()) {
3449 if (Config.LOGD) {
3450 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003451 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003452 if (mInstaller == null) {
3453 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003454 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003455 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003456 sharedLibraryFile);
3457 }
3458 }
3459 if (!hasNativeLibraries)
3460 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3461
3462 if (!installedNativeLibraries)
3463 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3464
3465 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3466 }
3467
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003468 // Find the gdbserver executable program in a package at
3469 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3470 //
3471 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3472 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3473 //
3474 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3475 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3476 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3477 final String GDBSERVER = "gdbserver";
3478 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3479
3480 ZipFile zipFile = new ZipFile(scanFile);
3481 Enumeration<ZipEntry> entries =
3482 (Enumeration<ZipEntry>) zipFile.entries();
3483
3484 while (entries.hasMoreElements()) {
3485 ZipEntry entry = entries.nextElement();
3486 // skip directories
3487 if (entry.isDirectory()) {
3488 continue;
3489 }
3490 String entryName = entry.getName();
3491
3492 if (!entryName.equals(apkGdbServerPath)) {
3493 continue;
3494 }
3495
3496 String installGdbServerPath = installGdbServerDir.getPath() +
3497 "/" + GDBSERVER;
3498 File installGdbServerFile = new File(installGdbServerPath);
3499 if (! installGdbServerFile.exists() ||
3500 installGdbServerFile.length() != entry.getSize() ||
3501 installGdbServerFile.lastModified() != entry.getTime()) {
3502 if (Config.LOGD) {
3503 Log.d(TAG, "Caching gdbserver " + entry.getName());
3504 }
3505 if (mInstaller == null) {
3506 installGdbServerDir.mkdir();
3507 }
3508 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3509 installGdbServerFile);
3510 }
3511 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3512 }
3513 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3514 }
3515
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003516 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3517 // and copy them to /data/data/<appname>/lib.
3518 //
3519 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3520 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3521 // one if ro.product.cpu.abi2 is defined.
3522 //
3523 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3524 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003525 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003526 try {
3527 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3528
3529 // some architectures are capable of supporting several CPU ABIs
3530 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3531 // this is indicated by the definition of the ro.product.cpu.abi2
3532 // system property.
3533 //
3534 // only scan the package twice in case of ABI mismatch
3535 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003536 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003537 if (cpuAbi2 != null) {
3538 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003540
3541 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003542 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003543 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003544 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003545
3546 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3547 cpuAbi = cpuAbi2;
3548 }
3549 }
3550
3551 // for debuggable packages, also extract gdbserver from lib/<abi>
3552 // into /data/data/<appname>/lib too.
3553 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3554 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3555 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3556 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3557 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003559 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003560 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003561 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003562 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003564 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003565 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003567 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 }
3569
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003570 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003572 File binaryDir,
3573 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574 InputStream inputStream = zipFile.getInputStream(entry);
3575 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003576 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003578 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003579 // now need to be left as world readable and owned by the system.
3580 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3581 ! tempFile.setLastModified(entry.getTime()) ||
3582 FileUtils.setPermissions(tempFilePath,
3583 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003584 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003585 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003586 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003587 // Failed to properly write file.
3588 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003589 throw new IOException("Couldn't create cached binary "
3590 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003591 }
3592 } finally {
3593 inputStream.close();
3594 }
3595 }
3596
3597 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3598 if (chatty && Config.LOGD) Log.d(
3599 TAG, "Removing package " + pkg.applicationInfo.packageName );
3600
3601 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003604 mPackages.remove(pkg.applicationInfo.packageName);
3605 if (pkg.mPath != null) {
3606 mAppDirs.remove(pkg.mPath);
3607 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003609 PackageSetting ps = (PackageSetting)pkg.mExtras;
3610 if (ps != null && ps.sharedUser != null) {
3611 // XXX don't do this until the data is removed.
3612 if (false) {
3613 ps.sharedUser.packages.remove(ps);
3614 if (ps.sharedUser.packages.size() == 0) {
3615 // Remove.
3616 }
3617 }
3618 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 int N = pkg.providers.size();
3621 StringBuilder r = null;
3622 int i;
3623 for (i=0; i<N; i++) {
3624 PackageParser.Provider p = pkg.providers.get(i);
3625 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3626 p.info.name));
3627 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003629 /* The is another ContentProvider with this authority when
3630 * this app was installed so this authority is null,
3631 * Ignore it as we don't have to unregister the provider.
3632 */
3633 continue;
3634 }
3635 String names[] = p.info.authority.split(";");
3636 for (int j = 0; j < names.length; j++) {
3637 if (mProviders.get(names[j]) == p) {
3638 mProviders.remove(names[j]);
3639 if (chatty && Config.LOGD) Log.d(
3640 TAG, "Unregistered content provider: " + names[j] +
3641 ", className = " + p.info.name +
3642 ", isSyncable = " + p.info.isSyncable);
3643 }
3644 }
3645 if (chatty) {
3646 if (r == null) {
3647 r = new StringBuilder(256);
3648 } else {
3649 r.append(' ');
3650 }
3651 r.append(p.info.name);
3652 }
3653 }
3654 if (r != null) {
3655 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3656 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 N = pkg.services.size();
3659 r = null;
3660 for (i=0; i<N; i++) {
3661 PackageParser.Service s = pkg.services.get(i);
3662 mServices.removeService(s);
3663 if (chatty) {
3664 if (r == null) {
3665 r = new StringBuilder(256);
3666 } else {
3667 r.append(' ');
3668 }
3669 r.append(s.info.name);
3670 }
3671 }
3672 if (r != null) {
3673 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3674 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 N = pkg.receivers.size();
3677 r = null;
3678 for (i=0; i<N; i++) {
3679 PackageParser.Activity a = pkg.receivers.get(i);
3680 mReceivers.removeActivity(a, "receiver");
3681 if (chatty) {
3682 if (r == null) {
3683 r = new StringBuilder(256);
3684 } else {
3685 r.append(' ');
3686 }
3687 r.append(a.info.name);
3688 }
3689 }
3690 if (r != null) {
3691 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3692 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 N = pkg.activities.size();
3695 r = null;
3696 for (i=0; i<N; i++) {
3697 PackageParser.Activity a = pkg.activities.get(i);
3698 mActivities.removeActivity(a, "activity");
3699 if (chatty) {
3700 if (r == null) {
3701 r = new StringBuilder(256);
3702 } else {
3703 r.append(' ');
3704 }
3705 r.append(a.info.name);
3706 }
3707 }
3708 if (r != null) {
3709 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3710 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003712 N = pkg.permissions.size();
3713 r = null;
3714 for (i=0; i<N; i++) {
3715 PackageParser.Permission p = pkg.permissions.get(i);
3716 boolean tree = false;
3717 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3718 if (bp == null) {
3719 tree = true;
3720 bp = mSettings.mPermissionTrees.get(p.info.name);
3721 }
3722 if (bp != null && bp.perm == p) {
3723 if (bp.type != BasePermission.TYPE_BUILTIN) {
3724 if (tree) {
3725 mSettings.mPermissionTrees.remove(p.info.name);
3726 } else {
3727 mSettings.mPermissions.remove(p.info.name);
3728 }
3729 } else {
3730 bp.perm = null;
3731 }
3732 if (chatty) {
3733 if (r == null) {
3734 r = new StringBuilder(256);
3735 } else {
3736 r.append(' ');
3737 }
3738 r.append(p.info.name);
3739 }
3740 }
3741 }
3742 if (r != null) {
3743 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3744 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 N = pkg.instrumentation.size();
3747 r = null;
3748 for (i=0; i<N; i++) {
3749 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003750 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 if (chatty) {
3752 if (r == null) {
3753 r = new StringBuilder(256);
3754 } else {
3755 r.append(' ');
3756 }
3757 r.append(a.info.name);
3758 }
3759 }
3760 if (r != null) {
3761 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3762 }
3763 }
3764 }
3765
3766 private static final boolean isPackageFilename(String name) {
3767 return name != null && name.endsWith(".apk");
3768 }
3769
3770 private void updatePermissionsLP() {
3771 // Make sure there are no dangling permission trees.
3772 Iterator<BasePermission> it = mSettings.mPermissionTrees
3773 .values().iterator();
3774 while (it.hasNext()) {
3775 BasePermission bp = it.next();
3776 if (bp.perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003777 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 + " from package " + bp.sourcePackage);
3779 it.remove();
3780 }
3781 }
3782
3783 // Make sure all dynamic permissions have been assigned to a package,
3784 // and make sure there are no dangling permissions.
3785 it = mSettings.mPermissions.values().iterator();
3786 while (it.hasNext()) {
3787 BasePermission bp = it.next();
3788 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3789 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3790 + bp.name + " pkg=" + bp.sourcePackage
3791 + " info=" + bp.pendingInfo);
3792 if (bp.perm == null && bp.pendingInfo != null) {
3793 BasePermission tree = findPermissionTreeLP(bp.name);
3794 if (tree != null) {
3795 bp.perm = new PackageParser.Permission(tree.perm.owner,
3796 new PermissionInfo(bp.pendingInfo));
3797 bp.perm.info.packageName = tree.perm.info.packageName;
3798 bp.perm.info.name = bp.name;
3799 bp.uid = tree.uid;
3800 }
3801 }
3802 }
3803 if (bp.perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003804 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 + " from package " + bp.sourcePackage);
3806 it.remove();
3807 }
3808 }
3809
3810 // Now update the permissions for all packages, in particular
3811 // replace the granted permissions of the system packages.
3812 for (PackageParser.Package pkg : mPackages.values()) {
3813 grantPermissionsLP(pkg, false);
3814 }
3815 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003817 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3818 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3819 if (ps == null) {
3820 return;
3821 }
3822 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3823 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 if (replace) {
3826 ps.permissionsFixed = false;
3827 if (gp == ps) {
3828 gp.grantedPermissions.clear();
3829 gp.gids = mGlobalGids;
3830 }
3831 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833 if (gp.gids == null) {
3834 gp.gids = mGlobalGids;
3835 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 final int N = pkg.requestedPermissions.size();
3838 for (int i=0; i<N; i++) {
3839 String name = pkg.requestedPermissions.get(i);
3840 BasePermission bp = mSettings.mPermissions.get(name);
3841 PackageParser.Permission p = bp != null ? bp.perm : null;
3842 if (false) {
3843 if (gp != ps) {
3844 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3845 + ": " + p);
3846 }
3847 }
3848 if (p != null) {
3849 final String perm = p.info.name;
3850 boolean allowed;
3851 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3852 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3853 allowed = true;
3854 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3855 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003856 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003858 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 == PackageManager.SIGNATURE_MATCH);
3860 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3861 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3862 // For updated system applications, the signatureOrSystem permission
3863 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003864 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3866 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3867 if(sysPs.grantedPermissions.contains(perm)) {
3868 allowed = true;
3869 } else {
3870 allowed = false;
3871 }
3872 } else {
3873 allowed = true;
3874 }
3875 }
3876 }
3877 } else {
3878 allowed = false;
3879 }
3880 if (false) {
3881 if (gp != ps) {
3882 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3883 }
3884 }
3885 if (allowed) {
3886 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3887 && ps.permissionsFixed) {
3888 // If this is an existing, non-system package, then
3889 // we can't add any new permissions to it.
3890 if (!gp.loadedPermissions.contains(perm)) {
3891 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003892 // Except... if this is a permission that was added
3893 // to the platform (note: need to only do this when
3894 // updating the platform).
3895 final int NP = PackageParser.NEW_PERMISSIONS.length;
3896 for (int ip=0; ip<NP; ip++) {
3897 final PackageParser.NewPermissionInfo npi
3898 = PackageParser.NEW_PERMISSIONS[ip];
3899 if (npi.name.equals(perm)
3900 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3901 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003902 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003903 + pkg.packageName);
3904 break;
3905 }
3906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907 }
3908 }
3909 if (allowed) {
3910 if (!gp.grantedPermissions.contains(perm)) {
3911 addedPermission = true;
3912 gp.grantedPermissions.add(perm);
3913 gp.gids = appendInts(gp.gids, bp.gids);
3914 }
3915 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003916 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917 + " to package " + pkg.packageName
3918 + " because it was previously installed without");
3919 }
3920 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003921 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 + " to package " + pkg.packageName
3923 + " (protectionLevel=" + p.info.protectionLevel
3924 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3925 + ")");
3926 }
3927 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003928 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003929 + " in package " + pkg.packageName);
3930 }
3931 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003934 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3935 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 // This is the first that we have heard about this package, so the
3937 // permissions we have now selected are fixed until explicitly
3938 // changed.
3939 ps.permissionsFixed = true;
3940 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3941 }
3942 }
3943
3944 private final class ActivityIntentResolver
3945 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003946 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003947 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003948 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 }
3950
Mihai Preda074edef2009-05-18 17:13:31 +02003951 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003953 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3955 }
3956
Mihai Predaeae850c2009-05-13 10:13:48 +02003957 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3958 ArrayList<PackageParser.Activity> packageActivities) {
3959 if (packageActivities == null) {
3960 return null;
3961 }
3962 mFlags = flags;
3963 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3964 int N = packageActivities.size();
3965 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3966 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003967
3968 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003969 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003970 intentFilters = packageActivities.get(i).intents;
3971 if (intentFilters != null && intentFilters.size() > 0) {
3972 listCut.add(intentFilters);
3973 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003974 }
3975 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3976 }
3977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003979 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 if (SHOW_INFO || Config.LOGV) Log.v(
3981 TAG, " " + type + " " +
3982 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3983 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3984 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003985 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3987 if (SHOW_INFO || Config.LOGV) {
3988 Log.v(TAG, " IntentFilter:");
3989 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3990 }
3991 if (!intent.debugCheck()) {
3992 Log.w(TAG, "==> For Activity " + a.info.name);
3993 }
3994 addFilter(intent);
3995 }
3996 }
3997
3998 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003999 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 if (SHOW_INFO || Config.LOGV) Log.v(
4001 TAG, " " + type + " " +
4002 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4003 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4004 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004005 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4007 if (SHOW_INFO || Config.LOGV) {
4008 Log.v(TAG, " IntentFilter:");
4009 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4010 }
4011 removeFilter(intent);
4012 }
4013 }
4014
4015 @Override
4016 protected boolean allowFilterResult(
4017 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4018 ActivityInfo filterAi = filter.activity.info;
4019 for (int i=dest.size()-1; i>=0; i--) {
4020 ActivityInfo destAi = dest.get(i).activityInfo;
4021 if (destAi.name == filterAi.name
4022 && destAi.packageName == filterAi.packageName) {
4023 return false;
4024 }
4025 }
4026 return true;
4027 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 @Override
4030 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4031 int match) {
4032 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4033 return null;
4034 }
4035 final PackageParser.Activity activity = info.activity;
4036 if (mSafeMode && (activity.info.applicationInfo.flags
4037 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4038 return null;
4039 }
4040 final ResolveInfo res = new ResolveInfo();
4041 res.activityInfo = PackageParser.generateActivityInfo(activity,
4042 mFlags);
4043 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4044 res.filter = info;
4045 }
4046 res.priority = info.getPriority();
4047 res.preferredOrder = activity.owner.mPreferredOrder;
4048 //System.out.println("Result: " + res.activityInfo.className +
4049 // " = " + res.priority);
4050 res.match = match;
4051 res.isDefault = info.hasDefault;
4052 res.labelRes = info.labelRes;
4053 res.nonLocalizedLabel = info.nonLocalizedLabel;
4054 res.icon = info.icon;
4055 return res;
4056 }
4057
4058 @Override
4059 protected void sortResults(List<ResolveInfo> results) {
4060 Collections.sort(results, mResolvePrioritySorter);
4061 }
4062
4063 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004064 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004066 out.print(prefix); out.print(
4067 Integer.toHexString(System.identityHashCode(filter.activity)));
4068 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004069 out.println(filter.activity.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004070 }
4071
4072// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4073// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4074// final List<ResolveInfo> retList = Lists.newArrayList();
4075// while (i.hasNext()) {
4076// final ResolveInfo resolveInfo = i.next();
4077// if (isEnabledLP(resolveInfo.activityInfo)) {
4078// retList.add(resolveInfo);
4079// }
4080// }
4081// return retList;
4082// }
4083
4084 // Keys are String (activity class name), values are Activity.
4085 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4086 = new HashMap<ComponentName, PackageParser.Activity>();
4087 private int mFlags;
4088 }
4089
4090 private final class ServiceIntentResolver
4091 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004092 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004093 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004094 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 }
4096
Mihai Preda074edef2009-05-18 17:13:31 +02004097 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004099 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004100 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4101 }
4102
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004103 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4104 ArrayList<PackageParser.Service> packageServices) {
4105 if (packageServices == null) {
4106 return null;
4107 }
4108 mFlags = flags;
4109 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4110 int N = packageServices.size();
4111 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4112 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4113
4114 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4115 for (int i = 0; i < N; ++i) {
4116 intentFilters = packageServices.get(i).intents;
4117 if (intentFilters != null && intentFilters.size() > 0) {
4118 listCut.add(intentFilters);
4119 }
4120 }
4121 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4122 }
4123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004124 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004125 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 if (SHOW_INFO || Config.LOGV) Log.v(
4127 TAG, " " + (s.info.nonLocalizedLabel != null
4128 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4129 if (SHOW_INFO || Config.LOGV) Log.v(
4130 TAG, " Class=" + s.info.name);
4131 int NI = s.intents.size();
4132 int j;
4133 for (j=0; j<NI; j++) {
4134 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4135 if (SHOW_INFO || Config.LOGV) {
4136 Log.v(TAG, " IntentFilter:");
4137 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4138 }
4139 if (!intent.debugCheck()) {
4140 Log.w(TAG, "==> For Service " + s.info.name);
4141 }
4142 addFilter(intent);
4143 }
4144 }
4145
4146 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004147 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 if (SHOW_INFO || Config.LOGV) Log.v(
4149 TAG, " " + (s.info.nonLocalizedLabel != null
4150 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4151 if (SHOW_INFO || Config.LOGV) Log.v(
4152 TAG, " Class=" + s.info.name);
4153 int NI = s.intents.size();
4154 int j;
4155 for (j=0; j<NI; j++) {
4156 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4157 if (SHOW_INFO || Config.LOGV) {
4158 Log.v(TAG, " IntentFilter:");
4159 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4160 }
4161 removeFilter(intent);
4162 }
4163 }
4164
4165 @Override
4166 protected boolean allowFilterResult(
4167 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4168 ServiceInfo filterSi = filter.service.info;
4169 for (int i=dest.size()-1; i>=0; i--) {
4170 ServiceInfo destAi = dest.get(i).serviceInfo;
4171 if (destAi.name == filterSi.name
4172 && destAi.packageName == filterSi.packageName) {
4173 return false;
4174 }
4175 }
4176 return true;
4177 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004179 @Override
4180 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4181 int match) {
4182 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4183 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4184 return null;
4185 }
4186 final PackageParser.Service service = info.service;
4187 if (mSafeMode && (service.info.applicationInfo.flags
4188 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4189 return null;
4190 }
4191 final ResolveInfo res = new ResolveInfo();
4192 res.serviceInfo = PackageParser.generateServiceInfo(service,
4193 mFlags);
4194 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4195 res.filter = filter;
4196 }
4197 res.priority = info.getPriority();
4198 res.preferredOrder = service.owner.mPreferredOrder;
4199 //System.out.println("Result: " + res.activityInfo.className +
4200 // " = " + res.priority);
4201 res.match = match;
4202 res.isDefault = info.hasDefault;
4203 res.labelRes = info.labelRes;
4204 res.nonLocalizedLabel = info.nonLocalizedLabel;
4205 res.icon = info.icon;
4206 return res;
4207 }
4208
4209 @Override
4210 protected void sortResults(List<ResolveInfo> results) {
4211 Collections.sort(results, mResolvePrioritySorter);
4212 }
4213
4214 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004215 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004217 out.print(prefix); out.print(
4218 Integer.toHexString(System.identityHashCode(filter.service)));
4219 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004220 out.println(filter.service.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 }
4222
4223// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4224// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4225// final List<ResolveInfo> retList = Lists.newArrayList();
4226// while (i.hasNext()) {
4227// final ResolveInfo resolveInfo = (ResolveInfo) i;
4228// if (isEnabledLP(resolveInfo.serviceInfo)) {
4229// retList.add(resolveInfo);
4230// }
4231// }
4232// return retList;
4233// }
4234
4235 // Keys are String (activity class name), values are Activity.
4236 private final HashMap<ComponentName, PackageParser.Service> mServices
4237 = new HashMap<ComponentName, PackageParser.Service>();
4238 private int mFlags;
4239 };
4240
4241 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4242 new Comparator<ResolveInfo>() {
4243 public int compare(ResolveInfo r1, ResolveInfo r2) {
4244 int v1 = r1.priority;
4245 int v2 = r2.priority;
4246 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4247 if (v1 != v2) {
4248 return (v1 > v2) ? -1 : 1;
4249 }
4250 v1 = r1.preferredOrder;
4251 v2 = r2.preferredOrder;
4252 if (v1 != v2) {
4253 return (v1 > v2) ? -1 : 1;
4254 }
4255 if (r1.isDefault != r2.isDefault) {
4256 return r1.isDefault ? -1 : 1;
4257 }
4258 v1 = r1.match;
4259 v2 = r2.match;
4260 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4261 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4262 }
4263 };
4264
4265 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4266 new Comparator<ProviderInfo>() {
4267 public int compare(ProviderInfo p1, ProviderInfo p2) {
4268 final int v1 = p1.initOrder;
4269 final int v2 = p2.initOrder;
4270 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4271 }
4272 };
4273
4274 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4275 IActivityManager am = ActivityManagerNative.getDefault();
4276 if (am != null) {
4277 try {
4278 final Intent intent = new Intent(action,
4279 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4280 if (extras != null) {
4281 intent.putExtras(extras);
4282 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004283 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004284 am.broadcastIntent(
4285 null, intent,
4286 null, null, 0, null, null, null, false, false);
4287 } catch (RemoteException ex) {
4288 }
4289 }
4290 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004291
4292 public String nextPackageToClean(String lastPackage) {
4293 synchronized (mPackages) {
4294 if (!mMediaMounted) {
4295 // If the external storage is no longer mounted at this point,
4296 // the caller may not have been able to delete all of this
4297 // packages files and can not delete any more. Bail.
4298 return null;
4299 }
4300 if (lastPackage != null) {
4301 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4302 }
4303 return mSettings.mPackagesToBeCleaned.size() > 0
4304 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4305 }
4306 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004308 void schedulePackageCleaning(String packageName) {
4309 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4310 }
4311
4312 void startCleaningPackages() {
4313 synchronized (mPackages) {
4314 if (!mMediaMounted) {
4315 return;
4316 }
4317 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4318 return;
4319 }
4320 }
4321 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4322 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4323 IActivityManager am = ActivityManagerNative.getDefault();
4324 if (am != null) {
4325 try {
4326 am.startService(null, intent, null);
4327 } catch (RemoteException e) {
4328 }
4329 }
4330 }
4331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004332 private final class AppDirObserver extends FileObserver {
4333 public AppDirObserver(String path, int mask, boolean isrom) {
4334 super(path, mask);
4335 mRootDir = path;
4336 mIsRom = isrom;
4337 }
4338
4339 public void onEvent(int event, String path) {
4340 String removedPackage = null;
4341 int removedUid = -1;
4342 String addedPackage = null;
4343 int addedUid = -1;
4344
4345 synchronized (mInstallLock) {
4346 String fullPathStr = null;
4347 File fullPath = null;
4348 if (path != null) {
4349 fullPath = new File(mRootDir, path);
4350 fullPathStr = fullPath.getPath();
4351 }
4352
4353 if (Config.LOGV) Log.v(
4354 TAG, "File " + fullPathStr + " changed: "
4355 + Integer.toHexString(event));
4356
4357 if (!isPackageFilename(path)) {
4358 if (Config.LOGV) Log.v(
4359 TAG, "Ignoring change of non-package file: " + fullPathStr);
4360 return;
4361 }
4362
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004363 // Ignore packages that are being installed or
4364 // have just been installed.
4365 if (ignoreCodePath(fullPathStr)) {
4366 return;
4367 }
4368 PackageParser.Package p = null;
4369 synchronized (mPackages) {
4370 p = mAppDirs.get(fullPathStr);
4371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004372 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004373 if (p != null) {
4374 removePackageLI(p, true);
4375 removedPackage = p.applicationInfo.packageName;
4376 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004377 }
4378 }
4379
4380 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004381 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004382 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004383 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
4384 PackageParser.PARSE_CHATTY |
4385 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004386 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004387 if (p != null) {
4388 synchronized (mPackages) {
4389 grantPermissionsLP(p, false);
4390 }
4391 addedPackage = p.applicationInfo.packageName;
4392 addedUid = p.applicationInfo.uid;
4393 }
4394 }
4395 }
4396
4397 synchronized (mPackages) {
4398 mSettings.writeLP();
4399 }
4400 }
4401
4402 if (removedPackage != null) {
4403 Bundle extras = new Bundle(1);
4404 extras.putInt(Intent.EXTRA_UID, removedUid);
4405 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4406 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4407 }
4408 if (addedPackage != null) {
4409 Bundle extras = new Bundle(1);
4410 extras.putInt(Intent.EXTRA_UID, addedUid);
4411 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4412 }
4413 }
4414
4415 private final String mRootDir;
4416 private final boolean mIsRom;
4417 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004419 /* Called when a downloaded package installation has been confirmed by the user */
4420 public void installPackage(
4421 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004422 installPackage(packageURI, observer, flags, null);
4423 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004424
Jacek Surazski65e13172009-04-28 15:26:38 +02004425 /* Called when a downloaded package installation has been confirmed by the user */
4426 public void installPackage(
4427 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4428 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004429 mContext.enforceCallingOrSelfPermission(
4430 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004431
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004432 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004433 msg.obj = new InstallParams(packageURI, observer, flags,
4434 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004435 mHandler.sendMessage(msg);
4436 }
4437
Christopher Tate1bb69062010-02-19 17:02:12 -08004438 public void finishPackageInstall(int token) {
4439 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4440 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4441 mHandler.sendMessage(msg);
4442 }
4443
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004444 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004445 // Queue up an async operation since the package installation may take a little while.
4446 mHandler.post(new Runnable() {
4447 public void run() {
4448 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004449 // Result object to be returned
4450 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004451 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004452 res.uid = -1;
4453 res.pkg = null;
4454 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004455 args.doPreInstall(res.returnCode);
4456 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004457 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004458 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004459 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004460 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004461 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004462
4463 // A restore should be performed at this point if (a) the install
4464 // succeeded, (b) the operation is not an update, and (c) the new
4465 // package has a backupAgent defined.
4466 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004467 boolean doRestore = (!update
4468 && res.pkg != null
4469 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004470
4471 // Set up the post-install work request bookkeeping. This will be used
4472 // and cleaned up by the post-install event handling regardless of whether
4473 // there's a restore pass performed. Token values are >= 1.
4474 int token;
4475 if (mNextInstallToken < 0) mNextInstallToken = 1;
4476 token = mNextInstallToken++;
4477
4478 PostInstallData data = new PostInstallData(args, res);
4479 mRunningInstalls.put(token, data);
4480 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4481
4482 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4483 // Pass responsibility to the Backup Manager. It will perform a
4484 // restore if appropriate, then pass responsibility back to the
4485 // Package Manager to run the post-install observer callbacks
4486 // and broadcasts.
4487 IBackupManager bm = IBackupManager.Stub.asInterface(
4488 ServiceManager.getService(Context.BACKUP_SERVICE));
4489 if (bm != null) {
4490 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4491 + " to BM for possible restore");
4492 try {
4493 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4494 } catch (RemoteException e) {
4495 // can't happen; the backup manager is local
4496 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004497 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004498 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004499 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004500 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004501 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004502 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004504 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004505
4506 if (!doRestore) {
4507 // No restore possible, or the Backup Manager was mysteriously not
4508 // available -- just fire the post-install work request directly.
4509 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4510 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4511 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004513 }
4514 });
4515 }
4516
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004517 abstract class HandlerParams {
4518 final static int MAX_RETRIES = 4;
4519 int retry = 0;
4520 final void startCopy() {
4521 try {
4522 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4523 retry++;
4524 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004525 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004526 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4527 handleServiceError();
4528 return;
4529 } else {
4530 handleStartCopy();
4531 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4532 mHandler.sendEmptyMessage(MCS_UNBIND);
4533 }
4534 } catch (RemoteException e) {
4535 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4536 mHandler.sendEmptyMessage(MCS_RECONNECT);
4537 }
4538 handleReturnCode();
4539 }
4540
4541 final void serviceError() {
4542 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4543 handleServiceError();
4544 handleReturnCode();
4545 }
4546 abstract void handleStartCopy() throws RemoteException;
4547 abstract void handleServiceError();
4548 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004549 }
4550
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004551 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004552 final IPackageInstallObserver observer;
4553 int flags;
4554 final Uri packageURI;
4555 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004556 private InstallArgs mArgs;
4557 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004558 InstallParams(Uri packageURI,
4559 IPackageInstallObserver observer, int flags,
4560 String installerPackageName) {
4561 this.packageURI = packageURI;
4562 this.flags = flags;
4563 this.observer = observer;
4564 this.installerPackageName = installerPackageName;
4565 }
4566
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004567 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4568 String packageName = pkgLite.packageName;
4569 int installLocation = pkgLite.installLocation;
4570 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4571 synchronized (mPackages) {
4572 PackageParser.Package pkg = mPackages.get(packageName);
4573 if (pkg != null) {
4574 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4575 // Check for updated system application.
4576 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4577 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004578 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004579 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4580 }
4581 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4582 } else {
4583 // When replacing apps make sure we honour
4584 // the existing app location if not overwritten by other options
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08004585 boolean prevOnSd = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004586 if (onSd) {
4587 // Install flag overrides everything.
4588 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4589 }
4590 // If current upgrade does not specify install location.
4591 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4592 // Application explicitly specified internal.
4593 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4594 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4595 // App explictly prefers external. Let policy decide
4596 } else if (installLocation == PackageInfo.INSTALL_LOCATION_AUTO) {
4597 // Prefer previous location
4598 return prevOnSd ? PackageHelper.RECOMMEND_INSTALL_EXTERNAL:
4599 PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4600 }
4601 }
4602 } else {
4603 // Invalid install. Return error code
4604 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4605 }
4606 }
4607 }
4608 // All the special cases have been taken care of.
4609 // Return result based on recommended install location.
4610 if (onSd) {
4611 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4612 }
4613 return pkgLite.recommendedInstallLocation;
4614 }
4615
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004616 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004617 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004618 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4619 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004620 // Dont need to invoke getInstallLocation for forward locked apps.
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004621 if (fwdLocked && onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004622 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004623 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004624 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004625 // Remote call to find out default install location
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004626 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI);
4627 int loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004628 // Use install location to create InstallArgs and temporary
4629 // install location
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004630 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4631 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4632 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4633 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4634 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004635 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4636 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4637 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
4638 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004639 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004640 if ((flags & PackageManager.INSTALL_EXTERNAL) == 0){
4641 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4642 // Set the flag to install on external media.
4643 flags |= PackageManager.INSTALL_EXTERNAL;
4644 } else {
4645 // Make sure the flag for installing on external
4646 // media is unset
4647 flags &= ~PackageManager.INSTALL_EXTERNAL;
4648 }
4649 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004650 }
4651 }
4652 // Create the file args now.
4653 mArgs = createInstallArgs(this);
4654 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4655 // Create copy only if we are not in an erroneous state.
4656 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004657 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004658 }
4659 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004660 }
4661
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004662 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004663 void handleReturnCode() {
4664 processPendingInstall(mArgs, mRet);
4665 }
4666
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004667 @Override
4668 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004669 mArgs = createInstallArgs(this);
4670 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004671 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004672 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004673
4674 /*
4675 * Utility class used in movePackage api.
4676 * srcArgs and targetArgs are not set for invalid flags and make
4677 * sure to do null checks when invoking methods on them.
4678 * We probably want to return ErrorPrams for both failed installs
4679 * and moves.
4680 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004681 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004682 final IPackageMoveObserver observer;
4683 final int flags;
4684 final String packageName;
4685 final InstallArgs srcArgs;
4686 final InstallArgs targetArgs;
4687 int mRet;
4688 MoveParams(InstallArgs srcArgs,
4689 IPackageMoveObserver observer,
4690 int flags, String packageName) {
4691 this.srcArgs = srcArgs;
4692 this.observer = observer;
4693 this.flags = flags;
4694 this.packageName = packageName;
4695 if (srcArgs != null) {
4696 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4697 targetArgs = createInstallArgs(packageUri, flags, packageName);
4698 } else {
4699 targetArgs = null;
4700 }
4701 }
4702
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004703 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004704 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004705 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004706 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004707 if (DEBUG_SD_INSTALL) {
4708 StringBuilder builder = new StringBuilder();
4709 if (srcArgs != null) {
4710 builder.append("src: ");
4711 builder.append(srcArgs.getCodePath());
4712 }
4713 if (targetArgs != null) {
4714 builder.append(" target : ");
4715 builder.append(targetArgs.getCodePath());
4716 }
4717 Log.i(TAG, "Posting move MCS_UNBIND for " + builder.toString());
4718 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004719 }
4720
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004721 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004722 void handleReturnCode() {
4723 targetArgs.doPostInstall(mRet);
4724 // TODO invoke pending move
4725 processPendingMove(this, mRet);
4726 }
4727
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004728 @Override
4729 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004730 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004731 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004732 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004733
4734 private InstallArgs createInstallArgs(InstallParams params) {
4735 if (installOnSd(params.flags)) {
4736 return new SdInstallArgs(params);
4737 } else {
4738 return new FileInstallArgs(params);
4739 }
4740 }
4741
4742 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4743 if (installOnSd(flags)) {
4744 return new SdInstallArgs(fullCodePath, fullResourcePath);
4745 } else {
4746 return new FileInstallArgs(fullCodePath, fullResourcePath);
4747 }
4748 }
4749
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004750 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4751 if (installOnSd(flags)) {
4752 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4753 return new SdInstallArgs(packageURI, cid);
4754 } else {
4755 return new FileInstallArgs(packageURI, pkgName);
4756 }
4757 }
4758
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004759 static abstract class InstallArgs {
4760 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004761 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004762 final int flags;
4763 final Uri packageURI;
4764 final String installerPackageName;
4765
4766 InstallArgs(Uri packageURI,
4767 IPackageInstallObserver observer, int flags,
4768 String installerPackageName) {
4769 this.packageURI = packageURI;
4770 this.flags = flags;
4771 this.observer = observer;
4772 this.installerPackageName = installerPackageName;
4773 }
4774
4775 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004776 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004777 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004778 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004779 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004780 abstract String getCodePath();
4781 abstract String getResourcePath();
4782 // Need installer lock especially for dex file removal.
4783 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004784 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004785 }
4786
4787 class FileInstallArgs extends InstallArgs {
4788 File installDir;
4789 String codeFileName;
4790 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004791 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004792
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004793 FileInstallArgs(InstallParams params) {
4794 super(params.packageURI, params.observer,
4795 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004796 }
4797
4798 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4799 super(null, null, 0, null);
4800 File codeFile = new File(fullCodePath);
4801 installDir = codeFile.getParentFile();
4802 codeFileName = fullCodePath;
4803 resourceFileName = fullResourcePath;
4804 }
4805
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004806 FileInstallArgs(Uri packageURI, String pkgName) {
4807 super(packageURI, null, 0, null);
4808 boolean fwdLocked = isFwdLocked(flags);
4809 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4810 String apkName = getNextCodePath(null, pkgName, ".apk");
4811 codeFileName = new File(installDir, apkName + ".apk").getPath();
4812 resourceFileName = getResourcePathFromCodePath();
4813 }
4814
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004815 String getCodePath() {
4816 return codeFileName;
4817 }
4818
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004819 void createCopyFile() {
4820 boolean fwdLocked = isFwdLocked(flags);
4821 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4822 codeFileName = createTempPackageFile(installDir).getPath();
4823 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004824 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004825 }
4826
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004827 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004828 if (temp) {
4829 // Generate temp file name
4830 createCopyFile();
4831 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004832 // Get a ParcelFileDescriptor to write to the output file
4833 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004834 if (!created) {
4835 try {
4836 codeFile.createNewFile();
4837 // Set permissions
4838 if (!setPermissions()) {
4839 // Failed setting permissions.
4840 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4841 }
4842 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004843 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004844 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4845 }
4846 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004847 ParcelFileDescriptor out = null;
4848 try {
4849 out = ParcelFileDescriptor.open(codeFile,
4850 ParcelFileDescriptor.MODE_READ_WRITE);
4851 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004852 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004853 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4854 }
4855 // Copy the resource now
4856 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4857 try {
4858 if (imcs.copyResource(packageURI, out)) {
4859 ret = PackageManager.INSTALL_SUCCEEDED;
4860 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004861 } finally {
4862 try { if (out != null) out.close(); } catch (IOException e) {}
4863 }
4864 return ret;
4865 }
4866
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004867 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004868 if (status != PackageManager.INSTALL_SUCCEEDED) {
4869 cleanUp();
4870 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004871 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004872 }
4873
4874 boolean doRename(int status, final String pkgName, String oldCodePath) {
4875 if (status != PackageManager.INSTALL_SUCCEEDED) {
4876 cleanUp();
4877 return false;
4878 } else {
4879 // Rename based on packageName
4880 File codeFile = new File(getCodePath());
4881 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
4882 File desFile = new File(installDir, apkName + ".apk");
4883 if (!codeFile.renameTo(desFile)) {
4884 return false;
4885 }
4886 // Reset paths since the file has been renamed.
4887 codeFileName = desFile.getPath();
4888 resourceFileName = getResourcePathFromCodePath();
4889 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004890 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004891 // Failed setting permissions.
4892 return false;
4893 }
4894 return true;
4895 }
4896 }
4897
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004898 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004899 if (status != PackageManager.INSTALL_SUCCEEDED) {
4900 cleanUp();
4901 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004902 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004903 }
4904
4905 String getResourcePath() {
4906 return resourceFileName;
4907 }
4908
4909 String getResourcePathFromCodePath() {
4910 String codePath = getCodePath();
4911 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4912 String apkNameOnly = getApkName(codePath);
4913 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
4914 } else {
4915 return codePath;
4916 }
4917 }
4918
4919 private boolean cleanUp() {
4920 boolean ret = true;
4921 String sourceDir = getCodePath();
4922 String publicSourceDir = getResourcePath();
4923 if (sourceDir != null) {
4924 File sourceFile = new File(sourceDir);
4925 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004926 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004927 ret = false;
4928 }
4929 // Delete application's code and resources
4930 sourceFile.delete();
4931 }
4932 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4933 final File publicSourceFile = new File(publicSourceDir);
4934 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004935 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004936 }
4937 if (publicSourceFile.exists()) {
4938 publicSourceFile.delete();
4939 }
4940 }
4941 return ret;
4942 }
4943
4944 void cleanUpResourcesLI() {
4945 String sourceDir = getCodePath();
4946 if (cleanUp() && mInstaller != null) {
4947 int retCode = mInstaller.rmdex(sourceDir);
4948 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004949 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004950 + " at location "
4951 + sourceDir + ", retcode=" + retCode);
4952 // we don't consider this to be a failure of the core package deletion
4953 }
4954 }
4955 }
4956
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004957 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004958 // TODO Do this in a more elegant way later on. for now just a hack
4959 if (!isFwdLocked(flags)) {
4960 final int filePermissions =
4961 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4962 |FileUtils.S_IROTH;
4963 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
4964 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004965 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004966 getCodePath()
4967 + ". The return code was: " + retCode);
4968 // TODO Define new internal error
4969 return false;
4970 }
4971 return true;
4972 }
4973 return true;
4974 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004975
4976 boolean doPostDeleteLI(boolean delete) {
4977 cleanUpResourcesLI();
4978 return true;
4979 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004980 }
4981
4982 class SdInstallArgs extends InstallArgs {
4983 String cid;
4984 String cachePath;
4985 static final String RES_FILE_NAME = "pkg.apk";
4986
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004987 SdInstallArgs(InstallParams params) {
4988 super(params.packageURI, params.observer,
4989 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004990 }
4991
4992 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004993 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004994 // Extract cid from fullCodePath
4995 int eidx = fullCodePath.lastIndexOf("/");
4996 String subStr1 = fullCodePath.substring(0, eidx);
4997 int sidx = subStr1.lastIndexOf("/");
4998 cid = subStr1.substring(sidx+1, eidx);
4999 cachePath = subStr1;
5000 }
5001
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005002 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005003 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5004 this.cid = cid;
5005 }
5006
5007 SdInstallArgs(Uri packageURI, String cid) {
5008 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005009 this.cid = cid;
5010 }
5011
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005012 void createCopyFile() {
5013 cid = getTempContainerId();
5014 }
5015
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005016 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005017 if (temp) {
5018 createCopyFile();
5019 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005020 cachePath = imcs.copyResourceToContainer(
5021 packageURI, cid,
5022 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005023 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5024 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005025 }
5026
5027 @Override
5028 String getCodePath() {
5029 return cachePath + "/" + RES_FILE_NAME;
5030 }
5031
5032 @Override
5033 String getResourcePath() {
5034 return cachePath + "/" + RES_FILE_NAME;
5035 }
5036
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005037 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005038 if (status != PackageManager.INSTALL_SUCCEEDED) {
5039 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005040 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005041 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005042 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005043 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005044 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005045 if (cachePath == null) {
5046 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5047 }
5048 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005049 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005050 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005051 }
5052
5053 boolean doRename(int status, final String pkgName,
5054 String oldCodePath) {
5055 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005056 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005057 if (PackageHelper.isContainerMounted(cid)) {
5058 // Unmount the container
5059 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005060 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005061 return false;
5062 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005063 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005064 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005065 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005066 return false;
5067 }
5068 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005069 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005070 newCachePath = PackageHelper.mountSdDir(newCacheId,
5071 getEncryptKey(), Process.SYSTEM_UID);
5072 } else {
5073 newCachePath = PackageHelper.getSdDir(newCacheId);
5074 }
5075 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005076 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005077 return false;
5078 }
5079 Log.i(TAG, "Succesfully renamed " + cid +
5080 " at path: " + cachePath + " to " + newCacheId +
5081 " at new path: " + newCachePath);
5082 cid = newCacheId;
5083 cachePath = newCachePath;
5084 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005085 }
5086
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005087 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005088 if (status != PackageManager.INSTALL_SUCCEEDED) {
5089 cleanUp();
5090 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005091 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005092 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005093 PackageHelper.mountSdDir(cid,
5094 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005095 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005096 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005097 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005098 }
5099
5100 private void cleanUp() {
5101 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005102 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005103 }
5104
5105 void cleanUpResourcesLI() {
5106 String sourceFile = getCodePath();
5107 // Remove dex file
5108 if (mInstaller != null) {
5109 int retCode = mInstaller.rmdex(sourceFile.toString());
5110 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005111 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005112 + " at location "
5113 + sourceFile.toString() + ", retcode=" + retCode);
5114 // we don't consider this to be a failure of the core package deletion
5115 }
5116 }
5117 cleanUp();
5118 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005119
5120 boolean matchContainer(String app) {
5121 if (cid.startsWith(app)) {
5122 return true;
5123 }
5124 return false;
5125 }
5126
5127 String getPackageName() {
5128 int idx = cid.lastIndexOf("-");
5129 if (idx == -1) {
5130 return cid;
5131 }
5132 return cid.substring(0, idx);
5133 }
5134
5135 boolean doPostDeleteLI(boolean delete) {
5136 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005137 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005138 if (mounted) {
5139 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005140 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005141 }
5142 if (ret && delete) {
5143 cleanUpResourcesLI();
5144 }
5145 return ret;
5146 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005147 };
5148
5149 // Utility method used to create code paths based on package name and available index.
5150 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5151 String idxStr = "";
5152 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005153 // Fall back to default value of idx=1 if prefix is not
5154 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005155 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005156 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005157 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005158 if (subStr.endsWith(suffix)) {
5159 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005160 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005161 // If oldCodePath already contains prefix find out the
5162 // ending index to either increment or decrement.
5163 int sidx = subStr.lastIndexOf(prefix);
5164 if (sidx != -1) {
5165 subStr = subStr.substring(sidx + prefix.length());
5166 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005167 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5168 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005169 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005170 try {
5171 idx = Integer.parseInt(subStr);
5172 if (idx <= 1) {
5173 idx++;
5174 } else {
5175 idx--;
5176 }
5177 } catch(NumberFormatException e) {
5178 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005179 }
5180 }
5181 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005182 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005183 return prefix + idxStr;
5184 }
5185
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005186 // Utility method used to ignore ADD/REMOVE events
5187 // by directory observer.
5188 private static boolean ignoreCodePath(String fullPathStr) {
5189 String apkName = getApkName(fullPathStr);
5190 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5191 if (idx != -1 && ((idx+1) < apkName.length())) {
5192 // Make sure the package ends with a numeral
5193 String version = apkName.substring(idx+1);
5194 try {
5195 Integer.parseInt(version);
5196 return true;
5197 } catch (NumberFormatException e) {}
5198 }
5199 return false;
5200 }
5201
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005202 // Utility method that returns the relative package path with respect
5203 // to the installation directory. Like say for /data/data/com.test-1.apk
5204 // string com.test-1 is returned.
5205 static String getApkName(String codePath) {
5206 if (codePath == null) {
5207 return null;
5208 }
5209 int sidx = codePath.lastIndexOf("/");
5210 int eidx = codePath.lastIndexOf(".");
5211 if (eidx == -1) {
5212 eidx = codePath.length();
5213 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005214 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005215 return null;
5216 }
5217 return codePath.substring(sidx+1, eidx);
5218 }
5219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005220 class PackageInstalledInfo {
5221 String name;
5222 int uid;
5223 PackageParser.Package pkg;
5224 int returnCode;
5225 PackageRemovedInfo removedInfo;
5226 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005228 /*
5229 * Install a non-existing package.
5230 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005231 private void installNewPackageLI(PackageParser.Package pkg,
5232 int parseFlags,
5233 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005234 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005235 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005236 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005237
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005238 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005239 res.name = pkgName;
5240 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005241 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005242 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005243 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005244 + " without first uninstalling.");
5245 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5246 return;
5247 }
5248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005249 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005250 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005251 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005252 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005253 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5254 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5255 }
5256 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005257 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005258 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005259 res);
5260 // delete the partially installed application. the data directory will have to be
5261 // restored if it was already existing
5262 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5263 // remove package from internal structures. Note that we want deletePackageX to
5264 // delete the package data and cache directories that it created in
5265 // scanPackageLocked, unless those directories existed before we even tried to
5266 // install.
5267 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005268 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005269 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5270 res.removedInfo);
5271 }
5272 }
5273 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005274
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005275 private void replacePackageLI(PackageParser.Package pkg,
5276 int parseFlags,
5277 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005278 String installerPackageName, PackageInstalledInfo res) {
5279
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005280 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005281 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005282 // First find the old package info and check signatures
5283 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005284 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005285 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005286 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005287 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5288 return;
5289 }
5290 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005291 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005292 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005293 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005294 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005295 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005296 }
5297 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005299 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005300 PackageParser.Package pkg,
5301 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005302 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005303 PackageParser.Package newPackage = null;
5304 String pkgName = deletedPackage.packageName;
5305 boolean deletedPkg = true;
5306 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005307
Jacek Surazski65e13172009-04-28 15:26:38 +02005308 String oldInstallerPackageName = null;
5309 synchronized (mPackages) {
5310 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5311 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005312
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005313 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005314 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005315 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005316 res.removedInfo)) {
5317 // If the existing package was'nt successfully deleted
5318 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5319 deletedPkg = false;
5320 } else {
5321 // Successfully deleted the old package. Now proceed with re-installation
5322 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005323 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005324 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005325 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005326 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5327 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005328 }
5329 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005330 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005331 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005332 res);
5333 updatedSettings = true;
5334 }
5335 }
5336
5337 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5338 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005339 // were keeping around in case we needed them (see below) can now be deleted.
5340 // This info will be set on the res.removedInfo to clean up later on as post
5341 // install action.
5342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005343 //update signature on the new package setting
5344 //this should always succeed, since we checked the
5345 //signature earlier.
5346 synchronized(mPackages) {
5347 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
5348 parseFlags, true);
5349 }
5350 } else {
5351 // remove package from internal structures. Note that we want deletePackageX to
5352 // delete the package data and cache directories that it created in
5353 // scanPackageLocked, unless those directories existed before we even tried to
5354 // install.
5355 if(updatedSettings) {
5356 deletePackageLI(
5357 pkgName, true,
5358 PackageManager.DONT_DELETE_DATA,
5359 res.removedInfo);
5360 }
5361 // Since we failed to install the new package we need to restore the old
5362 // package that we deleted.
5363 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005364 File restoreFile = new File(deletedPackage.mPath);
5365 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005366 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005367 return;
5368 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005369 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5370 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005371 // Parse old package
5372 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5373 scanPackageLI(restoreFile, parseFlags, scanMode);
5374 synchronized (mPackages) {
5375 grantPermissionsLP(deletedPackage, false);
5376 mSettings.writeLP();
5377 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005378 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005379 Slog.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005380 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005381 }
5382 }
5383 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005385 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005386 PackageParser.Package pkg,
5387 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005388 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005389 PackageParser.Package newPackage = null;
5390 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005391 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005392 PackageParser.PARSE_IS_SYSTEM;
5393 String packageName = deletedPackage.packageName;
5394 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5395 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005396 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005397 return;
5398 }
5399 PackageParser.Package oldPkg;
5400 PackageSetting oldPkgSetting;
5401 synchronized (mPackages) {
5402 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005403 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005404 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5405 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005406 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005407 return;
5408 }
5409 }
5410 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5411 res.removedInfo.removedPackage = packageName;
5412 // Remove existing system package
5413 removePackageLI(oldPkg, true);
5414 synchronized (mPackages) {
5415 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5416 }
5417
5418 // Successfully disabled the old package. Now proceed with re-installation
5419 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5420 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005421 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005422 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005423 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005424 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5425 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5426 }
5427 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005428 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005429 updatedSettings = true;
5430 }
5431
5432 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5433 //update signature on the new package setting
5434 //this should always succeed, since we checked the
5435 //signature earlier.
5436 synchronized(mPackages) {
5437 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5438 parseFlags, true);
5439 }
5440 } else {
5441 // Re installation failed. Restore old information
5442 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005443 if (newPackage != null) {
5444 removePackageLI(newPackage, true);
5445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005446 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005447 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005448 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005449 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005450 // Restore the old system information in Settings
5451 synchronized(mPackages) {
5452 if(updatedSettings) {
5453 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005454 mSettings.setInstallerPackageName(packageName,
5455 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005456 }
5457 mSettings.writeLP();
5458 }
5459 }
5460 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005461
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005462 // Utility method used to move dex files during install.
5463 private int moveDexFiles(PackageParser.Package newPackage) {
5464 int retCode;
5465 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5466 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5467 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005468 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005469 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5470 }
5471 }
5472 return PackageManager.INSTALL_SUCCEEDED;
5473 }
5474
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005475 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005476 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005477 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005478 synchronized (mPackages) {
5479 //write settings. the installStatus will be incomplete at this stage.
5480 //note that the new package setting would have already been
5481 //added to mPackages. It hasn't been persisted yet.
5482 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5483 mSettings.writeLP();
5484 }
5485
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005486 if ((res.returnCode = moveDexFiles(newPackage))
5487 != PackageManager.INSTALL_SUCCEEDED) {
5488 // Discontinue if moving dex files failed.
5489 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005490 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005491 if((res.returnCode = setPermissionsLI(newPackage))
5492 != PackageManager.INSTALL_SUCCEEDED) {
5493 if (mInstaller != null) {
5494 mInstaller.rmdex(newPackage.mScanPath);
5495 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005496 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005497 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005498 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005499 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005500 synchronized (mPackages) {
5501 grantPermissionsLP(newPackage, true);
5502 res.name = pkgName;
5503 res.uid = newPackage.applicationInfo.uid;
5504 res.pkg = newPackage;
5505 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005506 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005507 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5508 //to update install status
5509 mSettings.writeLP();
5510 }
5511 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005512
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005513 private void installPackageLI(InstallArgs args,
5514 boolean newInstall, PackageInstalledInfo res) {
5515 int pFlags = args.flags;
5516 String installerPackageName = args.installerPackageName;
5517 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005518 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005519 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005520 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005521 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5522 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005523 // Result object to be returned
5524 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5525
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005526 // Retrieve PackageSettings and parse package
5527 int parseFlags = PackageParser.PARSE_CHATTY |
5528 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5529 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5530 parseFlags |= mDefParseFlags;
5531 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5532 pp.setSeparateProcesses(mSeparateProcesses);
5533 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5534 null, mMetrics, parseFlags);
5535 if (pkg == null) {
5536 res.returnCode = pp.getParseError();
5537 return;
5538 }
5539 String pkgName = res.name = pkg.packageName;
5540 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5541 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5542 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5543 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005544 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005545 }
5546 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5547 res.returnCode = pp.getParseError();
5548 return;
5549 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005550 // Get rid of all references to package scan path via parser.
5551 pp = null;
5552 String oldCodePath = null;
5553 boolean systemApp = false;
5554 synchronized (mPackages) {
5555 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005556 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5557 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005558 if (pkg.mOriginalPackages != null
5559 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005560 && mPackages.containsKey(oldName)) {
5561 // This package is derived from an original package,
5562 // and this device has been updating from that original
5563 // name. We must continue using the original name, so
5564 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005565 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005566 pkgName = pkg.packageName;
5567 replace = true;
5568 } else if (mPackages.containsKey(pkgName)) {
5569 // This package, under its official name, already exists
5570 // on the device; we should replace it.
5571 replace = true;
5572 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005573 }
5574 PackageSetting ps = mSettings.mPackages.get(pkgName);
5575 if (ps != null) {
5576 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5577 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5578 systemApp = (ps.pkg.applicationInfo.flags &
5579 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005580 }
5581 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005582 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005583
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005584 if (systemApp && onSd) {
5585 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005586 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005587 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5588 return;
5589 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005590
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005591 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5592 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5593 return;
5594 }
5595 // Set application objects path explicitly after the rename
5596 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005597 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005598 replacePackageLI(pkg, parseFlags, scanMode,
5599 installerPackageName, res);
5600 } else {
5601 installNewPackageLI(pkg, parseFlags, scanMode,
5602 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005603 }
5604 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005605
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005606 private int setPermissionsLI(PackageParser.Package newPackage) {
5607 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005608 int retCode = 0;
5609 // TODO Gross hack but fix later. Ideally move this to be a post installation
5610 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005611 if ((newPackage.applicationInfo.flags
5612 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5613 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005614 try {
5615 extractPublicFiles(newPackage, destResourceFile);
5616 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005617 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 -08005618 " forward-locked app.");
5619 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5620 } finally {
5621 //TODO clean up the extracted public files
5622 }
5623 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005624 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005625 newPackage.applicationInfo.uid);
5626 } else {
5627 final int filePermissions =
5628 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005629 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005630 newPackage.applicationInfo.uid);
5631 }
5632 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005633 // The permissions on the resource file was set when it was copied for
5634 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005635 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005637 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005638 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005639 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005640 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005641 // TODO Define new internal error
5642 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005643 }
5644 return PackageManager.INSTALL_SUCCEEDED;
5645 }
5646
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005647 private boolean isForwardLocked(PackageParser.Package pkg) {
5648 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 }
5650
5651 private void extractPublicFiles(PackageParser.Package newPackage,
5652 File publicZipFile) throws IOException {
5653 final ZipOutputStream publicZipOutStream =
5654 new ZipOutputStream(new FileOutputStream(publicZipFile));
5655 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5656
5657 // Copy manifest, resources.arsc and res directory to public zip
5658
5659 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5660 while (privateZipEntries.hasMoreElements()) {
5661 final ZipEntry zipEntry = privateZipEntries.nextElement();
5662 final String zipEntryName = zipEntry.getName();
5663 if ("AndroidManifest.xml".equals(zipEntryName)
5664 || "resources.arsc".equals(zipEntryName)
5665 || zipEntryName.startsWith("res/")) {
5666 try {
5667 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5668 } catch (IOException e) {
5669 try {
5670 publicZipOutStream.close();
5671 throw e;
5672 } finally {
5673 publicZipFile.delete();
5674 }
5675 }
5676 }
5677 }
5678
5679 publicZipOutStream.close();
5680 FileUtils.setPermissions(
5681 publicZipFile.getAbsolutePath(),
5682 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5683 -1, -1);
5684 }
5685
5686 private static void copyZipEntry(ZipEntry zipEntry,
5687 ZipFile inZipFile,
5688 ZipOutputStream outZipStream) throws IOException {
5689 byte[] buffer = new byte[4096];
5690 int num;
5691
5692 ZipEntry newEntry;
5693 if (zipEntry.getMethod() == ZipEntry.STORED) {
5694 // Preserve the STORED method of the input entry.
5695 newEntry = new ZipEntry(zipEntry);
5696 } else {
5697 // Create a new entry so that the compressed len is recomputed.
5698 newEntry = new ZipEntry(zipEntry.getName());
5699 }
5700 outZipStream.putNextEntry(newEntry);
5701
5702 InputStream data = inZipFile.getInputStream(zipEntry);
5703 while ((num = data.read(buffer)) > 0) {
5704 outZipStream.write(buffer, 0, num);
5705 }
5706 outZipStream.flush();
5707 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005709 private void deleteTempPackageFiles() {
5710 FilenameFilter filter = new FilenameFilter() {
5711 public boolean accept(File dir, String name) {
5712 return name.startsWith("vmdl") && name.endsWith(".tmp");
5713 }
5714 };
5715 String tmpFilesList[] = mAppInstallDir.list(filter);
5716 if(tmpFilesList == null) {
5717 return;
5718 }
5719 for(int i = 0; i < tmpFilesList.length; i++) {
5720 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5721 tmpFile.delete();
5722 }
5723 }
5724
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005725 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 File tmpPackageFile;
5727 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005728 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005729 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005730 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005731 return null;
5732 }
5733 try {
5734 FileUtils.setPermissions(
5735 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5736 -1, -1);
5737 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005738 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005739 return null;
5740 }
5741 return tmpPackageFile;
5742 }
5743
5744 public void deletePackage(final String packageName,
5745 final IPackageDeleteObserver observer,
5746 final int flags) {
5747 mContext.enforceCallingOrSelfPermission(
5748 android.Manifest.permission.DELETE_PACKAGES, null);
5749 // Queue up an async operation since the package deletion may take a little while.
5750 mHandler.post(new Runnable() {
5751 public void run() {
5752 mHandler.removeCallbacks(this);
5753 final boolean succeded = deletePackageX(packageName, true, true, flags);
5754 if (observer != null) {
5755 try {
5756 observer.packageDeleted(succeded);
5757 } catch (RemoteException e) {
5758 Log.i(TAG, "Observer no longer exists.");
5759 } //end catch
5760 } //end if
5761 } //end run
5762 });
5763 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005765 /**
5766 * This method is an internal method that could be get invoked either
5767 * to delete an installed package or to clean up a failed installation.
5768 * After deleting an installed package, a broadcast is sent to notify any
5769 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005770 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005771 * installation wouldn't have sent the initial broadcast either
5772 * The key steps in deleting a package are
5773 * deleting the package information in internal structures like mPackages,
5774 * deleting the packages base directories through installd
5775 * updating mSettings to reflect current status
5776 * persisting settings for later use
5777 * sending a broadcast if necessary
5778 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005779 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5780 boolean deleteCodeAndResources, int flags) {
5781 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005782 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005783
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005784 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
5785 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
5786 try {
5787 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005788 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005789 return false;
5790 }
5791 } catch (RemoteException e) {
5792 }
5793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005794 synchronized (mInstallLock) {
5795 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5796 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005798 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005799 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5800 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5801
5802 // If the removed package was a system update, the old system packaged
5803 // was re-enabled; we need to broadcast this information
5804 if (systemUpdate) {
5805 Bundle extras = new Bundle(1);
5806 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5807 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5808
5809 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5810 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005812 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005813 // Force a gc here.
5814 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005815 // Delete the resources here after sending the broadcast to let
5816 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005817 if (info.args != null) {
5818 synchronized (mInstallLock) {
5819 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005820 }
5821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005822 return res;
5823 }
5824
5825 static class PackageRemovedInfo {
5826 String removedPackage;
5827 int uid = -1;
5828 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005829 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005830 // Clean up resources deleted packages.
5831 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005833 void sendBroadcast(boolean fullRemove, boolean replacing) {
5834 Bundle extras = new Bundle(1);
5835 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5836 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5837 if (replacing) {
5838 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5839 }
5840 if (removedPackage != null) {
5841 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5842 }
5843 if (removedUid >= 0) {
5844 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5845 }
5846 }
5847 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005849 /*
5850 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5851 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005852 * 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 -08005853 * delete a partially installed application.
5854 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005855 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005856 int flags) {
5857 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005858 if (outInfo != null) {
5859 outInfo.removedPackage = packageName;
5860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005861 removePackageLI(p, true);
5862 // Retrieve object to delete permissions for shared user later on
5863 PackageSetting deletedPs;
5864 synchronized (mPackages) {
5865 deletedPs = mSettings.mPackages.get(packageName);
5866 }
5867 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005868 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005869 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005870 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005871 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005872 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005873 + packageName + ", retcode=" + retCode);
5874 // we don't consider this to be a failure of the core package deletion
5875 }
5876 } else {
5877 //for emulator
5878 PackageParser.Package pkg = mPackages.get(packageName);
5879 File dataDir = new File(pkg.applicationInfo.dataDir);
5880 dataDir.delete();
5881 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005882 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005883 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005884 if (outInfo != null) {
5885 outInfo.removedUid = mSettings.removePackageLP(packageName);
5886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005887 }
5888 }
5889 synchronized (mPackages) {
5890 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5891 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005892 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005893 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005894 if (deletedPs != null) {
5895 // remove from preferred activities.
5896 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
5897 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
5898 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
5899 removed.add(pa);
5900 }
5901 }
5902 for (PreferredActivity pa : removed) {
5903 mSettings.mPreferredActivities.removeFilter(pa);
5904 }
5905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005906 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005907 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005908 }
5909 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005911 /*
5912 * Tries to delete system package.
5913 */
5914 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005915 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005916 ApplicationInfo applicationInfo = p.applicationInfo;
5917 //applicable for non-partially installed applications only
5918 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005919 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005920 return false;
5921 }
5922 PackageSetting ps = null;
5923 // Confirm if the system package has been updated
5924 // An updated system app can be deleted. This will also have to restore
5925 // the system pkg from system partition
5926 synchronized (mPackages) {
5927 ps = mSettings.getDisabledSystemPkg(p.packageName);
5928 }
5929 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005930 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005931 return false;
5932 } else {
5933 Log.i(TAG, "Deleting system pkg from data partition");
5934 }
5935 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005936 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005937 boolean deleteCodeAndResources = false;
5938 if (ps.versionCode < p.mVersionCode) {
5939 // Delete code and resources for downgrades
5940 deleteCodeAndResources = true;
5941 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5942 flags &= ~PackageManager.DONT_DELETE_DATA;
5943 }
5944 } else {
5945 // Preserve data by setting flag
5946 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5947 flags |= PackageManager.DONT_DELETE_DATA;
5948 }
5949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005950 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5951 if (!ret) {
5952 return false;
5953 }
5954 synchronized (mPackages) {
5955 // Reinstate the old system package
5956 mSettings.enableSystemPackageLP(p.packageName);
5957 }
5958 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005959 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005960 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005961 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005964 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005965 return false;
5966 }
5967 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07005968 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005969 mSettings.writeLP();
5970 }
5971 return true;
5972 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005974 private boolean deleteInstalledPackageLI(PackageParser.Package p,
5975 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5976 ApplicationInfo applicationInfo = p.applicationInfo;
5977 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005978 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005979 return false;
5980 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005981 if (outInfo != null) {
5982 outInfo.uid = applicationInfo.uid;
5983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005984
5985 // Delete package data from internal structures and also remove data if flag is set
5986 removePackageDataLI(p, outInfo, flags);
5987
5988 // Delete application code and resources
5989 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005990 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08005991 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005992 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005993 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
5994 PackageManager.INSTALL_FORWARD_LOCK : 0;
5995 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005996 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005997 }
5998 return true;
5999 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 /*
6002 * This method handles package deletion in general
6003 */
6004 private boolean deletePackageLI(String packageName,
6005 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6006 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006007 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006008 return false;
6009 }
6010 PackageParser.Package p;
6011 boolean dataOnly = false;
6012 synchronized (mPackages) {
6013 p = mPackages.get(packageName);
6014 if (p == null) {
6015 //this retrieves partially installed apps
6016 dataOnly = true;
6017 PackageSetting ps = mSettings.mPackages.get(packageName);
6018 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006019 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006020 return false;
6021 }
6022 p = ps.pkg;
6023 }
6024 }
6025 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006026 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006027 return false;
6028 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006030 if (dataOnly) {
6031 // Delete application data first
6032 removePackageDataLI(p, outInfo, flags);
6033 return true;
6034 }
6035 // At this point the package should have ApplicationInfo associated with it
6036 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006037 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006038 return false;
6039 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006040 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006041 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6042 Log.i(TAG, "Removing system package:"+p.packageName);
6043 // When an updated system application is deleted we delete the existing resources as well and
6044 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006045 ret = deleteSystemPackageLI(p, flags, outInfo);
6046 } else {
6047 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006048 // Kill application pre-emptively especially for apps on sd.
6049 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006050 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006051 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006052 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006053 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006055 public void clearApplicationUserData(final String packageName,
6056 final IPackageDataObserver observer) {
6057 mContext.enforceCallingOrSelfPermission(
6058 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6059 // Queue up an async operation since the package deletion may take a little while.
6060 mHandler.post(new Runnable() {
6061 public void run() {
6062 mHandler.removeCallbacks(this);
6063 final boolean succeeded;
6064 synchronized (mInstallLock) {
6065 succeeded = clearApplicationUserDataLI(packageName);
6066 }
6067 if (succeeded) {
6068 // invoke DeviceStorageMonitor's update method to clear any notifications
6069 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6070 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6071 if (dsm != null) {
6072 dsm.updateMemory();
6073 }
6074 }
6075 if(observer != null) {
6076 try {
6077 observer.onRemoveCompleted(packageName, succeeded);
6078 } catch (RemoteException e) {
6079 Log.i(TAG, "Observer no longer exists.");
6080 }
6081 } //end if observer
6082 } //end run
6083 });
6084 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006086 private boolean clearApplicationUserDataLI(String packageName) {
6087 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006088 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006089 return false;
6090 }
6091 PackageParser.Package p;
6092 boolean dataOnly = false;
6093 synchronized (mPackages) {
6094 p = mPackages.get(packageName);
6095 if(p == null) {
6096 dataOnly = true;
6097 PackageSetting ps = mSettings.mPackages.get(packageName);
6098 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006099 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006100 return false;
6101 }
6102 p = ps.pkg;
6103 }
6104 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006105 boolean useEncryptedFSDir = false;
6106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006107 if(!dataOnly) {
6108 //need to check this only for fully installed applications
6109 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006110 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006111 return false;
6112 }
6113 final ApplicationInfo applicationInfo = p.applicationInfo;
6114 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006115 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006116 return false;
6117 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006118 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006119 }
6120 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006121 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006122 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006123 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006124 + packageName);
6125 return false;
6126 }
6127 }
6128 return true;
6129 }
6130
6131 public void deleteApplicationCacheFiles(final String packageName,
6132 final IPackageDataObserver observer) {
6133 mContext.enforceCallingOrSelfPermission(
6134 android.Manifest.permission.DELETE_CACHE_FILES, null);
6135 // Queue up an async operation since the package deletion may take a little while.
6136 mHandler.post(new Runnable() {
6137 public void run() {
6138 mHandler.removeCallbacks(this);
6139 final boolean succeded;
6140 synchronized (mInstallLock) {
6141 succeded = deleteApplicationCacheFilesLI(packageName);
6142 }
6143 if(observer != null) {
6144 try {
6145 observer.onRemoveCompleted(packageName, succeded);
6146 } catch (RemoteException e) {
6147 Log.i(TAG, "Observer no longer exists.");
6148 }
6149 } //end if observer
6150 } //end run
6151 });
6152 }
6153
6154 private boolean deleteApplicationCacheFilesLI(String packageName) {
6155 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006156 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006157 return false;
6158 }
6159 PackageParser.Package p;
6160 synchronized (mPackages) {
6161 p = mPackages.get(packageName);
6162 }
6163 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006164 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006165 return false;
6166 }
6167 final ApplicationInfo applicationInfo = p.applicationInfo;
6168 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006169 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006170 return false;
6171 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006172 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006173 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006174 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006175 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006176 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006177 + packageName);
6178 return false;
6179 }
6180 }
6181 return true;
6182 }
6183
6184 public void getPackageSizeInfo(final String packageName,
6185 final IPackageStatsObserver observer) {
6186 mContext.enforceCallingOrSelfPermission(
6187 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6188 // Queue up an async operation since the package deletion may take a little while.
6189 mHandler.post(new Runnable() {
6190 public void run() {
6191 mHandler.removeCallbacks(this);
6192 PackageStats lStats = new PackageStats(packageName);
6193 final boolean succeded;
6194 synchronized (mInstallLock) {
6195 succeded = getPackageSizeInfoLI(packageName, lStats);
6196 }
6197 if(observer != null) {
6198 try {
6199 observer.onGetStatsCompleted(lStats, succeded);
6200 } catch (RemoteException e) {
6201 Log.i(TAG, "Observer no longer exists.");
6202 }
6203 } //end if observer
6204 } //end run
6205 });
6206 }
6207
6208 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6209 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006210 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006211 return false;
6212 }
6213 PackageParser.Package p;
6214 boolean dataOnly = false;
6215 synchronized (mPackages) {
6216 p = mPackages.get(packageName);
6217 if(p == null) {
6218 dataOnly = true;
6219 PackageSetting ps = mSettings.mPackages.get(packageName);
6220 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006221 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006222 return false;
6223 }
6224 p = ps.pkg;
6225 }
6226 }
6227 String publicSrcDir = null;
6228 if(!dataOnly) {
6229 final ApplicationInfo applicationInfo = p.applicationInfo;
6230 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006231 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006232 return false;
6233 }
6234 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6235 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006236 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 if (mInstaller != null) {
6238 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006239 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006240 if (res < 0) {
6241 return false;
6242 } else {
6243 return true;
6244 }
6245 }
6246 return true;
6247 }
6248
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250 public void addPackageToPreferred(String packageName) {
6251 mContext.enforceCallingOrSelfPermission(
6252 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006253 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006254 }
6255
6256 public void removePackageFromPreferred(String packageName) {
6257 mContext.enforceCallingOrSelfPermission(
6258 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006259 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006260 }
6261
6262 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006263 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 }
6265
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006266 int getUidTargetSdkVersionLockedLP(int uid) {
6267 Object obj = mSettings.getUserIdLP(uid);
6268 if (obj instanceof SharedUserSetting) {
6269 SharedUserSetting sus = (SharedUserSetting)obj;
6270 final int N = sus.packages.size();
6271 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6272 Iterator<PackageSetting> it = sus.packages.iterator();
6273 int i=0;
6274 while (it.hasNext()) {
6275 PackageSetting ps = it.next();
6276 if (ps.pkg != null) {
6277 int v = ps.pkg.applicationInfo.targetSdkVersion;
6278 if (v < vers) vers = v;
6279 }
6280 }
6281 return vers;
6282 } else if (obj instanceof PackageSetting) {
6283 PackageSetting ps = (PackageSetting)obj;
6284 if (ps.pkg != null) {
6285 return ps.pkg.applicationInfo.targetSdkVersion;
6286 }
6287 }
6288 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6289 }
6290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006291 public void addPreferredActivity(IntentFilter filter, int match,
6292 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006293 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006294 if (mContext.checkCallingOrSelfPermission(
6295 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6296 != PackageManager.PERMISSION_GRANTED) {
6297 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6298 < Build.VERSION_CODES.FROYO) {
6299 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6300 + Binder.getCallingUid());
6301 return;
6302 }
6303 mContext.enforceCallingOrSelfPermission(
6304 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6305 }
6306
6307 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006308 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6309 mSettings.mPreferredActivities.addFilter(
6310 new PreferredActivity(filter, match, set, activity));
6311 mSettings.writeLP();
6312 }
6313 }
6314
Satish Sampath8dbe6122009-06-02 23:35:54 +01006315 public void replacePreferredActivity(IntentFilter filter, int match,
6316 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006317 if (filter.countActions() != 1) {
6318 throw new IllegalArgumentException(
6319 "replacePreferredActivity expects filter to have only 1 action.");
6320 }
6321 if (filter.countCategories() != 1) {
6322 throw new IllegalArgumentException(
6323 "replacePreferredActivity expects filter to have only 1 category.");
6324 }
6325 if (filter.countDataAuthorities() != 0
6326 || filter.countDataPaths() != 0
6327 || filter.countDataSchemes() != 0
6328 || filter.countDataTypes() != 0) {
6329 throw new IllegalArgumentException(
6330 "replacePreferredActivity expects filter to have no data authorities, " +
6331 "paths, schemes or types.");
6332 }
6333 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006334 if (mContext.checkCallingOrSelfPermission(
6335 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6336 != PackageManager.PERMISSION_GRANTED) {
6337 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6338 < Build.VERSION_CODES.FROYO) {
6339 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6340 + Binder.getCallingUid());
6341 return;
6342 }
6343 mContext.enforceCallingOrSelfPermission(
6344 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6345 }
6346
Satish Sampath8dbe6122009-06-02 23:35:54 +01006347 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6348 String action = filter.getAction(0);
6349 String category = filter.getCategory(0);
6350 while (it.hasNext()) {
6351 PreferredActivity pa = it.next();
6352 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6353 it.remove();
6354 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6355 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6356 }
6357 }
6358 addPreferredActivity(filter, match, set, activity);
6359 }
6360 }
6361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006362 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006364 int uid = Binder.getCallingUid();
6365 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006366 if (pkg == null || pkg.applicationInfo.uid != uid) {
6367 if (mContext.checkCallingOrSelfPermission(
6368 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6369 != PackageManager.PERMISSION_GRANTED) {
6370 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6371 < Build.VERSION_CODES.FROYO) {
6372 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6373 + Binder.getCallingUid());
6374 return;
6375 }
6376 mContext.enforceCallingOrSelfPermission(
6377 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6378 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006379 }
6380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006381 if (clearPackagePreferredActivitiesLP(packageName)) {
6382 mSettings.writeLP();
6383 }
6384 }
6385 }
6386
6387 boolean clearPackagePreferredActivitiesLP(String packageName) {
6388 boolean changed = false;
6389 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6390 while (it.hasNext()) {
6391 PreferredActivity pa = it.next();
6392 if (pa.mActivity.getPackageName().equals(packageName)) {
6393 it.remove();
6394 changed = true;
6395 }
6396 }
6397 return changed;
6398 }
6399
6400 public int getPreferredActivities(List<IntentFilter> outFilters,
6401 List<ComponentName> outActivities, String packageName) {
6402
6403 int num = 0;
6404 synchronized (mPackages) {
6405 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6406 while (it.hasNext()) {
6407 PreferredActivity pa = it.next();
6408 if (packageName == null
6409 || pa.mActivity.getPackageName().equals(packageName)) {
6410 if (outFilters != null) {
6411 outFilters.add(new IntentFilter(pa));
6412 }
6413 if (outActivities != null) {
6414 outActivities.add(pa.mActivity);
6415 }
6416 }
6417 }
6418 }
6419
6420 return num;
6421 }
6422
6423 public void setApplicationEnabledSetting(String appPackageName,
6424 int newState, int flags) {
6425 setEnabledSetting(appPackageName, null, newState, flags);
6426 }
6427
6428 public void setComponentEnabledSetting(ComponentName componentName,
6429 int newState, int flags) {
6430 setEnabledSetting(componentName.getPackageName(),
6431 componentName.getClassName(), newState, flags);
6432 }
6433
6434 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006435 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006436 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6437 || newState == COMPONENT_ENABLED_STATE_ENABLED
6438 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6439 throw new IllegalArgumentException("Invalid new component state: "
6440 + newState);
6441 }
6442 PackageSetting pkgSetting;
6443 final int uid = Binder.getCallingUid();
6444 final int permission = mContext.checkCallingPermission(
6445 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6446 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006447 boolean sendNow = false;
6448 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006449 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006450 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006451 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006452 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006453 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006455 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006456 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006457 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006458 }
6459 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006460 "Unknown component: " + packageName
6461 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 }
6463 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6464 throw new SecurityException(
6465 "Permission Denial: attempt to change component state from pid="
6466 + Binder.getCallingPid()
6467 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6468 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006469 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006470 // We're dealing with an application/package level state change
6471 pkgSetting.enabled = newState;
6472 } else {
6473 // We're dealing with a component level state change
6474 switch (newState) {
6475 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006476 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 break;
6478 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006479 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006480 break;
6481 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006482 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006483 break;
6484 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006485 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006486 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 }
6488 }
6489 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006490 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006491 components = mPendingBroadcasts.get(packageName);
6492 boolean newPackage = components == null;
6493 if (newPackage) {
6494 components = new ArrayList<String>();
6495 }
6496 if (!components.contains(componentName)) {
6497 components.add(componentName);
6498 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006499 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6500 sendNow = true;
6501 // Purge entry from pending broadcast list if another one exists already
6502 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006503 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006504 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006505 if (newPackage) {
6506 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006507 }
6508 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6509 // Schedule a message
6510 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6511 }
6512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006513 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006515 long callingId = Binder.clearCallingIdentity();
6516 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006517 if (sendNow) {
6518 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006519 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006521 } finally {
6522 Binder.restoreCallingIdentity(callingId);
6523 }
6524 }
6525
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006526 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006527 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6528 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6529 + " components=" + componentNames);
6530 Bundle extras = new Bundle(4);
6531 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6532 String nameList[] = new String[componentNames.size()];
6533 componentNames.toArray(nameList);
6534 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006535 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6536 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006537 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006538 }
6539
Jacek Surazski65e13172009-04-28 15:26:38 +02006540 public String getInstallerPackageName(String packageName) {
6541 synchronized (mPackages) {
6542 PackageSetting pkg = mSettings.mPackages.get(packageName);
6543 if (pkg == null) {
6544 throw new IllegalArgumentException("Unknown package: " + packageName);
6545 }
6546 return pkg.installerPackageName;
6547 }
6548 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006550 public int getApplicationEnabledSetting(String appPackageName) {
6551 synchronized (mPackages) {
6552 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6553 if (pkg == null) {
6554 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6555 }
6556 return pkg.enabled;
6557 }
6558 }
6559
6560 public int getComponentEnabledSetting(ComponentName componentName) {
6561 synchronized (mPackages) {
6562 final String packageNameStr = componentName.getPackageName();
6563 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6564 if (pkg == null) {
6565 throw new IllegalArgumentException("Unknown component: " + componentName);
6566 }
6567 final String classNameStr = componentName.getClassName();
6568 return pkg.currentEnabledStateLP(classNameStr);
6569 }
6570 }
6571
6572 public void enterSafeMode() {
6573 if (!mSystemReady) {
6574 mSafeMode = true;
6575 }
6576 }
6577
6578 public void systemReady() {
6579 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006580
6581 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006582 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006583 mContext.getContentResolver(),
6584 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006585 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006586 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006587 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006589 }
6590
6591 public boolean isSafeMode() {
6592 return mSafeMode;
6593 }
6594
6595 public boolean hasSystemUidErrors() {
6596 return mHasSystemUidErrors;
6597 }
6598
6599 static String arrayToString(int[] array) {
6600 StringBuffer buf = new StringBuffer(128);
6601 buf.append('[');
6602 if (array != null) {
6603 for (int i=0; i<array.length; i++) {
6604 if (i > 0) buf.append(", ");
6605 buf.append(array[i]);
6606 }
6607 }
6608 buf.append(']');
6609 return buf.toString();
6610 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 @Override
6613 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6614 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6615 != PackageManager.PERMISSION_GRANTED) {
6616 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6617 + Binder.getCallingPid()
6618 + ", uid=" + Binder.getCallingUid()
6619 + " without permission "
6620 + android.Manifest.permission.DUMP);
6621 return;
6622 }
6623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006624 synchronized (mPackages) {
6625 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006626 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006627 pw.println(" ");
6628 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006629 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006630 pw.println(" ");
6631 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006632 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006633 pw.println(" ");
6634 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006635 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006636 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006637 pw.println("Permissions:");
6638 {
6639 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006640 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6641 pw.print(Integer.toHexString(System.identityHashCode(p)));
6642 pw.println("):");
6643 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6644 pw.print(" uid="); pw.print(p.uid);
6645 pw.print(" gids="); pw.print(arrayToString(p.gids));
6646 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006647 }
6648 }
6649 pw.println(" ");
6650 pw.println("Packages:");
6651 {
6652 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006653 pw.print(" Package [");
6654 pw.print(ps.realName != null ? ps.realName : ps.name);
6655 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006656 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6657 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006658 if (ps.realName != null) {
6659 pw.print(" compat name="); pw.println(ps.name);
6660 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006661 pw.print(" userId="); pw.print(ps.userId);
6662 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6663 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6664 pw.print(" pkg="); pw.println(ps.pkg);
6665 pw.print(" codePath="); pw.println(ps.codePathString);
6666 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006668 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006669 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006670 pw.print(" supportsScreens=[");
6671 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006672 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006673 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006674 if (!first) pw.print(", ");
6675 first = false;
6676 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006677 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006678 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006679 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006680 if (!first) pw.print(", ");
6681 first = false;
6682 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006683 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006684 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006685 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006686 if (!first) pw.print(", ");
6687 first = false;
6688 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006689 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006690 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006691 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006692 if (!first) pw.print(", ");
6693 first = false;
6694 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006695 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006696 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006697 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6698 if (!first) pw.print(", ");
6699 first = false;
6700 pw.print("anyDensity");
6701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006702 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006703 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006704 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6705 pw.print(" signatures="); pw.println(ps.signatures);
6706 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6707 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6708 pw.print(" installStatus="); pw.print(ps.installStatus);
6709 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006710 if (ps.disabledComponents.size() > 0) {
6711 pw.println(" disabledComponents:");
6712 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006713 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006714 }
6715 }
6716 if (ps.enabledComponents.size() > 0) {
6717 pw.println(" enabledComponents:");
6718 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006719 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006720 }
6721 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006722 if (ps.grantedPermissions.size() > 0) {
6723 pw.println(" grantedPermissions:");
6724 for (String s : ps.grantedPermissions) {
6725 pw.print(" "); pw.println(s);
6726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006727 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006728 if (ps.loadedPermissions.size() > 0) {
6729 pw.println(" loadedPermissions:");
6730 for (String s : ps.loadedPermissions) {
6731 pw.print(" "); pw.println(s);
6732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006733 }
6734 }
6735 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006736 if (mSettings.mRenamedPackages.size() > 0) {
6737 pw.println(" ");
6738 pw.println("Renamed packages:");
6739 for (HashMap.Entry<String, String> e
6740 : mSettings.mRenamedPackages.entrySet()) {
6741 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6742 pw.println(e.getValue());
6743 }
6744 }
6745 if (mSettings.mDisabledSysPackages.size() > 0) {
6746 pw.println(" ");
6747 pw.println("Hidden system packages:");
6748 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
6749 pw.print(" Package [");
6750 pw.print(ps.realName != null ? ps.realName : ps.name);
6751 pw.print("] (");
6752 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6753 pw.println("):");
6754 if (ps.realName != null) {
6755 pw.print(" compat name="); pw.println(ps.name);
6756 }
6757 pw.print(" userId="); pw.println(ps.userId);
6758 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6759 pw.print(" codePath="); pw.println(ps.codePathString);
6760 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
6761 }
6762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006763 pw.println(" ");
6764 pw.println("Shared Users:");
6765 {
6766 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006767 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6768 pw.print(Integer.toHexString(System.identityHashCode(su)));
6769 pw.println("):");
6770 pw.print(" userId="); pw.print(su.userId);
6771 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006772 pw.println(" grantedPermissions:");
6773 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006774 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006775 }
6776 pw.println(" loadedPermissions:");
6777 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006778 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006779 }
6780 }
6781 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006783 pw.println(" ");
6784 pw.println("Settings parse messages:");
6785 pw.println(mSettings.mReadMessages.toString());
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006786
6787 pw.println(" ");
6788 pw.println("Package warning messages:");
6789 File fname = getSettingsProblemFile();
6790 FileInputStream in;
6791 try {
6792 in = new FileInputStream(fname);
6793 int avail = in.available();
6794 byte[] data = new byte[avail];
6795 in.read(data);
6796 pw.println(new String(data));
6797 } catch (FileNotFoundException e) {
6798 } catch (IOException e) {
6799 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006800 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006801
6802 synchronized (mProviders) {
6803 pw.println(" ");
6804 pw.println("Registered ContentProviders:");
6805 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006806 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006807 pw.println(p.toString());
6808 }
6809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006810 }
6811
6812 static final class BasePermission {
6813 final static int TYPE_NORMAL = 0;
6814 final static int TYPE_BUILTIN = 1;
6815 final static int TYPE_DYNAMIC = 2;
6816
6817 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006818 String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006819 final int type;
6820 PackageParser.Permission perm;
6821 PermissionInfo pendingInfo;
6822 int uid;
6823 int[] gids;
6824
6825 BasePermission(String _name, String _sourcePackage, int _type) {
6826 name = _name;
6827 sourcePackage = _sourcePackage;
6828 type = _type;
6829 }
6830 }
6831
6832 static class PackageSignatures {
6833 private Signature[] mSignatures;
6834
6835 PackageSignatures(Signature[] sigs) {
6836 assignSignatures(sigs);
6837 }
6838
6839 PackageSignatures() {
6840 }
6841
6842 void writeXml(XmlSerializer serializer, String tagName,
6843 ArrayList<Signature> pastSignatures) throws IOException {
6844 if (mSignatures == null) {
6845 return;
6846 }
6847 serializer.startTag(null, tagName);
6848 serializer.attribute(null, "count",
6849 Integer.toString(mSignatures.length));
6850 for (int i=0; i<mSignatures.length; i++) {
6851 serializer.startTag(null, "cert");
6852 final Signature sig = mSignatures[i];
6853 final int sigHash = sig.hashCode();
6854 final int numPast = pastSignatures.size();
6855 int j;
6856 for (j=0; j<numPast; j++) {
6857 Signature pastSig = pastSignatures.get(j);
6858 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
6859 serializer.attribute(null, "index", Integer.toString(j));
6860 break;
6861 }
6862 }
6863 if (j >= numPast) {
6864 pastSignatures.add(sig);
6865 serializer.attribute(null, "index", Integer.toString(numPast));
6866 serializer.attribute(null, "key", sig.toCharsString());
6867 }
6868 serializer.endTag(null, "cert");
6869 }
6870 serializer.endTag(null, tagName);
6871 }
6872
6873 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
6874 throws IOException, XmlPullParserException {
6875 String countStr = parser.getAttributeValue(null, "count");
6876 if (countStr == null) {
6877 reportSettingsProblem(Log.WARN,
6878 "Error in package manager settings: <signatures> has"
6879 + " no count at " + parser.getPositionDescription());
6880 XmlUtils.skipCurrentTag(parser);
6881 }
6882 final int count = Integer.parseInt(countStr);
6883 mSignatures = new Signature[count];
6884 int pos = 0;
6885
6886 int outerDepth = parser.getDepth();
6887 int type;
6888 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6889 && (type != XmlPullParser.END_TAG
6890 || parser.getDepth() > outerDepth)) {
6891 if (type == XmlPullParser.END_TAG
6892 || type == XmlPullParser.TEXT) {
6893 continue;
6894 }
6895
6896 String tagName = parser.getName();
6897 if (tagName.equals("cert")) {
6898 if (pos < count) {
6899 String index = parser.getAttributeValue(null, "index");
6900 if (index != null) {
6901 try {
6902 int idx = Integer.parseInt(index);
6903 String key = parser.getAttributeValue(null, "key");
6904 if (key == null) {
6905 if (idx >= 0 && idx < pastSignatures.size()) {
6906 Signature sig = pastSignatures.get(idx);
6907 if (sig != null) {
6908 mSignatures[pos] = pastSignatures.get(idx);
6909 pos++;
6910 } else {
6911 reportSettingsProblem(Log.WARN,
6912 "Error in package manager settings: <cert> "
6913 + "index " + index + " is not defined at "
6914 + parser.getPositionDescription());
6915 }
6916 } else {
6917 reportSettingsProblem(Log.WARN,
6918 "Error in package manager settings: <cert> "
6919 + "index " + index + " is out of bounds at "
6920 + parser.getPositionDescription());
6921 }
6922 } else {
6923 while (pastSignatures.size() <= idx) {
6924 pastSignatures.add(null);
6925 }
6926 Signature sig = new Signature(key);
6927 pastSignatures.set(idx, sig);
6928 mSignatures[pos] = sig;
6929 pos++;
6930 }
6931 } catch (NumberFormatException e) {
6932 reportSettingsProblem(Log.WARN,
6933 "Error in package manager settings: <cert> "
6934 + "index " + index + " is not a number at "
6935 + parser.getPositionDescription());
6936 }
6937 } else {
6938 reportSettingsProblem(Log.WARN,
6939 "Error in package manager settings: <cert> has"
6940 + " no index at " + parser.getPositionDescription());
6941 }
6942 } else {
6943 reportSettingsProblem(Log.WARN,
6944 "Error in package manager settings: too "
6945 + "many <cert> tags, expected " + count
6946 + " at " + parser.getPositionDescription());
6947 }
6948 } else {
6949 reportSettingsProblem(Log.WARN,
6950 "Unknown element under <cert>: "
6951 + parser.getName());
6952 }
6953 XmlUtils.skipCurrentTag(parser);
6954 }
6955
6956 if (pos < count) {
6957 // Should never happen -- there is an error in the written
6958 // settings -- but if it does we don't want to generate
6959 // a bad array.
6960 Signature[] newSigs = new Signature[pos];
6961 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6962 mSignatures = newSigs;
6963 }
6964 }
6965
6966 /**
6967 * If any of the given 'sigs' is contained in the existing signatures,
6968 * then completely replace the current signatures with the ones in
6969 * 'sigs'. This is used for updating an existing package to a newly
6970 * installed version.
6971 */
6972 boolean updateSignatures(Signature[] sigs, boolean update) {
6973 if (mSignatures == null) {
6974 if (update) {
6975 assignSignatures(sigs);
6976 }
6977 return true;
6978 }
6979 if (sigs == null) {
6980 return false;
6981 }
6982
6983 for (int i=0; i<sigs.length; i++) {
6984 Signature sig = sigs[i];
6985 for (int j=0; j<mSignatures.length; j++) {
6986 if (mSignatures[j].equals(sig)) {
6987 if (update) {
6988 assignSignatures(sigs);
6989 }
6990 return true;
6991 }
6992 }
6993 }
6994 return false;
6995 }
6996
6997 /**
6998 * If any of the given 'sigs' is contained in the existing signatures,
6999 * then add in any new signatures found in 'sigs'. This is used for
7000 * including a new package into an existing shared user id.
7001 */
7002 boolean mergeSignatures(Signature[] sigs, boolean update) {
7003 if (mSignatures == null) {
7004 if (update) {
7005 assignSignatures(sigs);
7006 }
7007 return true;
7008 }
7009 if (sigs == null) {
7010 return false;
7011 }
7012
7013 Signature[] added = null;
7014 int addedCount = 0;
7015 boolean haveMatch = false;
7016 for (int i=0; i<sigs.length; i++) {
7017 Signature sig = sigs[i];
7018 boolean found = false;
7019 for (int j=0; j<mSignatures.length; j++) {
7020 if (mSignatures[j].equals(sig)) {
7021 found = true;
7022 haveMatch = true;
7023 break;
7024 }
7025 }
7026
7027 if (!found) {
7028 if (added == null) {
7029 added = new Signature[sigs.length];
7030 }
7031 added[i] = sig;
7032 addedCount++;
7033 }
7034 }
7035
7036 if (!haveMatch) {
7037 // Nothing matched -- reject the new signatures.
7038 return false;
7039 }
7040 if (added == null) {
7041 // Completely matched -- nothing else to do.
7042 return true;
7043 }
7044
7045 // Add additional signatures in.
7046 if (update) {
7047 Signature[] total = new Signature[addedCount+mSignatures.length];
7048 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
7049 int j = mSignatures.length;
7050 for (int i=0; i<added.length; i++) {
7051 if (added[i] != null) {
7052 total[j] = added[i];
7053 j++;
7054 }
7055 }
7056 mSignatures = total;
7057 }
7058 return true;
7059 }
7060
7061 private void assignSignatures(Signature[] sigs) {
7062 if (sigs == null) {
7063 mSignatures = null;
7064 return;
7065 }
7066 mSignatures = new Signature[sigs.length];
7067 for (int i=0; i<sigs.length; i++) {
7068 mSignatures[i] = sigs[i];
7069 }
7070 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007072 @Override
7073 public String toString() {
7074 StringBuffer buf = new StringBuffer(128);
7075 buf.append("PackageSignatures{");
7076 buf.append(Integer.toHexString(System.identityHashCode(this)));
7077 buf.append(" [");
7078 if (mSignatures != null) {
7079 for (int i=0; i<mSignatures.length; i++) {
7080 if (i > 0) buf.append(", ");
7081 buf.append(Integer.toHexString(
7082 System.identityHashCode(mSignatures[i])));
7083 }
7084 }
7085 buf.append("]}");
7086 return buf.toString();
7087 }
7088 }
7089
7090 static class PreferredActivity extends IntentFilter {
7091 final int mMatch;
7092 final String[] mSetPackages;
7093 final String[] mSetClasses;
7094 final String[] mSetComponents;
7095 final ComponentName mActivity;
7096 final String mShortActivity;
7097 String mParseError;
7098
7099 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7100 ComponentName activity) {
7101 super(filter);
7102 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7103 mActivity = activity;
7104 mShortActivity = activity.flattenToShortString();
7105 mParseError = null;
7106 if (set != null) {
7107 final int N = set.length;
7108 String[] myPackages = new String[N];
7109 String[] myClasses = new String[N];
7110 String[] myComponents = new String[N];
7111 for (int i=0; i<N; i++) {
7112 ComponentName cn = set[i];
7113 if (cn == null) {
7114 mSetPackages = null;
7115 mSetClasses = null;
7116 mSetComponents = null;
7117 return;
7118 }
7119 myPackages[i] = cn.getPackageName().intern();
7120 myClasses[i] = cn.getClassName().intern();
7121 myComponents[i] = cn.flattenToShortString().intern();
7122 }
7123 mSetPackages = myPackages;
7124 mSetClasses = myClasses;
7125 mSetComponents = myComponents;
7126 } else {
7127 mSetPackages = null;
7128 mSetClasses = null;
7129 mSetComponents = null;
7130 }
7131 }
7132
7133 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7134 IOException {
7135 mShortActivity = parser.getAttributeValue(null, "name");
7136 mActivity = ComponentName.unflattenFromString(mShortActivity);
7137 if (mActivity == null) {
7138 mParseError = "Bad activity name " + mShortActivity;
7139 }
7140 String matchStr = parser.getAttributeValue(null, "match");
7141 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7142 String setCountStr = parser.getAttributeValue(null, "set");
7143 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7144
7145 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7146 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7147 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7148
7149 int setPos = 0;
7150
7151 int outerDepth = parser.getDepth();
7152 int type;
7153 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7154 && (type != XmlPullParser.END_TAG
7155 || parser.getDepth() > outerDepth)) {
7156 if (type == XmlPullParser.END_TAG
7157 || type == XmlPullParser.TEXT) {
7158 continue;
7159 }
7160
7161 String tagName = parser.getName();
7162 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7163 // + parser.getDepth() + " tag=" + tagName);
7164 if (tagName.equals("set")) {
7165 String name = parser.getAttributeValue(null, "name");
7166 if (name == null) {
7167 if (mParseError == null) {
7168 mParseError = "No name in set tag in preferred activity "
7169 + mShortActivity;
7170 }
7171 } else if (setPos >= setCount) {
7172 if (mParseError == null) {
7173 mParseError = "Too many set tags in preferred activity "
7174 + mShortActivity;
7175 }
7176 } else {
7177 ComponentName cn = ComponentName.unflattenFromString(name);
7178 if (cn == null) {
7179 if (mParseError == null) {
7180 mParseError = "Bad set name " + name + " in preferred activity "
7181 + mShortActivity;
7182 }
7183 } else {
7184 myPackages[setPos] = cn.getPackageName();
7185 myClasses[setPos] = cn.getClassName();
7186 myComponents[setPos] = name;
7187 setPos++;
7188 }
7189 }
7190 XmlUtils.skipCurrentTag(parser);
7191 } else if (tagName.equals("filter")) {
7192 //Log.i(TAG, "Starting to parse filter...");
7193 readFromXml(parser);
7194 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7195 // + parser.getDepth() + " tag=" + parser.getName());
7196 } else {
7197 reportSettingsProblem(Log.WARN,
7198 "Unknown element under <preferred-activities>: "
7199 + parser.getName());
7200 XmlUtils.skipCurrentTag(parser);
7201 }
7202 }
7203
7204 if (setPos != setCount) {
7205 if (mParseError == null) {
7206 mParseError = "Not enough set tags (expected " + setCount
7207 + " but found " + setPos + ") in " + mShortActivity;
7208 }
7209 }
7210
7211 mSetPackages = myPackages;
7212 mSetClasses = myClasses;
7213 mSetComponents = myComponents;
7214 }
7215
7216 public void writeToXml(XmlSerializer serializer) throws IOException {
7217 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7218 serializer.attribute(null, "name", mShortActivity);
7219 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7220 serializer.attribute(null, "set", Integer.toString(NS));
7221 for (int s=0; s<NS; s++) {
7222 serializer.startTag(null, "set");
7223 serializer.attribute(null, "name", mSetComponents[s]);
7224 serializer.endTag(null, "set");
7225 }
7226 serializer.startTag(null, "filter");
7227 super.writeToXml(serializer);
7228 serializer.endTag(null, "filter");
7229 }
7230
7231 boolean sameSet(List<ResolveInfo> query, int priority) {
7232 if (mSetPackages == null) return false;
7233 final int NQ = query.size();
7234 final int NS = mSetPackages.length;
7235 int numMatch = 0;
7236 for (int i=0; i<NQ; i++) {
7237 ResolveInfo ri = query.get(i);
7238 if (ri.priority != priority) continue;
7239 ActivityInfo ai = ri.activityInfo;
7240 boolean good = false;
7241 for (int j=0; j<NS; j++) {
7242 if (mSetPackages[j].equals(ai.packageName)
7243 && mSetClasses[j].equals(ai.name)) {
7244 numMatch++;
7245 good = true;
7246 break;
7247 }
7248 }
7249 if (!good) return false;
7250 }
7251 return numMatch == NS;
7252 }
7253 }
7254
7255 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007256 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007258 HashSet<String> grantedPermissions = new HashSet<String>();
7259 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007261 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007263 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007264 setFlags(pkgFlags);
7265 }
7266
7267 void setFlags(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007268 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007269 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08007270 (pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) |
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08007271 (pkgFlags & ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007272 }
7273 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007275 /**
7276 * Settings base class for pending and resolved classes.
7277 */
7278 static class PackageSettingBase extends GrantedPermissions {
7279 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007280 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007281 File codePath;
7282 String codePathString;
7283 File resourcePath;
7284 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007285 private long timeStamp;
7286 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007287 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007288
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007289 boolean uidError;
7290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007291 PackageSignatures signatures = new PackageSignatures();
7292
7293 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007295 /* Explicitly disabled components */
7296 HashSet<String> disabledComponents = new HashSet<String>(0);
7297 /* Explicitly enabled components */
7298 HashSet<String> enabledComponents = new HashSet<String>(0);
7299 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7300 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007301
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007302 PackageSettingBase origPackage;
7303
Jacek Surazski65e13172009-04-28 15:26:38 +02007304 /* package name of the app that installed this package */
7305 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007306
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007307 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007308 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007309 super(pkgFlags);
7310 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007311 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007312 init(codePath, resourcePath, pVersionCode);
7313 }
7314
7315 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007316 this.codePath = codePath;
7317 this.codePathString = codePath.toString();
7318 this.resourcePath = resourcePath;
7319 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007320 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007321 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007322
Jacek Surazski65e13172009-04-28 15:26:38 +02007323 public void setInstallerPackageName(String packageName) {
7324 installerPackageName = packageName;
7325 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007326
Jacek Surazski65e13172009-04-28 15:26:38 +02007327 String getInstallerPackageName() {
7328 return installerPackageName;
7329 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007331 public void setInstallStatus(int newStatus) {
7332 installStatus = newStatus;
7333 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007335 public int getInstallStatus() {
7336 return installStatus;
7337 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007339 public void setTimeStamp(long newStamp) {
7340 if (newStamp != timeStamp) {
7341 timeStamp = newStamp;
7342 timeStampString = Long.toString(newStamp);
7343 }
7344 }
7345
7346 public void setTimeStamp(long newStamp, String newStampStr) {
7347 timeStamp = newStamp;
7348 timeStampString = newStampStr;
7349 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007351 public long getTimeStamp() {
7352 return timeStamp;
7353 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007355 public String getTimeStampStr() {
7356 return timeStampString;
7357 }
7358
7359 public void copyFrom(PackageSettingBase base) {
7360 grantedPermissions = base.grantedPermissions;
7361 gids = base.gids;
7362 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007364 timeStamp = base.timeStamp;
7365 timeStampString = base.timeStampString;
7366 signatures = base.signatures;
7367 permissionsFixed = base.permissionsFixed;
7368 disabledComponents = base.disabledComponents;
7369 enabledComponents = base.enabledComponents;
7370 enabled = base.enabled;
7371 installStatus = base.installStatus;
7372 }
7373
7374 void enableComponentLP(String componentClassName) {
7375 disabledComponents.remove(componentClassName);
7376 enabledComponents.add(componentClassName);
7377 }
7378
7379 void disableComponentLP(String componentClassName) {
7380 enabledComponents.remove(componentClassName);
7381 disabledComponents.add(componentClassName);
7382 }
7383
7384 void restoreComponentLP(String componentClassName) {
7385 enabledComponents.remove(componentClassName);
7386 disabledComponents.remove(componentClassName);
7387 }
7388
7389 int currentEnabledStateLP(String componentName) {
7390 if (enabledComponents.contains(componentName)) {
7391 return COMPONENT_ENABLED_STATE_ENABLED;
7392 } else if (disabledComponents.contains(componentName)) {
7393 return COMPONENT_ENABLED_STATE_DISABLED;
7394 } else {
7395 return COMPONENT_ENABLED_STATE_DEFAULT;
7396 }
7397 }
7398 }
7399
7400 /**
7401 * Settings data for a particular package we know about.
7402 */
7403 static final class PackageSetting extends PackageSettingBase {
7404 int userId;
7405 PackageParser.Package pkg;
7406 SharedUserSetting sharedUser;
7407
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007408 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007409 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007410 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007411 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007413 @Override
7414 public String toString() {
7415 return "PackageSetting{"
7416 + Integer.toHexString(System.identityHashCode(this))
7417 + " " + name + "/" + userId + "}";
7418 }
7419 }
7420
7421 /**
7422 * Settings data for a particular shared user ID we know about.
7423 */
7424 static final class SharedUserSetting extends GrantedPermissions {
7425 final String name;
7426 int userId;
7427 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7428 final PackageSignatures signatures = new PackageSignatures();
7429
7430 SharedUserSetting(String _name, int _pkgFlags) {
7431 super(_pkgFlags);
7432 name = _name;
7433 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007435 @Override
7436 public String toString() {
7437 return "SharedUserSetting{"
7438 + Integer.toHexString(System.identityHashCode(this))
7439 + " " + name + "/" + userId + "}";
7440 }
7441 }
7442
7443 /**
7444 * Holds information about dynamic settings.
7445 */
7446 private static final class Settings {
7447 private final File mSettingsFilename;
7448 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007449 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007450 private final HashMap<String, PackageSetting> mPackages =
7451 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007452 // List of replaced system applications
7453 final HashMap<String, PackageSetting> mDisabledSysPackages =
7454 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007456 // The user's preferred activities associated with particular intent
7457 // filters.
7458 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7459 new IntentResolver<PreferredActivity, PreferredActivity>() {
7460 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007461 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007462 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007463 out.print(prefix); out.print(
7464 Integer.toHexString(System.identityHashCode(filter)));
7465 out.print(' ');
7466 out.print(filter.mActivity.flattenToShortString());
7467 out.print(" match=0x");
7468 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007469 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007470 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007471 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007472 out.print(prefix); out.print(" ");
7473 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007474 }
7475 }
7476 }
7477 };
7478 private final HashMap<String, SharedUserSetting> mSharedUsers =
7479 new HashMap<String, SharedUserSetting>();
7480 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7481 private final SparseArray<Object> mOtherUserIds =
7482 new SparseArray<Object>();
7483
7484 // For reading/writing settings file.
7485 private final ArrayList<Signature> mPastSignatures =
7486 new ArrayList<Signature>();
7487
7488 // Mapping from permission names to info about them.
7489 final HashMap<String, BasePermission> mPermissions =
7490 new HashMap<String, BasePermission>();
7491
7492 // Mapping from permission tree names to info about them.
7493 final HashMap<String, BasePermission> mPermissionTrees =
7494 new HashMap<String, BasePermission>();
7495
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007496 // Packages that have been uninstalled and still need their external
7497 // storage data deleted.
7498 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7499
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007500 // Packages that have been renamed since they were first installed.
7501 // Keys are the new names of the packages, values are the original
7502 // names. The packages appear everwhere else under their original
7503 // names.
7504 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007506 private final StringBuilder mReadMessages = new StringBuilder();
7507
7508 private static final class PendingPackage extends PackageSettingBase {
7509 final int sharedId;
7510
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007511 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007512 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007513 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007514 this.sharedId = sharedId;
7515 }
7516 }
7517 private final ArrayList<PendingPackage> mPendingPackages
7518 = new ArrayList<PendingPackage>();
7519
7520 Settings() {
7521 File dataDir = Environment.getDataDirectory();
7522 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007523 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7524 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007525 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007526 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007527 FileUtils.setPermissions(systemDir.toString(),
7528 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7529 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7530 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007531 FileUtils.setPermissions(systemSecureDir.toString(),
7532 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7533 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7534 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007535 mSettingsFilename = new File(systemDir, "packages.xml");
7536 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007537 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007538 }
7539
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007540 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007541 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007542 int pkgFlags, boolean create, boolean add) {
7543 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007544 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007545 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007546 return p;
7547 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007548
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007549 PackageSetting peekPackageLP(String name) {
7550 return mPackages.get(name);
7551 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007552 PackageSetting p = mPackages.get(name);
7553 if (p != null && p.codePath.getPath().equals(codePath)) {
7554 return p;
7555 }
7556 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007557 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007558 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007560 void setInstallStatus(String pkgName, int status) {
7561 PackageSetting p = mPackages.get(pkgName);
7562 if(p != null) {
7563 if(p.getInstallStatus() != status) {
7564 p.setInstallStatus(status);
7565 }
7566 }
7567 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007568
Jacek Surazski65e13172009-04-28 15:26:38 +02007569 void setInstallerPackageName(String pkgName,
7570 String installerPkgName) {
7571 PackageSetting p = mPackages.get(pkgName);
7572 if(p != null) {
7573 p.setInstallerPackageName(installerPkgName);
7574 }
7575 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007576
Jacek Surazski65e13172009-04-28 15:26:38 +02007577 String getInstallerPackageName(String pkgName) {
7578 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007579 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007580 }
7581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007582 int getInstallStatus(String pkgName) {
7583 PackageSetting p = mPackages.get(pkgName);
7584 if(p != null) {
7585 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007587 return -1;
7588 }
7589
7590 SharedUserSetting getSharedUserLP(String name,
7591 int pkgFlags, boolean create) {
7592 SharedUserSetting s = mSharedUsers.get(name);
7593 if (s == null) {
7594 if (!create) {
7595 return null;
7596 }
7597 s = new SharedUserSetting(name, pkgFlags);
7598 if (MULTIPLE_APPLICATION_UIDS) {
7599 s.userId = newUserIdLP(s);
7600 } else {
7601 s.userId = FIRST_APPLICATION_UID;
7602 }
7603 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7604 // < 0 means we couldn't assign a userid; fall out and return
7605 // s, which is currently null
7606 if (s.userId >= 0) {
7607 mSharedUsers.put(name, s);
7608 }
7609 }
7610
7611 return s;
7612 }
7613
7614 int disableSystemPackageLP(String name) {
7615 PackageSetting p = mPackages.get(name);
7616 if(p == null) {
7617 Log.w(TAG, "Package:"+name+" is not an installed package");
7618 return -1;
7619 }
7620 PackageSetting dp = mDisabledSysPackages.get(name);
7621 // always make sure the system package code and resource paths dont change
7622 if(dp == null) {
7623 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7624 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7625 }
7626 mDisabledSysPackages.put(name, p);
7627 }
7628 return removePackageLP(name);
7629 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007631 PackageSetting enableSystemPackageLP(String name) {
7632 PackageSetting p = mDisabledSysPackages.get(name);
7633 if(p == null) {
7634 Log.w(TAG, "Package:"+name+" is not disabled");
7635 return null;
7636 }
7637 // Reset flag in ApplicationInfo object
7638 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7639 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7640 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007641 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007642 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007643 mDisabledSysPackages.remove(name);
7644 return ret;
7645 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007646
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007647 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007648 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007649 PackageSetting p = mPackages.get(name);
7650 if (p != null) {
7651 if (p.userId == uid) {
7652 return p;
7653 }
7654 reportSettingsProblem(Log.ERROR,
7655 "Adding duplicate package, keeping first: " + name);
7656 return null;
7657 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007658 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007659 p.userId = uid;
7660 if (addUserIdLP(uid, p, name)) {
7661 mPackages.put(name, p);
7662 return p;
7663 }
7664 return null;
7665 }
7666
7667 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7668 SharedUserSetting s = mSharedUsers.get(name);
7669 if (s != null) {
7670 if (s.userId == uid) {
7671 return s;
7672 }
7673 reportSettingsProblem(Log.ERROR,
7674 "Adding duplicate shared user, keeping first: " + name);
7675 return null;
7676 }
7677 s = new SharedUserSetting(name, pkgFlags);
7678 s.userId = uid;
7679 if (addUserIdLP(uid, s, name)) {
7680 mSharedUsers.put(name, s);
7681 return s;
7682 }
7683 return null;
7684 }
7685
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007686 // Transfer ownership of permissions from one package to another.
7687 private void transferPermissions(String origPkg, String newPkg) {
7688 // Transfer ownership of permissions to the new package.
7689 for (int i=0; i<2; i++) {
7690 HashMap<String, BasePermission> permissions =
7691 i == 0 ? mPermissionTrees : mPermissions;
7692 for (BasePermission bp : permissions.values()) {
7693 if (origPkg.equals(bp.sourcePackage)) {
7694 if (DEBUG_UPGRADE) Log.v(TAG,
7695 "Moving permission " + bp.name
7696 + " from pkg " + bp.sourcePackage
7697 + " to " + newPkg);
7698 bp.sourcePackage = newPkg;
7699 bp.perm = null;
7700 if (bp.pendingInfo != null) {
7701 bp.sourcePackage = newPkg;
7702 }
7703 bp.uid = 0;
7704 bp.gids = null;
7705 }
7706 }
7707 }
7708 }
7709
7710 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007711 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007712 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007713 PackageSetting p = mPackages.get(name);
7714 if (p != null) {
7715 if (!p.codePath.equals(codePath)) {
7716 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007717 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007718 // This is an updated system app with versions in both system
7719 // and data partition. Just let the most recent version
7720 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007721 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007722 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007723 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007724 // Just a change in the code path is not an issue, but
7725 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007726 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007727 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007728 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007729 }
7730 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007731 reportSettingsProblem(Log.WARN,
7732 "Package " + name + " shared user changed from "
7733 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7734 + " to "
7735 + (sharedUser != null ? sharedUser.name : "<nothing>")
7736 + "; replacing with new");
7737 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007738 } else {
7739 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7740 // If what we are scanning is a system package, then
7741 // make it so, regardless of whether it was previously
7742 // installed only in the data partition.
7743 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007745 }
7746 }
7747 if (p == null) {
7748 // Create a new PackageSettings entry. this can end up here because
7749 // of code path mismatch or user id mismatch of an updated system partition
7750 if (!create) {
7751 return null;
7752 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007753 if (origPackage != null) {
7754 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007755 p = new PackageSetting(origPackage.name, name, codePath,
7756 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007757 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
7758 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08007759 // Note that we will retain the new package's signature so
7760 // that we can keep its data.
7761 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007762 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08007763 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007764 p.sharedUser = origPackage.sharedUser;
7765 p.userId = origPackage.userId;
7766 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007767 mRenamedPackages.put(name, origPackage.name);
7768 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007769 // Update new package state.
7770 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007771 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007772 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007773 p.setTimeStamp(codePath.lastModified());
7774 p.sharedUser = sharedUser;
7775 if (sharedUser != null) {
7776 p.userId = sharedUser.userId;
7777 } else if (MULTIPLE_APPLICATION_UIDS) {
7778 // Clone the setting here for disabled system packages
7779 PackageSetting dis = mDisabledSysPackages.get(name);
7780 if (dis != null) {
7781 // For disabled packages a new setting is created
7782 // from the existing user id. This still has to be
7783 // added to list of user id's
7784 // Copy signatures from previous setting
7785 if (dis.signatures.mSignatures != null) {
7786 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
7787 }
7788 p.userId = dis.userId;
7789 // Clone permissions
7790 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
7791 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
7792 // Clone component info
7793 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
7794 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
7795 // Add new setting to list of user ids
7796 addUserIdLP(p.userId, p, name);
7797 } else {
7798 // Assign new user id
7799 p.userId = newUserIdLP(p);
7800 }
7801 } else {
7802 p.userId = FIRST_APPLICATION_UID;
7803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007804 }
7805 if (p.userId < 0) {
7806 reportSettingsProblem(Log.WARN,
7807 "Package " + name + " could not be assigned a valid uid");
7808 return null;
7809 }
7810 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007811 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007812 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007813 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007814 }
7815 }
7816 return p;
7817 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007818
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007819 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007820 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007821 String codePath = pkg.applicationInfo.sourceDir;
7822 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007823 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007824 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007825 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007826 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007827 p.codePath = new File(codePath);
7828 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007829 }
7830 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007831 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007832 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007833 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007834 p.resourcePath = new File(resourcePath);
7835 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007836 }
7837 // Update version code if needed
7838 if (pkg.mVersionCode != p.versionCode) {
7839 p.versionCode = pkg.mVersionCode;
7840 }
7841 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
7842 }
7843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007844 // Utility method that adds a PackageSetting to mPackages and
7845 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007846 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007847 SharedUserSetting sharedUser) {
7848 mPackages.put(name, p);
7849 if (sharedUser != null) {
7850 if (p.sharedUser != null && p.sharedUser != sharedUser) {
7851 reportSettingsProblem(Log.ERROR,
7852 "Package " + p.name + " was user "
7853 + p.sharedUser + " but is now " + sharedUser
7854 + "; I am not changing its files so it will probably fail!");
7855 p.sharedUser.packages.remove(p);
7856 } else if (p.userId != sharedUser.userId) {
7857 reportSettingsProblem(Log.ERROR,
7858 "Package " + p.name + " was user id " + p.userId
7859 + " but is now user " + sharedUser
7860 + " with id " + sharedUser.userId
7861 + "; I am not changing its files so it will probably fail!");
7862 }
7863
7864 sharedUser.packages.add(p);
7865 p.sharedUser = sharedUser;
7866 p.userId = sharedUser.userId;
7867 }
7868 }
7869
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007870 /*
7871 * Update the shared user setting when a package using
7872 * specifying the shared user id is removed. The gids
7873 * associated with each permission of the deleted package
7874 * are removed from the shared user's gid list only if its
7875 * not in use by other permissions of packages in the
7876 * shared user setting.
7877 */
7878 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007879 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007880 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007881 return;
7882 }
7883 // No sharedUserId
7884 if (deletedPs.sharedUser == null) {
7885 return;
7886 }
7887 SharedUserSetting sus = deletedPs.sharedUser;
7888 // Update permissions
7889 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
7890 boolean used = false;
7891 if (!sus.grantedPermissions.contains (eachPerm)) {
7892 continue;
7893 }
7894 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007895 if (pkg.pkg != null &&
7896 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
7897 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007898 used = true;
7899 break;
7900 }
7901 }
7902 if (!used) {
7903 // can safely delete this permission from list
7904 sus.grantedPermissions.remove(eachPerm);
7905 sus.loadedPermissions.remove(eachPerm);
7906 }
7907 }
7908 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007909 int newGids[] = globalGids;
7910 for (String eachPerm : sus.grantedPermissions) {
7911 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007912 if (bp != null) {
7913 newGids = appendInts(newGids, bp.gids);
7914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007915 }
7916 sus.gids = newGids;
7917 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007919 private int removePackageLP(String name) {
7920 PackageSetting p = mPackages.get(name);
7921 if (p != null) {
7922 mPackages.remove(name);
7923 if (p.sharedUser != null) {
7924 p.sharedUser.packages.remove(p);
7925 if (p.sharedUser.packages.size() == 0) {
7926 mSharedUsers.remove(p.sharedUser.name);
7927 removeUserIdLP(p.sharedUser.userId);
7928 return p.sharedUser.userId;
7929 }
7930 } else {
7931 removeUserIdLP(p.userId);
7932 return p.userId;
7933 }
7934 }
7935 return -1;
7936 }
7937
7938 private boolean addUserIdLP(int uid, Object obj, Object name) {
7939 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
7940 return false;
7941 }
7942
7943 if (uid >= FIRST_APPLICATION_UID) {
7944 int N = mUserIds.size();
7945 final int index = uid - FIRST_APPLICATION_UID;
7946 while (index >= N) {
7947 mUserIds.add(null);
7948 N++;
7949 }
7950 if (mUserIds.get(index) != null) {
7951 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007952 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007953 + " name=" + name);
7954 return false;
7955 }
7956 mUserIds.set(index, obj);
7957 } else {
7958 if (mOtherUserIds.get(uid) != null) {
7959 reportSettingsProblem(Log.ERROR,
7960 "Adding duplicate shared id: " + uid
7961 + " name=" + name);
7962 return false;
7963 }
7964 mOtherUserIds.put(uid, obj);
7965 }
7966 return true;
7967 }
7968
7969 public Object getUserIdLP(int uid) {
7970 if (uid >= FIRST_APPLICATION_UID) {
7971 int N = mUserIds.size();
7972 final int index = uid - FIRST_APPLICATION_UID;
7973 return index < N ? mUserIds.get(index) : null;
7974 } else {
7975 return mOtherUserIds.get(uid);
7976 }
7977 }
7978
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007979 private Set<String> findPackagesWithFlag(int flag) {
7980 Set<String> ret = new HashSet<String>();
7981 for (PackageSetting ps : mPackages.values()) {
7982 // Has to match atleast all the flag bits set on flag
7983 if ((ps.pkgFlags & flag) == flag) {
7984 ret.add(ps.name);
7985 }
7986 }
7987 return ret;
7988 }
7989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007990 private void removeUserIdLP(int uid) {
7991 if (uid >= FIRST_APPLICATION_UID) {
7992 int N = mUserIds.size();
7993 final int index = uid - FIRST_APPLICATION_UID;
7994 if (index < N) mUserIds.set(index, null);
7995 } else {
7996 mOtherUserIds.remove(uid);
7997 }
7998 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008000 void writeLP() {
8001 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8002
8003 // Keep the old settings around until we know the new ones have
8004 // been successfully written.
8005 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008006 // Presence of backup settings file indicates that we failed
8007 // to persist settings earlier. So preserve the older
8008 // backup for future reference since the current settings
8009 // might have been corrupted.
8010 if (!mBackupSettingsFilename.exists()) {
8011 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008012 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008013 return;
8014 }
8015 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008016 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008018 }
8019
8020 mPastSignatures.clear();
8021
8022 try {
8023 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8024
8025 //XmlSerializer serializer = XmlUtils.serializerInstance();
8026 XmlSerializer serializer = new FastXmlSerializer();
8027 serializer.setOutput(str, "utf-8");
8028 serializer.startDocument(null, true);
8029 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8030
8031 serializer.startTag(null, "packages");
8032
8033 serializer.startTag(null, "permission-trees");
8034 for (BasePermission bp : mPermissionTrees.values()) {
8035 writePermission(serializer, bp);
8036 }
8037 serializer.endTag(null, "permission-trees");
8038
8039 serializer.startTag(null, "permissions");
8040 for (BasePermission bp : mPermissions.values()) {
8041 writePermission(serializer, bp);
8042 }
8043 serializer.endTag(null, "permissions");
8044
8045 for (PackageSetting pkg : mPackages.values()) {
8046 writePackage(serializer, pkg);
8047 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008049 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8050 writeDisabledSysPackage(serializer, pkg);
8051 }
8052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008053 serializer.startTag(null, "preferred-activities");
8054 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8055 serializer.startTag(null, "item");
8056 pa.writeToXml(serializer);
8057 serializer.endTag(null, "item");
8058 }
8059 serializer.endTag(null, "preferred-activities");
8060
8061 for (SharedUserSetting usr : mSharedUsers.values()) {
8062 serializer.startTag(null, "shared-user");
8063 serializer.attribute(null, "name", usr.name);
8064 serializer.attribute(null, "userId",
8065 Integer.toString(usr.userId));
8066 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8067 serializer.startTag(null, "perms");
8068 for (String name : usr.grantedPermissions) {
8069 serializer.startTag(null, "item");
8070 serializer.attribute(null, "name", name);
8071 serializer.endTag(null, "item");
8072 }
8073 serializer.endTag(null, "perms");
8074 serializer.endTag(null, "shared-user");
8075 }
8076
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008077 if (mPackagesToBeCleaned.size() > 0) {
8078 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8079 serializer.startTag(null, "cleaning-package");
8080 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8081 serializer.endTag(null, "cleaning-package");
8082 }
8083 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008084
8085 if (mRenamedPackages.size() > 0) {
8086 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8087 serializer.startTag(null, "renamed-package");
8088 serializer.attribute(null, "new", e.getKey());
8089 serializer.attribute(null, "old", e.getValue());
8090 serializer.endTag(null, "renamed-package");
8091 }
8092 }
8093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008094 serializer.endTag(null, "packages");
8095
8096 serializer.endDocument();
8097
8098 str.flush();
8099 str.close();
8100
8101 // New settings successfully written, old ones are no longer
8102 // needed.
8103 mBackupSettingsFilename.delete();
8104 FileUtils.setPermissions(mSettingsFilename.toString(),
8105 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8106 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8107 |FileUtils.S_IROTH,
8108 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008109
8110 // Write package list file now, use a JournaledFile.
8111 //
8112 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8113 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8114
8115 str = new FileOutputStream(journal.chooseForWrite());
8116 try {
8117 StringBuilder sb = new StringBuilder();
8118 for (PackageSetting pkg : mPackages.values()) {
8119 ApplicationInfo ai = pkg.pkg.applicationInfo;
8120 String dataPath = ai.dataDir;
8121 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8122
8123 // Avoid any application that has a space in its path
8124 // or that is handled by the system.
8125 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8126 continue;
8127
8128 // we store on each line the following information for now:
8129 //
8130 // pkgName - package name
8131 // userId - application-specific user id
8132 // debugFlag - 0 or 1 if the package is debuggable.
8133 // dataPath - path to package's data path
8134 //
8135 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8136 //
8137 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8138 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8139 // system/core/run-as/run-as.c
8140 //
8141 sb.setLength(0);
8142 sb.append(ai.packageName);
8143 sb.append(" ");
8144 sb.append((int)ai.uid);
8145 sb.append(isDebug ? " 1 " : " 0 ");
8146 sb.append(dataPath);
8147 sb.append("\n");
8148 str.write(sb.toString().getBytes());
8149 }
8150 str.flush();
8151 str.close();
8152 journal.commit();
8153 }
8154 catch (Exception e) {
8155 journal.rollback();
8156 }
8157
8158 FileUtils.setPermissions(mPackageListFilename.toString(),
8159 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8160 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8161 |FileUtils.S_IROTH,
8162 -1, -1);
8163
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008164 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008165
8166 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008167 Slog.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008168 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008169 Slog.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008170 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008171 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008172 if (mSettingsFilename.exists()) {
8173 if (!mSettingsFilename.delete()) {
8174 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8175 }
8176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008177 //Debug.stopMethodTracing();
8178 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008179
8180 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008181 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008182 serializer.startTag(null, "updated-package");
8183 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008184 if (pkg.realName != null) {
8185 serializer.attribute(null, "realName", pkg.realName);
8186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008187 serializer.attribute(null, "codePath", pkg.codePathString);
8188 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008189 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008190 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8191 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8192 }
8193 if (pkg.sharedUser == null) {
8194 serializer.attribute(null, "userId",
8195 Integer.toString(pkg.userId));
8196 } else {
8197 serializer.attribute(null, "sharedUserId",
8198 Integer.toString(pkg.userId));
8199 }
8200 serializer.startTag(null, "perms");
8201 if (pkg.sharedUser == null) {
8202 // If this is a shared user, the permissions will
8203 // be written there. We still need to write an
8204 // empty permissions list so permissionsFixed will
8205 // be set.
8206 for (final String name : pkg.grantedPermissions) {
8207 BasePermission bp = mPermissions.get(name);
8208 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
8209 // We only need to write signature or system permissions but this wont
8210 // match the semantics of grantedPermissions. So write all permissions.
8211 serializer.startTag(null, "item");
8212 serializer.attribute(null, "name", name);
8213 serializer.endTag(null, "item");
8214 }
8215 }
8216 }
8217 serializer.endTag(null, "perms");
8218 serializer.endTag(null, "updated-package");
8219 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008220
8221 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008222 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008223 serializer.startTag(null, "package");
8224 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008225 if (pkg.realName != null) {
8226 serializer.attribute(null, "realName", pkg.realName);
8227 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008228 serializer.attribute(null, "codePath", pkg.codePathString);
8229 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8230 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8231 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008232 serializer.attribute(null, "flags",
8233 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008234 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008235 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008236 if (pkg.sharedUser == null) {
8237 serializer.attribute(null, "userId",
8238 Integer.toString(pkg.userId));
8239 } else {
8240 serializer.attribute(null, "sharedUserId",
8241 Integer.toString(pkg.userId));
8242 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008243 if (pkg.uidError) {
8244 serializer.attribute(null, "uidError", "true");
8245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008246 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8247 serializer.attribute(null, "enabled",
8248 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8249 ? "true" : "false");
8250 }
8251 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8252 serializer.attribute(null, "installStatus", "false");
8253 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008254 if (pkg.installerPackageName != null) {
8255 serializer.attribute(null, "installer", pkg.installerPackageName);
8256 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008257 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8258 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8259 serializer.startTag(null, "perms");
8260 if (pkg.sharedUser == null) {
8261 // If this is a shared user, the permissions will
8262 // be written there. We still need to write an
8263 // empty permissions list so permissionsFixed will
8264 // be set.
8265 for (final String name : pkg.grantedPermissions) {
8266 serializer.startTag(null, "item");
8267 serializer.attribute(null, "name", name);
8268 serializer.endTag(null, "item");
8269 }
8270 }
8271 serializer.endTag(null, "perms");
8272 }
8273 if (pkg.disabledComponents.size() > 0) {
8274 serializer.startTag(null, "disabled-components");
8275 for (final String name : pkg.disabledComponents) {
8276 serializer.startTag(null, "item");
8277 serializer.attribute(null, "name", name);
8278 serializer.endTag(null, "item");
8279 }
8280 serializer.endTag(null, "disabled-components");
8281 }
8282 if (pkg.enabledComponents.size() > 0) {
8283 serializer.startTag(null, "enabled-components");
8284 for (final String name : pkg.enabledComponents) {
8285 serializer.startTag(null, "item");
8286 serializer.attribute(null, "name", name);
8287 serializer.endTag(null, "item");
8288 }
8289 serializer.endTag(null, "enabled-components");
8290 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008292 serializer.endTag(null, "package");
8293 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008295 void writePermission(XmlSerializer serializer, BasePermission bp)
8296 throws XmlPullParserException, java.io.IOException {
8297 if (bp.type != BasePermission.TYPE_BUILTIN
8298 && bp.sourcePackage != null) {
8299 serializer.startTag(null, "item");
8300 serializer.attribute(null, "name", bp.name);
8301 serializer.attribute(null, "package", bp.sourcePackage);
8302 if (DEBUG_SETTINGS) Log.v(TAG,
8303 "Writing perm: name=" + bp.name + " type=" + bp.type);
8304 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8305 PermissionInfo pi = bp.perm != null ? bp.perm.info
8306 : bp.pendingInfo;
8307 if (pi != null) {
8308 serializer.attribute(null, "type", "dynamic");
8309 if (pi.icon != 0) {
8310 serializer.attribute(null, "icon",
8311 Integer.toString(pi.icon));
8312 }
8313 if (pi.nonLocalizedLabel != null) {
8314 serializer.attribute(null, "label",
8315 pi.nonLocalizedLabel.toString());
8316 }
8317 if (pi.protectionLevel !=
8318 PermissionInfo.PROTECTION_NORMAL) {
8319 serializer.attribute(null, "protection",
8320 Integer.toString(pi.protectionLevel));
8321 }
8322 }
8323 }
8324 serializer.endTag(null, "item");
8325 }
8326 }
8327
8328 String getReadMessagesLP() {
8329 return mReadMessages.toString();
8330 }
8331
Oscar Montemayora8529f62009-11-18 10:14:20 -08008332 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008333 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8334 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008335 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008336 while(its.hasNext()) {
8337 String key = its.next();
8338 PackageSetting ps = mPackages.get(key);
8339 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008340 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008341 }
8342 }
8343 return ret;
8344 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008346 boolean readLP() {
8347 FileInputStream str = null;
8348 if (mBackupSettingsFilename.exists()) {
8349 try {
8350 str = new FileInputStream(mBackupSettingsFilename);
8351 mReadMessages.append("Reading from backup settings file\n");
8352 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008353 if (mSettingsFilename.exists()) {
8354 // If both the backup and settings file exist, we
8355 // ignore the settings since it might have been
8356 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008357 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008358 mSettingsFilename.delete();
8359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008360 } catch (java.io.IOException e) {
8361 // We'll try for the normal settings file.
8362 }
8363 }
8364
8365 mPastSignatures.clear();
8366
8367 try {
8368 if (str == null) {
8369 if (!mSettingsFilename.exists()) {
8370 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008371 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008372 return false;
8373 }
8374 str = new FileInputStream(mSettingsFilename);
8375 }
8376 XmlPullParser parser = Xml.newPullParser();
8377 parser.setInput(str, null);
8378
8379 int type;
8380 while ((type=parser.next()) != XmlPullParser.START_TAG
8381 && type != XmlPullParser.END_DOCUMENT) {
8382 ;
8383 }
8384
8385 if (type != XmlPullParser.START_TAG) {
8386 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008387 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008388 return false;
8389 }
8390
8391 int outerDepth = parser.getDepth();
8392 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8393 && (type != XmlPullParser.END_TAG
8394 || parser.getDepth() > outerDepth)) {
8395 if (type == XmlPullParser.END_TAG
8396 || type == XmlPullParser.TEXT) {
8397 continue;
8398 }
8399
8400 String tagName = parser.getName();
8401 if (tagName.equals("package")) {
8402 readPackageLP(parser);
8403 } else if (tagName.equals("permissions")) {
8404 readPermissionsLP(mPermissions, parser);
8405 } else if (tagName.equals("permission-trees")) {
8406 readPermissionsLP(mPermissionTrees, parser);
8407 } else if (tagName.equals("shared-user")) {
8408 readSharedUserLP(parser);
8409 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008410 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008411 } else if (tagName.equals("preferred-activities")) {
8412 readPreferredActivitiesLP(parser);
8413 } else if(tagName.equals("updated-package")) {
8414 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008415 } else if (tagName.equals("cleaning-package")) {
8416 String name = parser.getAttributeValue(null, "name");
8417 if (name != null) {
8418 mPackagesToBeCleaned.add(name);
8419 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008420 } else if (tagName.equals("renamed-package")) {
8421 String nname = parser.getAttributeValue(null, "new");
8422 String oname = parser.getAttributeValue(null, "old");
8423 if (nname != null && oname != null) {
8424 mRenamedPackages.put(nname, oname);
8425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008426 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008427 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008428 + parser.getName());
8429 XmlUtils.skipCurrentTag(parser);
8430 }
8431 }
8432
8433 str.close();
8434
8435 } catch(XmlPullParserException e) {
8436 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008437 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008438
8439 } catch(java.io.IOException e) {
8440 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008441 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008442
8443 }
8444
8445 int N = mPendingPackages.size();
8446 for (int i=0; i<N; i++) {
8447 final PendingPackage pp = mPendingPackages.get(i);
8448 Object idObj = getUserIdLP(pp.sharedId);
8449 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008450 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008451 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008452 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008453 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008454 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008455 + pp.name);
8456 continue;
8457 }
8458 p.copyFrom(pp);
8459 } else if (idObj != null) {
8460 String msg = "Bad package setting: package " + pp.name
8461 + " has shared uid " + pp.sharedId
8462 + " that is not a shared uid\n";
8463 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008464 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008465 } else {
8466 String msg = "Bad package setting: package " + pp.name
8467 + " has shared uid " + pp.sharedId
8468 + " that is not defined\n";
8469 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008470 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008471 }
8472 }
8473 mPendingPackages.clear();
8474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008475 mReadMessages.append("Read completed successfully: "
8476 + mPackages.size() + " packages, "
8477 + mSharedUsers.size() + " shared uids\n");
8478
8479 return true;
8480 }
8481
8482 private int readInt(XmlPullParser parser, String ns, String name,
8483 int defValue) {
8484 String v = parser.getAttributeValue(ns, name);
8485 try {
8486 if (v == null) {
8487 return defValue;
8488 }
8489 return Integer.parseInt(v);
8490 } catch (NumberFormatException e) {
8491 reportSettingsProblem(Log.WARN,
8492 "Error in package manager settings: attribute " +
8493 name + " has bad integer value " + v + " at "
8494 + parser.getPositionDescription());
8495 }
8496 return defValue;
8497 }
8498
8499 private void readPermissionsLP(HashMap<String, BasePermission> out,
8500 XmlPullParser parser)
8501 throws IOException, XmlPullParserException {
8502 int outerDepth = parser.getDepth();
8503 int type;
8504 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8505 && (type != XmlPullParser.END_TAG
8506 || parser.getDepth() > outerDepth)) {
8507 if (type == XmlPullParser.END_TAG
8508 || type == XmlPullParser.TEXT) {
8509 continue;
8510 }
8511
8512 String tagName = parser.getName();
8513 if (tagName.equals("item")) {
8514 String name = parser.getAttributeValue(null, "name");
8515 String sourcePackage = parser.getAttributeValue(null, "package");
8516 String ptype = parser.getAttributeValue(null, "type");
8517 if (name != null && sourcePackage != null) {
8518 boolean dynamic = "dynamic".equals(ptype);
8519 BasePermission bp = new BasePermission(name, sourcePackage,
8520 dynamic
8521 ? BasePermission.TYPE_DYNAMIC
8522 : BasePermission.TYPE_NORMAL);
8523 if (dynamic) {
8524 PermissionInfo pi = new PermissionInfo();
8525 pi.packageName = sourcePackage.intern();
8526 pi.name = name.intern();
8527 pi.icon = readInt(parser, null, "icon", 0);
8528 pi.nonLocalizedLabel = parser.getAttributeValue(
8529 null, "label");
8530 pi.protectionLevel = readInt(parser, null, "protection",
8531 PermissionInfo.PROTECTION_NORMAL);
8532 bp.pendingInfo = pi;
8533 }
8534 out.put(bp.name, bp);
8535 } else {
8536 reportSettingsProblem(Log.WARN,
8537 "Error in package manager settings: permissions has"
8538 + " no name at " + parser.getPositionDescription());
8539 }
8540 } else {
8541 reportSettingsProblem(Log.WARN,
8542 "Unknown element reading permissions: "
8543 + parser.getName() + " at "
8544 + parser.getPositionDescription());
8545 }
8546 XmlUtils.skipCurrentTag(parser);
8547 }
8548 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008550 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008551 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008552 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008553 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008554 String codePathStr = parser.getAttributeValue(null, "codePath");
8555 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008556 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008557 resourcePathStr = codePathStr;
8558 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008559 String version = parser.getAttributeValue(null, "version");
8560 int versionCode = 0;
8561 if (version != null) {
8562 try {
8563 versionCode = Integer.parseInt(version);
8564 } catch (NumberFormatException e) {
8565 }
8566 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008568 int pkgFlags = 0;
8569 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008570 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008571 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008572 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008573 String timeStampStr = parser.getAttributeValue(null, "ts");
8574 if (timeStampStr != null) {
8575 try {
8576 long timeStamp = Long.parseLong(timeStampStr);
8577 ps.setTimeStamp(timeStamp, timeStampStr);
8578 } catch (NumberFormatException e) {
8579 }
8580 }
8581 String idStr = parser.getAttributeValue(null, "userId");
8582 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8583 if(ps.userId <= 0) {
8584 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8585 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8586 }
8587 int outerDepth = parser.getDepth();
8588 int type;
8589 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8590 && (type != XmlPullParser.END_TAG
8591 || parser.getDepth() > outerDepth)) {
8592 if (type == XmlPullParser.END_TAG
8593 || type == XmlPullParser.TEXT) {
8594 continue;
8595 }
8596
8597 String tagName = parser.getName();
8598 if (tagName.equals("perms")) {
8599 readGrantedPermissionsLP(parser,
8600 ps.grantedPermissions);
8601 } else {
8602 reportSettingsProblem(Log.WARN,
8603 "Unknown element under <updated-package>: "
8604 + parser.getName());
8605 XmlUtils.skipCurrentTag(parser);
8606 }
8607 }
8608 mDisabledSysPackages.put(name, ps);
8609 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008611 private void readPackageLP(XmlPullParser parser)
8612 throws XmlPullParserException, IOException {
8613 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008614 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008615 String idStr = null;
8616 String sharedIdStr = null;
8617 String codePathStr = null;
8618 String resourcePathStr = null;
8619 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008620 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008621 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008622 int pkgFlags = 0;
8623 String timeStampStr;
8624 long timeStamp = 0;
8625 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008626 String version = null;
8627 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008628 try {
8629 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008630 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008631 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008632 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008633 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8634 codePathStr = parser.getAttributeValue(null, "codePath");
8635 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008636 version = parser.getAttributeValue(null, "version");
8637 if (version != null) {
8638 try {
8639 versionCode = Integer.parseInt(version);
8640 } catch (NumberFormatException e) {
8641 }
8642 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008643 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008644
8645 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008646 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008647 try {
8648 pkgFlags = Integer.parseInt(systemStr);
8649 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008650 }
8651 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008652 // For backward compatibility
8653 systemStr = parser.getAttributeValue(null, "system");
8654 if (systemStr != null) {
8655 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8656 } else {
8657 // Old settings that don't specify system... just treat
8658 // them as system, good enough.
8659 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008661 }
8662 timeStampStr = parser.getAttributeValue(null, "ts");
8663 if (timeStampStr != null) {
8664 try {
8665 timeStamp = Long.parseLong(timeStampStr);
8666 } catch (NumberFormatException e) {
8667 }
8668 }
8669 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8670 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8671 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8672 if (resourcePathStr == null) {
8673 resourcePathStr = codePathStr;
8674 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008675 if (realName != null) {
8676 realName = realName.intern();
8677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008678 if (name == null) {
8679 reportSettingsProblem(Log.WARN,
8680 "Error in package manager settings: <package> has no name at "
8681 + parser.getPositionDescription());
8682 } else if (codePathStr == null) {
8683 reportSettingsProblem(Log.WARN,
8684 "Error in package manager settings: <package> has no codePath at "
8685 + parser.getPositionDescription());
8686 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008687 packageSetting = addPackageLP(name.intern(), realName,
8688 new File(codePathStr), new File(resourcePathStr),
8689 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008690 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8691 + ": userId=" + userId + " pkg=" + packageSetting);
8692 if (packageSetting == null) {
8693 reportSettingsProblem(Log.ERROR,
8694 "Failure adding uid " + userId
8695 + " while parsing settings at "
8696 + parser.getPositionDescription());
8697 } else {
8698 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8699 }
8700 } else if (sharedIdStr != null) {
8701 userId = sharedIdStr != null
8702 ? Integer.parseInt(sharedIdStr) : 0;
8703 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008704 packageSetting = new PendingPackage(name.intern(), realName,
8705 new File(codePathStr), new File(resourcePathStr),
8706 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008707 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8708 mPendingPackages.add((PendingPackage) packageSetting);
8709 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8710 + ": sharedUserId=" + userId + " pkg="
8711 + packageSetting);
8712 } else {
8713 reportSettingsProblem(Log.WARN,
8714 "Error in package manager settings: package "
8715 + name + " has bad sharedId " + sharedIdStr
8716 + " at " + parser.getPositionDescription());
8717 }
8718 } else {
8719 reportSettingsProblem(Log.WARN,
8720 "Error in package manager settings: package "
8721 + name + " has bad userId " + idStr + " at "
8722 + parser.getPositionDescription());
8723 }
8724 } catch (NumberFormatException e) {
8725 reportSettingsProblem(Log.WARN,
8726 "Error in package manager settings: package "
8727 + name + " has bad userId " + idStr + " at "
8728 + parser.getPositionDescription());
8729 }
8730 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008731 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008732 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008733 final String enabledStr = parser.getAttributeValue(null, "enabled");
8734 if (enabledStr != null) {
8735 if (enabledStr.equalsIgnoreCase("true")) {
8736 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8737 } else if (enabledStr.equalsIgnoreCase("false")) {
8738 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
8739 } else if (enabledStr.equalsIgnoreCase("default")) {
8740 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8741 } else {
8742 reportSettingsProblem(Log.WARN,
8743 "Error in package manager settings: package "
8744 + name + " has bad enabled value: " + idStr
8745 + " at " + parser.getPositionDescription());
8746 }
8747 } else {
8748 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8749 }
8750 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
8751 if (installStatusStr != null) {
8752 if (installStatusStr.equalsIgnoreCase("false")) {
8753 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
8754 } else {
8755 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
8756 }
8757 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008759 int outerDepth = parser.getDepth();
8760 int type;
8761 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8762 && (type != XmlPullParser.END_TAG
8763 || parser.getDepth() > outerDepth)) {
8764 if (type == XmlPullParser.END_TAG
8765 || type == XmlPullParser.TEXT) {
8766 continue;
8767 }
8768
8769 String tagName = parser.getName();
8770 if (tagName.equals("disabled-components")) {
8771 readDisabledComponentsLP(packageSetting, parser);
8772 } else if (tagName.equals("enabled-components")) {
8773 readEnabledComponentsLP(packageSetting, parser);
8774 } else if (tagName.equals("sigs")) {
8775 packageSetting.signatures.readXml(parser, mPastSignatures);
8776 } else if (tagName.equals("perms")) {
8777 readGrantedPermissionsLP(parser,
8778 packageSetting.loadedPermissions);
8779 packageSetting.permissionsFixed = true;
8780 } else {
8781 reportSettingsProblem(Log.WARN,
8782 "Unknown element under <package>: "
8783 + parser.getName());
8784 XmlUtils.skipCurrentTag(parser);
8785 }
8786 }
8787 } else {
8788 XmlUtils.skipCurrentTag(parser);
8789 }
8790 }
8791
8792 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
8793 XmlPullParser parser)
8794 throws IOException, XmlPullParserException {
8795 int outerDepth = parser.getDepth();
8796 int type;
8797 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8798 && (type != XmlPullParser.END_TAG
8799 || parser.getDepth() > outerDepth)) {
8800 if (type == XmlPullParser.END_TAG
8801 || type == XmlPullParser.TEXT) {
8802 continue;
8803 }
8804
8805 String tagName = parser.getName();
8806 if (tagName.equals("item")) {
8807 String name = parser.getAttributeValue(null, "name");
8808 if (name != null) {
8809 packageSetting.disabledComponents.add(name.intern());
8810 } else {
8811 reportSettingsProblem(Log.WARN,
8812 "Error in package manager settings: <disabled-components> has"
8813 + " no name at " + parser.getPositionDescription());
8814 }
8815 } else {
8816 reportSettingsProblem(Log.WARN,
8817 "Unknown element under <disabled-components>: "
8818 + parser.getName());
8819 }
8820 XmlUtils.skipCurrentTag(parser);
8821 }
8822 }
8823
8824 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
8825 XmlPullParser parser)
8826 throws IOException, XmlPullParserException {
8827 int outerDepth = parser.getDepth();
8828 int type;
8829 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8830 && (type != XmlPullParser.END_TAG
8831 || parser.getDepth() > outerDepth)) {
8832 if (type == XmlPullParser.END_TAG
8833 || type == XmlPullParser.TEXT) {
8834 continue;
8835 }
8836
8837 String tagName = parser.getName();
8838 if (tagName.equals("item")) {
8839 String name = parser.getAttributeValue(null, "name");
8840 if (name != null) {
8841 packageSetting.enabledComponents.add(name.intern());
8842 } else {
8843 reportSettingsProblem(Log.WARN,
8844 "Error in package manager settings: <enabled-components> has"
8845 + " no name at " + parser.getPositionDescription());
8846 }
8847 } else {
8848 reportSettingsProblem(Log.WARN,
8849 "Unknown element under <enabled-components>: "
8850 + parser.getName());
8851 }
8852 XmlUtils.skipCurrentTag(parser);
8853 }
8854 }
8855
8856 private void readSharedUserLP(XmlPullParser parser)
8857 throws XmlPullParserException, IOException {
8858 String name = null;
8859 String idStr = null;
8860 int pkgFlags = 0;
8861 SharedUserSetting su = null;
8862 try {
8863 name = parser.getAttributeValue(null, "name");
8864 idStr = parser.getAttributeValue(null, "userId");
8865 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8866 if ("true".equals(parser.getAttributeValue(null, "system"))) {
8867 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8868 }
8869 if (name == null) {
8870 reportSettingsProblem(Log.WARN,
8871 "Error in package manager settings: <shared-user> has no name at "
8872 + parser.getPositionDescription());
8873 } else if (userId == 0) {
8874 reportSettingsProblem(Log.WARN,
8875 "Error in package manager settings: shared-user "
8876 + name + " has bad userId " + idStr + " at "
8877 + parser.getPositionDescription());
8878 } else {
8879 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
8880 reportSettingsProblem(Log.ERROR,
8881 "Occurred while parsing settings at "
8882 + parser.getPositionDescription());
8883 }
8884 }
8885 } catch (NumberFormatException e) {
8886 reportSettingsProblem(Log.WARN,
8887 "Error in package manager settings: package "
8888 + name + " has bad userId " + idStr + " at "
8889 + parser.getPositionDescription());
8890 };
8891
8892 if (su != null) {
8893 int outerDepth = parser.getDepth();
8894 int type;
8895 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8896 && (type != XmlPullParser.END_TAG
8897 || parser.getDepth() > outerDepth)) {
8898 if (type == XmlPullParser.END_TAG
8899 || type == XmlPullParser.TEXT) {
8900 continue;
8901 }
8902
8903 String tagName = parser.getName();
8904 if (tagName.equals("sigs")) {
8905 su.signatures.readXml(parser, mPastSignatures);
8906 } else if (tagName.equals("perms")) {
8907 readGrantedPermissionsLP(parser, su.loadedPermissions);
8908 } else {
8909 reportSettingsProblem(Log.WARN,
8910 "Unknown element under <shared-user>: "
8911 + parser.getName());
8912 XmlUtils.skipCurrentTag(parser);
8913 }
8914 }
8915
8916 } else {
8917 XmlUtils.skipCurrentTag(parser);
8918 }
8919 }
8920
8921 private void readGrantedPermissionsLP(XmlPullParser parser,
8922 HashSet<String> outPerms) throws IOException, XmlPullParserException {
8923 int outerDepth = parser.getDepth();
8924 int type;
8925 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8926 && (type != XmlPullParser.END_TAG
8927 || parser.getDepth() > outerDepth)) {
8928 if (type == XmlPullParser.END_TAG
8929 || type == XmlPullParser.TEXT) {
8930 continue;
8931 }
8932
8933 String tagName = parser.getName();
8934 if (tagName.equals("item")) {
8935 String name = parser.getAttributeValue(null, "name");
8936 if (name != null) {
8937 outPerms.add(name.intern());
8938 } else {
8939 reportSettingsProblem(Log.WARN,
8940 "Error in package manager settings: <perms> has"
8941 + " no name at " + parser.getPositionDescription());
8942 }
8943 } else {
8944 reportSettingsProblem(Log.WARN,
8945 "Unknown element under <perms>: "
8946 + parser.getName());
8947 }
8948 XmlUtils.skipCurrentTag(parser);
8949 }
8950 }
8951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008952 private void readPreferredActivitiesLP(XmlPullParser parser)
8953 throws XmlPullParserException, IOException {
8954 int outerDepth = parser.getDepth();
8955 int type;
8956 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8957 && (type != XmlPullParser.END_TAG
8958 || parser.getDepth() > outerDepth)) {
8959 if (type == XmlPullParser.END_TAG
8960 || type == XmlPullParser.TEXT) {
8961 continue;
8962 }
8963
8964 String tagName = parser.getName();
8965 if (tagName.equals("item")) {
8966 PreferredActivity pa = new PreferredActivity(parser);
8967 if (pa.mParseError == null) {
8968 mPreferredActivities.addFilter(pa);
8969 } else {
8970 reportSettingsProblem(Log.WARN,
8971 "Error in package manager settings: <preferred-activity> "
8972 + pa.mParseError + " at "
8973 + parser.getPositionDescription());
8974 }
8975 } else {
8976 reportSettingsProblem(Log.WARN,
8977 "Unknown element under <preferred-activities>: "
8978 + parser.getName());
8979 XmlUtils.skipCurrentTag(parser);
8980 }
8981 }
8982 }
8983
8984 // Returns -1 if we could not find an available UserId to assign
8985 private int newUserIdLP(Object obj) {
8986 // Let's be stupidly inefficient for now...
8987 final int N = mUserIds.size();
8988 for (int i=0; i<N; i++) {
8989 if (mUserIds.get(i) == null) {
8990 mUserIds.set(i, obj);
8991 return FIRST_APPLICATION_UID + i;
8992 }
8993 }
8994
8995 // None left?
8996 if (N >= MAX_APPLICATION_UIDS) {
8997 return -1;
8998 }
8999
9000 mUserIds.add(obj);
9001 return FIRST_APPLICATION_UID + N;
9002 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009004 public PackageSetting getDisabledSystemPkg(String name) {
9005 synchronized(mPackages) {
9006 PackageSetting ps = mDisabledSysPackages.get(name);
9007 return ps;
9008 }
9009 }
9010
9011 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9012 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9013 if (Config.LOGV) {
9014 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9015 + " componentName = " + componentInfo.name);
9016 Log.v(TAG, "enabledComponents: "
9017 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9018 Log.v(TAG, "disabledComponents: "
9019 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9020 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009021 if (packageSettings == null) {
9022 if (false) {
9023 Log.w(TAG, "WAITING FOR DEBUGGER");
9024 Debug.waitForDebugger();
9025 Log.i(TAG, "We will crash!");
9026 }
9027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009028 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9029 || ((componentInfo.enabled
9030 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9031 || (componentInfo.applicationInfo.enabled
9032 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9033 && !packageSettings.disabledComponents.contains(componentInfo.name))
9034 || packageSettings.enabledComponents.contains(componentInfo.name));
9035 }
9036 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009037
9038 // ------- apps on sdcard specific code -------
9039 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009040 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009041 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009042 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009043 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009044
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009045 private String getEncryptKey() {
9046 try {
9047 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9048 if (sdEncKey == null) {
9049 sdEncKey = SystemKeyStore.getInstance().
9050 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9051 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009052 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009053 return null;
9054 }
9055 }
9056 return sdEncKey;
9057 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009058 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009059 return null;
9060 }
9061 }
9062
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009063 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009064 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009065 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009066 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009067 if (list != null) {
9068 int idx = 0;
9069 int idList[] = new int[MAX_CONTAINERS];
9070 boolean neverFound = true;
9071 for (String name : list) {
9072 // Ignore null entries
9073 if (name == null) {
9074 continue;
9075 }
9076 int sidx = name.indexOf(prefix);
9077 if (sidx == -1) {
9078 // Not a temp file. just ignore
9079 continue;
9080 }
9081 String subStr = name.substring(sidx + prefix.length());
9082 idList[idx] = -1;
9083 if (subStr != null) {
9084 try {
9085 int cid = Integer.parseInt(subStr);
9086 idList[idx++] = cid;
9087 neverFound = false;
9088 } catch (NumberFormatException e) {
9089 }
9090 }
9091 }
9092 if (!neverFound) {
9093 // Sort idList
9094 Arrays.sort(idList);
9095 for (int j = 1; j <= idList.length; j++) {
9096 if (idList[j-1] != j) {
9097 tmpIdx = j;
9098 break;
9099 }
9100 }
9101 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009102 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009103 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009104 }
9105
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009106 /*
9107 * Return true if PackageManager does have packages to be updated.
9108 */
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009109 public boolean updateExternalMediaStatus(final boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009110 final boolean ret;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009111 synchronized (mPackages) {
9112 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9113 mediaStatus+", mMediaMounted=" + mMediaMounted);
9114 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009115 return false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009116 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009117 mMediaMounted = mediaStatus;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009118 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_EXTERNAL_STORAGE);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009119 ret = appList != null && appList.size() > 0;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009120 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009121 // Queue up an async operation since the package installation may take a little while.
9122 mHandler.post(new Runnable() {
9123 public void run() {
9124 mHandler.removeCallbacks(this);
9125 updateExternalMediaStatusInner(mediaStatus, ret);
9126 }
9127 });
9128 return ret;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009129 }
9130
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009131 private void updateExternalMediaStatusInner(boolean mediaStatus,
9132 boolean sendUpdateBroadcast) {
9133 // If we are up here that means there are packages to be
9134 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009135 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009136 if (list == null || list.length == 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009137 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009138 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009139
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009140 int uidList[] = new int[list.length];
9141 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009142 HashSet<String> removeCids = new HashSet<String>();
9143 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9144 /*HashMap<String, String> cidPathMap = new HashMap<String, String>();
9145 // Don't hold any locks when getting cache paths
9146 for (String cid : list) {
9147 String cpath = PackageHelper.getSdDir(cid);
9148 if (cpath == null) {
9149 removeCids.add(cid);
9150 } else {
9151 cidPathMap.put(cid, cpath);
9152 }
9153 }*/
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009154 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009155 for (String cid : list) {
9156 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009157 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9158 boolean failed = true;
9159 try {
9160 String pkgName = args.getPackageName();
9161 if (pkgName == null) {
9162 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009163 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009164 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9165 PackageSetting ps = mSettings.mPackages.get(pkgName);
9166 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009167 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009168 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9169 " corresponds to pkg : " + pkgName +
9170 " at code path: " + ps.codePathString);
9171 // We do have a valid package installed on sdcard
9172 processCids.put(args, ps.codePathString);
9173 failed = false;
9174 int uid = ps.userId;
9175 if (uid != -1) {
9176 uidList[num++] = uid;
9177 }
9178 }
9179 } finally {
9180 if (failed) {
9181 // Stale container on sdcard. Just delete
9182 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9183 removeCids.add(cid);
9184 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009185 }
9186 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009187 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009188 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009189 int uidArr[] = null;
9190 if (num > 0) {
9191 // Sort uid list
9192 Arrays.sort(uidList, 0, num);
9193 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009194 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009195 uidArr[0] = uidList[0];
9196 int di = 0;
9197 for (int i = 1; i < num; i++) {
9198 if (uidList[i-1] != uidList[i]) {
9199 uidArr[di++] = uidList[i];
9200 }
9201 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009202 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009203 // Process packages with valid entries.
9204 if (mediaStatus) {
9205 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
9206 loadMediaPackages(processCids, uidArr, sendUpdateBroadcast, removeCids);
9207 startCleaningPackages();
9208 } else {
9209 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
9210 unloadMediaPackages(processCids, uidArr, sendUpdateBroadcast);
9211 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009212 }
9213
9214 private void sendResourcesChangedBroadcast(boolean mediaStatus,
9215 ArrayList<String> pkgList, int uidArr[]) {
9216 int size = pkgList.size();
9217 if (size > 0) {
9218 // Send broadcasts here
9219 Bundle extras = new Bundle();
9220 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9221 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009222 if (uidArr != null) {
9223 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9224 }
9225 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9226 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009227 sendPackageBroadcast(action, null, extras);
9228 }
9229 }
9230
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009231 /*
9232 * Look at potentially valid container ids from processCids
9233 * If package information doesn't match the one on record
9234 * or package scanning fails, the cid is added to list of
9235 * removeCids and cleaned up. Since cleaning up containers
9236 * involves destroying them, we do not want any parse
9237 * references to such stale containers. So force gc's
9238 * to avoid unnecessary crashes.
9239 */
9240 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
9241 int uidArr[], boolean sendUpdateBroadcast,
9242 HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009243 ArrayList<String> pkgList = new ArrayList<String>();
9244 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009245 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009246 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009247 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009248 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9249 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009250 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009251 try {
9252 // Make sure there are no container errors first.
9253 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9254 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009255 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009256 " when installing from sdcard");
9257 continue;
9258 }
9259 // Check code path here.
9260 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009261 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009262 " does not match one in settings " + codePath);
9263 continue;
9264 }
9265 // Parse package
9266 int parseFlags = PackageParser.PARSE_CHATTY |
9267 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
9268 PackageParser pp = new PackageParser(codePath);
9269 pp.setSeparateProcesses(mSeparateProcesses);
9270 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
9271 codePath, mMetrics, parseFlags);
9272 pp = null;
9273 doGc = true;
9274 // Check for parse errors
9275 if (pkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009276 Slog.e(TAG, "Parse error when installing install pkg : "
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009277 + args.cid + " from " + args.cachePath);
9278 continue;
9279 }
9280 setApplicationInfoPaths(pkg, codePath, codePath);
9281 synchronized (mInstallLock) {
9282 // Scan the package
9283 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
9284 synchronized (mPackages) {
9285 // Grant permissions
9286 grantPermissionsLP(pkg, false);
9287 // Persist settings
9288 mSettings.writeLP();
9289 retCode = PackageManager.INSTALL_SUCCEEDED;
9290 pkgList.add(pkg.packageName);
9291 // Post process args
9292 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9293 }
9294 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009295 Slog.i(TAG, "Failed to install pkg: " +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009296 pkg.packageName + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009297 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009298 }
9299
9300 } finally {
9301 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9302 // Don't destroy container here. Wait till gc clears things up.
9303 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009304 }
9305 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009306 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009307 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009308 if (sendUpdateBroadcast) {
9309 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9310 }
9311 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009312 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009313 }
9314 // Delete any stale containers if needed.
9315 if (removeCids != null) {
9316 for (String cid : removeCids) {
9317 Log.i(TAG, "Destroying stale container : " + cid);
9318 PackageHelper.destroySdDir(cid);
9319 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009320 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009321 }
9322
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009323 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
9324 int uidArr[], boolean sendUpdateBroadcast) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009325 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009326 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009327 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009328 Set<SdInstallArgs> keys = processCids.keySet();
9329 for (SdInstallArgs args : keys) {
9330 String cid = args.cid;
9331 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009332 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009333 // Delete package internally
9334 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9335 synchronized (mInstallLock) {
9336 boolean res = deletePackageLI(pkgName, false,
9337 PackageManager.DONT_DELETE_DATA, outInfo);
9338 if (res) {
9339 pkgList.add(pkgName);
9340 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009341 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009342 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009343 }
9344 }
9345 }
9346 // Send broadcasts
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009347 if (sendUpdateBroadcast) {
9348 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009349 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009350 // Force gc
9351 Runtime.getRuntime().gc();
9352 // Just unmount all valid containers.
9353 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009354 synchronized (mInstallLock) {
9355 args.doPostDeleteLI(false);
9356 }
9357 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009358 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009359
9360 public void movePackage(final String packageName,
9361 final IPackageMoveObserver observer, final int flags) {
9362 if (packageName == null) {
9363 return;
9364 }
9365 mContext.enforceCallingOrSelfPermission(
9366 android.Manifest.permission.MOVE_PACKAGE, null);
9367 int returnCode = PackageManager.MOVE_SUCCEEDED;
9368 int currFlags = 0;
9369 int newFlags = 0;
9370 synchronized (mPackages) {
9371 PackageParser.Package pkg = mPackages.get(packageName);
9372 if (pkg == null) {
9373 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9374 }
9375 // Disable moving fwd locked apps and system packages
9376 if (pkg.applicationInfo != null &&
9377 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009378 Slog.w(TAG, "Cannot move system application");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009379 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9380 } else if (pkg.applicationInfo != null &&
9381 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009382 Slog.w(TAG, "Cannot move forward locked app.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009383 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9384 } else {
9385 // Find install location first
9386 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9387 (flags & PackageManager.MOVE_INTERNAL) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009388 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009389 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9390 } else {
9391 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9392 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009393 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009394 PackageManager.INSTALL_EXTERNAL : 0;
9395 if (newFlags == currFlags) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009396 Slog.w(TAG, "No move required. Trying to move to same location");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009397 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9398 }
9399 }
9400 }
9401 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9402 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9403 } else {
9404 Message msg = mHandler.obtainMessage(INIT_COPY);
9405 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9406 pkg.applicationInfo.publicSourceDir);
9407 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9408 packageName);
9409 msg.obj = mp;
9410 mHandler.sendMessage(msg);
9411 }
9412 }
9413 }
9414
9415 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9416 // Queue up an async operation since the package deletion may take a little while.
9417 mHandler.post(new Runnable() {
9418 public void run() {
9419 mHandler.removeCallbacks(this);
9420 int returnCode = currentStatus;
9421 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9422 if (moveSucceeded) {
9423 int uid = -1;
9424 synchronized (mPackages) {
9425 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9426 }
9427 ArrayList<String> pkgList = new ArrayList<String>();
9428 pkgList.add(mp.packageName);
9429 int uidArr[] = new int[] { uid };
9430 // Send resources unavailable broadcast
9431 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9432
9433 // Update package code and resource paths
9434 synchronized (mPackages) {
9435 PackageParser.Package pkg = mPackages.get(mp.packageName);
9436 if (pkg != null) {
9437 String oldCodePath = pkg.mPath;
9438 String newCodePath = mp.targetArgs.getCodePath();
9439 String newResPath = mp.targetArgs.getResourcePath();
9440 pkg.mPath = newCodePath;
9441 // Move dex files around
9442 if (moveDexFiles(pkg)
9443 != PackageManager.INSTALL_SUCCEEDED) {
9444 // Moving of dex files failed. Set
9445 // error code and abort move.
9446 pkg.mPath = pkg.mScanPath;
9447 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9448 moveSucceeded = false;
9449 } else {
9450 pkg.mScanPath = newCodePath;
9451 pkg.applicationInfo.sourceDir = newCodePath;
9452 pkg.applicationInfo.publicSourceDir = newResPath;
9453 PackageSetting ps = (PackageSetting) pkg.mExtras;
9454 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9455 ps.codePathString = ps.codePath.getPath();
9456 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9457 ps.resourcePathString = ps.resourcePath.getPath();
9458 // Set the application info flag correctly.
9459 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009460 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009461 } else {
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009462 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009463 }
9464 ps.setFlags(pkg.applicationInfo.flags);
9465 mAppDirs.remove(oldCodePath);
9466 mAppDirs.put(newCodePath, pkg);
9467 // Persist settings
9468 mSettings.writeLP();
9469 }
9470 }
9471 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009472 // Send resources available broadcast
9473 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009474 }
9475 if (!moveSucceeded){
9476 // Clean up failed installation
9477 if (mp.targetArgs != null) {
9478 mp.targetArgs.doPostInstall(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009479 returnCode);
9480 }
9481 } else {
9482 // Force a gc to clear things up.
9483 Runtime.getRuntime().gc();
9484 // Delete older code
9485 synchronized (mInstallLock) {
9486 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009487 }
9488 }
9489 IPackageMoveObserver observer = mp.observer;
9490 if (observer != null) {
9491 try {
9492 observer.packageMoved(mp.packageName, returnCode);
9493 } catch (RemoteException e) {
9494 Log.i(TAG, "Observer no longer exists.");
9495 }
9496 }
9497 }
9498 });
9499 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009500}