blob: 4c1356b6a5138c3141321349b205c871c86ab9e5 [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()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800411 Log.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
436 Log.e(TAG, "Cannot bind to media container service");
437 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.
450 Log.w(TAG, "Empty queue");
451 }
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()) {
461 Log.e(TAG, "Failed to bind to media container service");
462 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) {
585 Log.i(TAG, "Observer no longer exists.");
586 }
587 }
588 } else {
589 Log.e(TAG, "Bogus post-install token " + msg.arg1);
590 }
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) {
644 Log.w(TAG, "**** ro.build.version.sdk not set!");
645 }
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;
668 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
669 } else {
670 mDefParseFlags = 0;
671 mSeparateProcesses = separateProcesses.split(",");
672 Log.w(TAG, "Running with debug.separate_processes: "
673 + 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) {
728 Log.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) {
755 Log.w(TAG, "Boot class path not found: " + paths[i]);
756 } catch (IOException e) {
757 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
758 }
759 }
760 } else {
761 Log.w(TAG, "No BOOTCLASSPATH found!");
762 }
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) {
778 Log.w(TAG, "Library not found: " + lib);
779 } catch (IOException e) {
780 Log.w(TAG, "Exception reading library: " + lib, e);
781 }
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) {
813 Log.w(TAG, "Jar not found: " + path);
814 } catch (IOException e) {
815 Log.w(TAG, "Exception reading jar: " + path, e);
816 }
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@")) {
832 Log.i(TAG, "Pruning dalvik file: " + fn);
833 (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());
908 Log.i(TAG, "Time to scan packages: "
909 + ((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)) {
934 Log.e(TAG, "Package Manager Crash", e);
935 }
936 throw e;
937 }
938 }
939
Dianne Hackborne6620b22010-01-22 14:46:21 -0800940 void cleanupInstallFailedPackage(PackageSetting ps) {
941 Log.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) {
946 Log.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()) {
957 Log.w(TAG, "Unable to remove old code file: " + ps.codePath);
958 }
959 }
960 if (ps.resourcePath != null) {
961 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
962 Log.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
963 }
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()) {
972 Log.w(TAG, "No directory " + libraryDir + ", skipping");
973 return;
974 }
975 if (!libraryDir.canRead()) {
976 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
977 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")) {
988 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
989 continue;
990 }
991 if (!f.canRead()) {
992 Log.w(TAG, "Permissions library file " + f + " cannot be read");
993 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) {
1031 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
1032 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 {
1054 Log.w(TAG, "<group> without gid at "
1055 + 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) {
1063 Log.w(TAG, "<permission> without name at "
1064 + 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) {
1074 Log.w(TAG, "<assign-permission> without name at "
1075 + parser.getPositionDescription());
1076 XmlUtils.skipCurrentTag(parser);
1077 continue;
1078 }
1079 String uidStr = parser.getAttributeValue(null, "uid");
1080 if (uidStr == null) {
1081 Log.w(TAG, "<assign-permission> without uid at "
1082 + parser.getPositionDescription());
1083 XmlUtils.skipCurrentTag(parser);
1084 continue;
1085 }
1086 int uid = Process.getUidForName(uidStr);
1087 if (uid < 0) {
1088 Log.w(TAG, "<assign-permission> with unknown uid \""
1089 + 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) {
1107 Log.w(TAG, "<library> without name at "
1108 + parser.getPositionDescription());
1109 } else if (lfile == null) {
1110 Log.w(TAG, "<library> without file at "
1111 + 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) {
1122 Log.w(TAG, "<feature> without name at "
1123 + 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) {
1140 Log.w(TAG, "Got execption parsing permissions.", e);
1141 } catch (IOException e) {
1142 Log.w(TAG, "Got execption parsing permissions.", e);
1143 }
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 {
1173 Log.w(TAG, "<group> without gid at "
1174 + 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) {
1403 Log.w(TAG, "Couldn't clear application caches");
1404 }
1405 } //end if mInstaller
1406 if (observer != null) {
1407 try {
1408 observer.onRemoveCompleted(null, (retCode >= 0));
1409 } catch (RemoteException e) {
1410 Log.w(TAG, "RemoveException when invoking call back");
1411 }
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) {
1428 Log.w(TAG, "Couldn't clear application caches");
1429 }
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) {
1438 Log.i(TAG, "Failed to send pending intent");
1439 }
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) {
1543 if (obj instanceof SharedUserSetting) {
1544 SharedUserSetting sus = (SharedUserSetting)obj;
1545 if (sus.grantedPermissions.contains(permName)) {
1546 return PackageManager.PERMISSION_GRANTED;
1547 }
1548 } else if (obj instanceof PackageSetting) {
1549 PackageSetting ps = (PackageSetting)obj;
1550 if (ps.grantedPermissions.contains(permName)) {
1551 return PackageManager.PERMISSION_GRANTED;
1552 }
1553 }
1554 } else {
1555 HashSet<String> perms = mSystemPermissions.get(uid);
1556 if (perms != null && perms.contains(permName)) {
1557 return PackageManager.PERMISSION_GRANTED;
1558 }
1559 }
1560 }
1561 return PackageManager.PERMISSION_DENIED;
1562 }
1563
1564 private BasePermission findPermissionTreeLP(String permName) {
1565 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1566 if (permName.startsWith(bp.name) &&
1567 permName.length() > bp.name.length() &&
1568 permName.charAt(bp.name.length()) == '.') {
1569 return bp;
1570 }
1571 }
1572 return null;
1573 }
1574
1575 private BasePermission checkPermissionTreeLP(String permName) {
1576 if (permName != null) {
1577 BasePermission bp = findPermissionTreeLP(permName);
1578 if (bp != null) {
1579 if (bp.uid == Binder.getCallingUid()) {
1580 return bp;
1581 }
1582 throw new SecurityException("Calling uid "
1583 + Binder.getCallingUid()
1584 + " is not allowed to add to permission tree "
1585 + bp.name + " owned by uid " + bp.uid);
1586 }
1587 }
1588 throw new SecurityException("No permission tree found for " + permName);
1589 }
1590
1591 public boolean addPermission(PermissionInfo info) {
1592 synchronized (mPackages) {
1593 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1594 throw new SecurityException("Label must be specified in permission");
1595 }
1596 BasePermission tree = checkPermissionTreeLP(info.name);
1597 BasePermission bp = mSettings.mPermissions.get(info.name);
1598 boolean added = bp == null;
1599 if (added) {
1600 bp = new BasePermission(info.name, tree.sourcePackage,
1601 BasePermission.TYPE_DYNAMIC);
1602 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1603 throw new SecurityException(
1604 "Not allowed to modify non-dynamic permission "
1605 + info.name);
1606 }
1607 bp.perm = new PackageParser.Permission(tree.perm.owner,
1608 new PermissionInfo(info));
1609 bp.perm.info.packageName = tree.perm.info.packageName;
1610 bp.uid = tree.uid;
1611 if (added) {
1612 mSettings.mPermissions.put(info.name, bp);
1613 }
1614 mSettings.writeLP();
1615 return added;
1616 }
1617 }
1618
1619 public void removePermission(String name) {
1620 synchronized (mPackages) {
1621 checkPermissionTreeLP(name);
1622 BasePermission bp = mSettings.mPermissions.get(name);
1623 if (bp != null) {
1624 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1625 throw new SecurityException(
1626 "Not allowed to modify non-dynamic permission "
1627 + name);
1628 }
1629 mSettings.mPermissions.remove(name);
1630 mSettings.writeLP();
1631 }
1632 }
1633 }
1634
Dianne Hackborn854060af2009-07-09 18:14:31 -07001635 public boolean isProtectedBroadcast(String actionName) {
1636 synchronized (mPackages) {
1637 return mProtectedBroadcasts.contains(actionName);
1638 }
1639 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 public int checkSignatures(String pkg1, String pkg2) {
1642 synchronized (mPackages) {
1643 PackageParser.Package p1 = mPackages.get(pkg1);
1644 PackageParser.Package p2 = mPackages.get(pkg2);
1645 if (p1 == null || p1.mExtras == null
1646 || p2 == null || p2.mExtras == null) {
1647 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1648 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001649 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 }
1651 }
1652
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001653 public int checkUidSignatures(int uid1, int uid2) {
1654 synchronized (mPackages) {
1655 Signature[] s1;
1656 Signature[] s2;
1657 Object obj = mSettings.getUserIdLP(uid1);
1658 if (obj != null) {
1659 if (obj instanceof SharedUserSetting) {
1660 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1661 } else if (obj instanceof PackageSetting) {
1662 s1 = ((PackageSetting)obj).signatures.mSignatures;
1663 } else {
1664 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1665 }
1666 } else {
1667 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1668 }
1669 obj = mSettings.getUserIdLP(uid2);
1670 if (obj != null) {
1671 if (obj instanceof SharedUserSetting) {
1672 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1673 } else if (obj instanceof PackageSetting) {
1674 s2 = ((PackageSetting)obj).signatures.mSignatures;
1675 } else {
1676 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1677 }
1678 } else {
1679 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1680 }
1681 return checkSignaturesLP(s1, s2);
1682 }
1683 }
1684
1685 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1686 if (s1 == null) {
1687 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1689 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1690 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001691 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1693 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001694 final int N1 = s1.length;
1695 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 for (int i=0; i<N1; i++) {
1697 boolean match = false;
1698 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001699 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 match = true;
1701 break;
1702 }
1703 }
1704 if (!match) {
1705 return PackageManager.SIGNATURE_NO_MATCH;
1706 }
1707 }
1708 return PackageManager.SIGNATURE_MATCH;
1709 }
1710
1711 public String[] getPackagesForUid(int uid) {
1712 synchronized (mPackages) {
1713 Object obj = mSettings.getUserIdLP(uid);
1714 if (obj instanceof SharedUserSetting) {
1715 SharedUserSetting sus = (SharedUserSetting)obj;
1716 final int N = sus.packages.size();
1717 String[] res = new String[N];
1718 Iterator<PackageSetting> it = sus.packages.iterator();
1719 int i=0;
1720 while (it.hasNext()) {
1721 res[i++] = it.next().name;
1722 }
1723 return res;
1724 } else if (obj instanceof PackageSetting) {
1725 PackageSetting ps = (PackageSetting)obj;
1726 return new String[] { ps.name };
1727 }
1728 }
1729 return null;
1730 }
1731
1732 public String getNameForUid(int uid) {
1733 synchronized (mPackages) {
1734 Object obj = mSettings.getUserIdLP(uid);
1735 if (obj instanceof SharedUserSetting) {
1736 SharedUserSetting sus = (SharedUserSetting)obj;
1737 return sus.name + ":" + sus.userId;
1738 } else if (obj instanceof PackageSetting) {
1739 PackageSetting ps = (PackageSetting)obj;
1740 return ps.name;
1741 }
1742 }
1743 return null;
1744 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 public int getUidForSharedUser(String sharedUserName) {
1747 if(sharedUserName == null) {
1748 return -1;
1749 }
1750 synchronized (mPackages) {
1751 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1752 if(suid == null) {
1753 return -1;
1754 }
1755 return suid.userId;
1756 }
1757 }
1758
1759 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1760 int flags) {
1761 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001762 return chooseBestActivity(intent, resolvedType, flags, query);
1763 }
1764
Mihai Predaeae850c2009-05-13 10:13:48 +02001765 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1766 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 if (query != null) {
1768 final int N = query.size();
1769 if (N == 1) {
1770 return query.get(0);
1771 } else if (N > 1) {
1772 // If there is more than one activity with the same priority,
1773 // then let the user decide between them.
1774 ResolveInfo r0 = query.get(0);
1775 ResolveInfo r1 = query.get(1);
1776 if (false) {
1777 System.out.println(r0.activityInfo.name +
1778 "=" + r0.priority + " vs " +
1779 r1.activityInfo.name +
1780 "=" + r1.priority);
1781 }
1782 // If the first activity has a higher priority, or a different
1783 // default, then it is always desireable to pick it.
1784 if (r0.priority != r1.priority
1785 || r0.preferredOrder != r1.preferredOrder
1786 || r0.isDefault != r1.isDefault) {
1787 return query.get(0);
1788 }
1789 // If we have saved a preference for a preferred activity for
1790 // this Intent, use that.
1791 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1792 flags, query, r0.priority);
1793 if (ri != null) {
1794 return ri;
1795 }
1796 return mResolveInfo;
1797 }
1798 }
1799 return null;
1800 }
1801
1802 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1803 int flags, List<ResolveInfo> query, int priority) {
1804 synchronized (mPackages) {
1805 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1806 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001807 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1809 if (prefs != null && prefs.size() > 0) {
1810 // First figure out how good the original match set is.
1811 // We will only allow preferred activities that came
1812 // from the same match quality.
1813 int match = 0;
1814 final int N = query.size();
1815 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1816 for (int j=0; j<N; j++) {
1817 ResolveInfo ri = query.get(j);
1818 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1819 + ": 0x" + Integer.toHexString(match));
1820 if (ri.match > match) match = ri.match;
1821 }
1822 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1823 + Integer.toHexString(match));
1824 match &= IntentFilter.MATCH_CATEGORY_MASK;
1825 final int M = prefs.size();
1826 for (int i=0; i<M; i++) {
1827 PreferredActivity pa = prefs.get(i);
1828 if (pa.mMatch != match) {
1829 continue;
1830 }
1831 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1832 if (DEBUG_PREFERRED) {
1833 Log.v(TAG, "Got preferred activity:");
1834 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1835 }
1836 if (ai != null) {
1837 for (int j=0; j<N; j++) {
1838 ResolveInfo ri = query.get(j);
1839 if (!ri.activityInfo.applicationInfo.packageName
1840 .equals(ai.applicationInfo.packageName)) {
1841 continue;
1842 }
1843 if (!ri.activityInfo.name.equals(ai.name)) {
1844 continue;
1845 }
1846
1847 // Okay we found a previously set preferred app.
1848 // If the result set is different from when this
1849 // was created, we need to clear it and re-ask the
1850 // user their preference.
1851 if (!pa.sameSet(query, priority)) {
1852 Log.i(TAG, "Result set changed, dropping preferred activity for "
1853 + intent + " type " + resolvedType);
1854 mSettings.mPreferredActivities.removeFilter(pa);
1855 return null;
1856 }
1857
1858 // Yay!
1859 return ri;
1860 }
1861 }
1862 }
1863 }
1864 }
1865 return null;
1866 }
1867
1868 public List<ResolveInfo> queryIntentActivities(Intent intent,
1869 String resolvedType, int flags) {
1870 ComponentName comp = intent.getComponent();
1871 if (comp != null) {
1872 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1873 ActivityInfo ai = getActivityInfo(comp, flags);
1874 if (ai != null) {
1875 ResolveInfo ri = new ResolveInfo();
1876 ri.activityInfo = ai;
1877 list.add(ri);
1878 }
1879 return list;
1880 }
1881
1882 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001883 String pkgName = intent.getPackage();
1884 if (pkgName == null) {
1885 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1886 resolvedType, flags);
1887 }
1888 PackageParser.Package pkg = mPackages.get(pkgName);
1889 if (pkg != null) {
1890 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1891 resolvedType, flags, pkg.activities);
1892 }
1893 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 }
1895 }
1896
1897 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1898 Intent[] specifics, String[] specificTypes, Intent intent,
1899 String resolvedType, int flags) {
1900 final String resultsAction = intent.getAction();
1901
1902 List<ResolveInfo> results = queryIntentActivities(
1903 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1904 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1905
1906 int specificsPos = 0;
1907 int N;
1908
1909 // todo: note that the algorithm used here is O(N^2). This
1910 // isn't a problem in our current environment, but if we start running
1911 // into situations where we have more than 5 or 10 matches then this
1912 // should probably be changed to something smarter...
1913
1914 // First we go through and resolve each of the specific items
1915 // that were supplied, taking care of removing any corresponding
1916 // duplicate items in the generic resolve list.
1917 if (specifics != null) {
1918 for (int i=0; i<specifics.length; i++) {
1919 final Intent sintent = specifics[i];
1920 if (sintent == null) {
1921 continue;
1922 }
1923
1924 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1925 String action = sintent.getAction();
1926 if (resultsAction != null && resultsAction.equals(action)) {
1927 // If this action was explicitly requested, then don't
1928 // remove things that have it.
1929 action = null;
1930 }
1931 ComponentName comp = sintent.getComponent();
1932 ResolveInfo ri = null;
1933 ActivityInfo ai = null;
1934 if (comp == null) {
1935 ri = resolveIntent(
1936 sintent,
1937 specificTypes != null ? specificTypes[i] : null,
1938 flags);
1939 if (ri == null) {
1940 continue;
1941 }
1942 if (ri == mResolveInfo) {
1943 // ACK! Must do something better with this.
1944 }
1945 ai = ri.activityInfo;
1946 comp = new ComponentName(ai.applicationInfo.packageName,
1947 ai.name);
1948 } else {
1949 ai = getActivityInfo(comp, flags);
1950 if (ai == null) {
1951 continue;
1952 }
1953 }
1954
1955 // Look for any generic query activities that are duplicates
1956 // of this specific one, and remove them from the results.
1957 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1958 N = results.size();
1959 int j;
1960 for (j=specificsPos; j<N; j++) {
1961 ResolveInfo sri = results.get(j);
1962 if ((sri.activityInfo.name.equals(comp.getClassName())
1963 && sri.activityInfo.applicationInfo.packageName.equals(
1964 comp.getPackageName()))
1965 || (action != null && sri.filter.matchAction(action))) {
1966 results.remove(j);
1967 if (Config.LOGV) Log.v(
1968 TAG, "Removing duplicate item from " + j
1969 + " due to specific " + specificsPos);
1970 if (ri == null) {
1971 ri = sri;
1972 }
1973 j--;
1974 N--;
1975 }
1976 }
1977
1978 // Add this specific item to its proper place.
1979 if (ri == null) {
1980 ri = new ResolveInfo();
1981 ri.activityInfo = ai;
1982 }
1983 results.add(specificsPos, ri);
1984 ri.specificIndex = i;
1985 specificsPos++;
1986 }
1987 }
1988
1989 // Now we go through the remaining generic results and remove any
1990 // duplicate actions that are found here.
1991 N = results.size();
1992 for (int i=specificsPos; i<N-1; i++) {
1993 final ResolveInfo rii = results.get(i);
1994 if (rii.filter == null) {
1995 continue;
1996 }
1997
1998 // Iterate over all of the actions of this result's intent
1999 // filter... typically this should be just one.
2000 final Iterator<String> it = rii.filter.actionsIterator();
2001 if (it == null) {
2002 continue;
2003 }
2004 while (it.hasNext()) {
2005 final String action = it.next();
2006 if (resultsAction != null && resultsAction.equals(action)) {
2007 // If this action was explicitly requested, then don't
2008 // remove things that have it.
2009 continue;
2010 }
2011 for (int j=i+1; j<N; j++) {
2012 final ResolveInfo rij = results.get(j);
2013 if (rij.filter != null && rij.filter.hasAction(action)) {
2014 results.remove(j);
2015 if (Config.LOGV) Log.v(
2016 TAG, "Removing duplicate item from " + j
2017 + " due to action " + action + " at " + i);
2018 j--;
2019 N--;
2020 }
2021 }
2022 }
2023
2024 // If the caller didn't request filter information, drop it now
2025 // so we don't have to marshall/unmarshall it.
2026 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2027 rii.filter = null;
2028 }
2029 }
2030
2031 // Filter out the caller activity if so requested.
2032 if (caller != null) {
2033 N = results.size();
2034 for (int i=0; i<N; i++) {
2035 ActivityInfo ainfo = results.get(i).activityInfo;
2036 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2037 && caller.getClassName().equals(ainfo.name)) {
2038 results.remove(i);
2039 break;
2040 }
2041 }
2042 }
2043
2044 // If the caller didn't request filter information,
2045 // drop them now so we don't have to
2046 // marshall/unmarshall it.
2047 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2048 N = results.size();
2049 for (int i=0; i<N; i++) {
2050 results.get(i).filter = null;
2051 }
2052 }
2053
2054 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2055 return results;
2056 }
2057
2058 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2059 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002060 ComponentName comp = intent.getComponent();
2061 if (comp != null) {
2062 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2063 ActivityInfo ai = getReceiverInfo(comp, flags);
2064 if (ai != null) {
2065 ResolveInfo ri = new ResolveInfo();
2066 ri.activityInfo = ai;
2067 list.add(ri);
2068 }
2069 return list;
2070 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002073 String pkgName = intent.getPackage();
2074 if (pkgName == null) {
2075 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2076 resolvedType, flags);
2077 }
2078 PackageParser.Package pkg = mPackages.get(pkgName);
2079 if (pkg != null) {
2080 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2081 resolvedType, flags, pkg.receivers);
2082 }
2083 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 }
2085 }
2086
2087 public ResolveInfo resolveService(Intent intent, String resolvedType,
2088 int flags) {
2089 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2090 flags);
2091 if (query != null) {
2092 if (query.size() >= 1) {
2093 // If there is more than one service with the same priority,
2094 // just arbitrarily pick the first one.
2095 return query.get(0);
2096 }
2097 }
2098 return null;
2099 }
2100
2101 public List<ResolveInfo> queryIntentServices(Intent intent,
2102 String resolvedType, int flags) {
2103 ComponentName comp = intent.getComponent();
2104 if (comp != null) {
2105 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2106 ServiceInfo si = getServiceInfo(comp, flags);
2107 if (si != null) {
2108 ResolveInfo ri = new ResolveInfo();
2109 ri.serviceInfo = si;
2110 list.add(ri);
2111 }
2112 return list;
2113 }
2114
2115 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002116 String pkgName = intent.getPackage();
2117 if (pkgName == null) {
2118 return (List<ResolveInfo>)mServices.queryIntent(intent,
2119 resolvedType, flags);
2120 }
2121 PackageParser.Package pkg = mPackages.get(pkgName);
2122 if (pkg != null) {
2123 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2124 resolvedType, flags, pkg.services);
2125 }
2126 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 }
2128 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 public List<PackageInfo> getInstalledPackages(int flags) {
2131 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2132
2133 synchronized (mPackages) {
2134 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2135 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2136 while (i.hasNext()) {
2137 final PackageSetting ps = i.next();
2138 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2139 if(psPkg != null) {
2140 finalList.add(psPkg);
2141 }
2142 }
2143 }
2144 else {
2145 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2146 while (i.hasNext()) {
2147 final PackageParser.Package p = i.next();
2148 if (p.applicationInfo != null) {
2149 PackageInfo pi = generatePackageInfo(p, flags);
2150 if(pi != null) {
2151 finalList.add(pi);
2152 }
2153 }
2154 }
2155 }
2156 }
2157 return finalList;
2158 }
2159
2160 public List<ApplicationInfo> getInstalledApplications(int flags) {
2161 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2162 synchronized(mPackages) {
2163 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2164 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2165 while (i.hasNext()) {
2166 final PackageSetting ps = i.next();
2167 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2168 if(ai != null) {
2169 finalList.add(ai);
2170 }
2171 }
2172 }
2173 else {
2174 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2175 while (i.hasNext()) {
2176 final PackageParser.Package p = i.next();
2177 if (p.applicationInfo != null) {
2178 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2179 if(ai != null) {
2180 finalList.add(ai);
2181 }
2182 }
2183 }
2184 }
2185 }
2186 return finalList;
2187 }
2188
2189 public List<ApplicationInfo> getPersistentApplications(int flags) {
2190 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2191
2192 synchronized (mPackages) {
2193 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2194 while (i.hasNext()) {
2195 PackageParser.Package p = i.next();
2196 if (p.applicationInfo != null
2197 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2198 && (!mSafeMode || (p.applicationInfo.flags
2199 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2200 finalList.add(p.applicationInfo);
2201 }
2202 }
2203 }
2204
2205 return finalList;
2206 }
2207
2208 public ProviderInfo resolveContentProvider(String name, int flags) {
2209 synchronized (mPackages) {
2210 final PackageParser.Provider provider = mProviders.get(name);
2211 return provider != null
2212 && mSettings.isEnabledLP(provider.info, flags)
2213 && (!mSafeMode || (provider.info.applicationInfo.flags
2214 &ApplicationInfo.FLAG_SYSTEM) != 0)
2215 ? PackageParser.generateProviderInfo(provider, flags)
2216 : null;
2217 }
2218 }
2219
Fred Quintana718d8a22009-04-29 17:53:20 -07002220 /**
2221 * @deprecated
2222 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 public void querySyncProviders(List outNames, List outInfo) {
2224 synchronized (mPackages) {
2225 Iterator<Map.Entry<String, PackageParser.Provider>> i
2226 = mProviders.entrySet().iterator();
2227
2228 while (i.hasNext()) {
2229 Map.Entry<String, PackageParser.Provider> entry = i.next();
2230 PackageParser.Provider p = entry.getValue();
2231
2232 if (p.syncable
2233 && (!mSafeMode || (p.info.applicationInfo.flags
2234 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2235 outNames.add(entry.getKey());
2236 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2237 }
2238 }
2239 }
2240 }
2241
2242 public List<ProviderInfo> queryContentProviders(String processName,
2243 int uid, int flags) {
2244 ArrayList<ProviderInfo> finalList = null;
2245
2246 synchronized (mPackages) {
2247 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2248 while (i.hasNext()) {
2249 PackageParser.Provider p = i.next();
2250 if (p.info.authority != null
2251 && (processName == null ||
2252 (p.info.processName.equals(processName)
2253 && p.info.applicationInfo.uid == uid))
2254 && mSettings.isEnabledLP(p.info, flags)
2255 && (!mSafeMode || (p.info.applicationInfo.flags
2256 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2257 if (finalList == null) {
2258 finalList = new ArrayList<ProviderInfo>(3);
2259 }
2260 finalList.add(PackageParser.generateProviderInfo(p,
2261 flags));
2262 }
2263 }
2264 }
2265
2266 if (finalList != null) {
2267 Collections.sort(finalList, mProviderInitOrderSorter);
2268 }
2269
2270 return finalList;
2271 }
2272
2273 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2274 int flags) {
2275 synchronized (mPackages) {
2276 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2277 return PackageParser.generateInstrumentationInfo(i, flags);
2278 }
2279 }
2280
2281 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2282 int flags) {
2283 ArrayList<InstrumentationInfo> finalList =
2284 new ArrayList<InstrumentationInfo>();
2285
2286 synchronized (mPackages) {
2287 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2288 while (i.hasNext()) {
2289 PackageParser.Instrumentation p = i.next();
2290 if (targetPackage == null
2291 || targetPackage.equals(p.info.targetPackage)) {
2292 finalList.add(PackageParser.generateInstrumentationInfo(p,
2293 flags));
2294 }
2295 }
2296 }
2297
2298 return finalList;
2299 }
2300
2301 private void scanDirLI(File dir, int flags, int scanMode) {
2302 Log.d(TAG, "Scanning app dir " + dir);
2303
2304 String[] files = dir.list();
2305
2306 int i;
2307 for (i=0; i<files.length; i++) {
2308 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002309 if (!isPackageFilename(files[i])) {
2310 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002311 continue;
2312 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002313 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002315 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002316 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2317 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002318 // Delete the apk
2319 Log.w(TAG, "Cleaning up failed install of " + file);
2320 file.delete();
2321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322 }
2323 }
2324
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002325 private static File getSettingsProblemFile() {
2326 File dataDir = Environment.getDataDirectory();
2327 File systemDir = new File(dataDir, "system");
2328 File fname = new File(systemDir, "uiderrors.txt");
2329 return fname;
2330 }
2331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002332 private static void reportSettingsProblem(int priority, String msg) {
2333 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002334 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002335 FileOutputStream out = new FileOutputStream(fname, true);
2336 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002337 SimpleDateFormat formatter = new SimpleDateFormat();
2338 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2339 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002340 pw.close();
2341 FileUtils.setPermissions(
2342 fname.toString(),
2343 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2344 -1, -1);
2345 } catch (java.io.IOException e) {
2346 }
2347 Log.println(priority, TAG, msg);
2348 }
2349
2350 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2351 PackageParser.Package pkg, File srcFile, int parseFlags) {
2352 if (GET_CERTIFICATES) {
2353 if (ps == null || !ps.codePath.equals(srcFile)
2354 || ps.getTimeStamp() != srcFile.lastModified()) {
2355 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2356 if (!pp.collectCertificates(pkg, parseFlags)) {
2357 mLastScanError = pp.getParseError();
2358 return false;
2359 }
2360 }
2361 }
2362 return true;
2363 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 /*
2366 * Scan a package and return the newly parsed package.
2367 * Returns null in case of errors and the error code is stored in mLastScanError
2368 */
2369 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002370 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002372 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002374 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002377 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 if (pkg == null) {
2379 mLastScanError = pp.getParseError();
2380 return null;
2381 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002382 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002383 PackageSetting updatedPkg;
2384 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002385 // Look to see if we already know about this package.
2386 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002387 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002388 // This package has been renamed to its original name. Let's
2389 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002390 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002391 }
2392 // If there was no original package, see one for the real package name.
2393 if (ps == null) {
2394 ps = mSettings.peekPackageLP(pkg.packageName);
2395 }
2396 // Check to see if this package could be hiding/updating a system
2397 // package. Must look for it either under the original or real
2398 // package name depending on our state.
2399 updatedPkg = mSettings.mDisabledSysPackages.get(
2400 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002402 // First check if this is a system package that may involve an update
2403 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2404 if (!ps.codePath.equals(scanFile)) {
2405 // The path has changed from what was last scanned... check the
2406 // version of the new path against what we have stored to determine
2407 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002408 if (pkg.mVersionCode < ps.versionCode) {
2409 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002410 // Ignore entry. Skip it.
2411 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2412 + "ignored: updated version " + ps.versionCode
2413 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002414 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2415 return null;
2416 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002417 // The current app on the system partion is better than
2418 // what we have updated to on the data partition; switch
2419 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002420 // At this point, its safely assumed that package installation for
2421 // apps in system partition will go through. If not there won't be a working
2422 // version of the app
2423 synchronized (mPackages) {
2424 // Just remove the loaded entries from package lists.
2425 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002426 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002427 Log.w(TAG, "Package " + ps.name + " at " + scanFile
2428 + "reverting from " + ps.codePathString
2429 + ": new version " + pkg.mVersionCode
2430 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002431 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2432 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002433 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 }
2436 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002437 if (updatedPkg != null) {
2438 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2439 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2440 }
2441 // Verify certificates against what was last scanned
2442 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2443 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2444 return null;
2445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 // The apk is forward locked (not public) if its code and resources
2447 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002448 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002450 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002451 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002452
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002453 String codePath = null;
2454 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002455 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2456 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002457 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002458 } else {
2459 // Should not happen at all. Just log an error.
2460 Log.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
2461 }
2462 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002463 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002464 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002465 codePath = pkg.mScanPath;
2466 // Set application objects path explicitly.
2467 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002468 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002469 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470 }
2471
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002472 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2473 String destCodePath, String destResPath) {
2474 pkg.mPath = pkg.mScanPath = destCodePath;
2475 pkg.applicationInfo.sourceDir = destCodePath;
2476 pkg.applicationInfo.publicSourceDir = destResPath;
2477 }
2478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 private static String fixProcessName(String defProcessName,
2480 String processName, int uid) {
2481 if (processName == null) {
2482 return defProcessName;
2483 }
2484 return processName;
2485 }
2486
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002487 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2489 if (pkg.mSignatures != null) {
2490 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2491 updateSignature)) {
2492 Log.e(TAG, "Package " + pkg.packageName
2493 + " signatures do not match the previously installed version; ignoring!");
2494 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2495 return false;
2496 }
2497
2498 if (pkgSetting.sharedUser != null) {
2499 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2500 pkg.mSignatures, updateSignature)) {
2501 Log.e(TAG, "Package " + pkg.packageName
2502 + " has no signatures that match those in shared user "
2503 + pkgSetting.sharedUser.name + "; ignoring!");
2504 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2505 return false;
2506 }
2507 }
2508 } else {
2509 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2510 }
2511 return true;
2512 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002513
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002514 public boolean performDexOpt(String packageName) {
2515 if (!mNoDexOpt) {
2516 return false;
2517 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002518
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002519 PackageParser.Package p;
2520 synchronized (mPackages) {
2521 p = mPackages.get(packageName);
2522 if (p == null || p.mDidDexOpt) {
2523 return false;
2524 }
2525 }
2526 synchronized (mInstallLock) {
2527 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2528 }
2529 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002530
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002531 static final int DEX_OPT_SKIPPED = 0;
2532 static final int DEX_OPT_PERFORMED = 1;
2533 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002534
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002535 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2536 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002537 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002538 String path = pkg.mScanPath;
2539 int ret = 0;
2540 try {
2541 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002542 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002543 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002544 pkg.mDidDexOpt = true;
2545 performed = true;
2546 }
2547 } catch (FileNotFoundException e) {
2548 Log.w(TAG, "Apk not found for dexopt: " + path);
2549 ret = -1;
2550 } catch (IOException e) {
2551 Log.w(TAG, "Exception reading apk: " + path, e);
2552 ret = -1;
2553 }
2554 if (ret < 0) {
2555 //error from installer
2556 return DEX_OPT_FAILED;
2557 }
2558 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002559
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002560 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2561 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002562
2563 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2564 return Environment.isEncryptedFilesystemEnabled() &&
2565 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2566 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002567
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002568 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2569 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2570 Log.w(TAG, "Unable to update from " + oldPkg.name
2571 + " to " + newPkg.packageName
2572 + ": old package not in system partition");
2573 return false;
2574 } else if (mPackages.get(oldPkg.name) != null) {
2575 Log.w(TAG, "Unable to update from " + oldPkg.name
2576 + " to " + newPkg.packageName
2577 + ": old package still exists");
2578 return false;
2579 }
2580 return true;
2581 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002582
2583 private File getDataPathForPackage(PackageParser.Package pkg) {
2584 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2585 File dataPath;
2586 if (useEncryptedFSDir) {
2587 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2588 } else {
2589 dataPath = new File(mAppDataDir, pkg.packageName);
2590 }
2591 return dataPath;
2592 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002593
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002594 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2595 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002596 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002597 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2598 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002599 // Bail out. The resource and code paths haven't been set.
2600 Log.w(TAG, " Code and resource paths haven't been set correctly");
2601 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2602 return null;
2603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 mScanningPath = scanFile;
2605 if (pkg == null) {
2606 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2607 return null;
2608 }
2609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002610 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2611 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2612 }
2613
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002614 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 synchronized (mPackages) {
2616 if (mAndroidApplication != null) {
2617 Log.w(TAG, "*************************************************");
2618 Log.w(TAG, "Core android package being redefined. Skipping.");
2619 Log.w(TAG, " file=" + mScanningPath);
2620 Log.w(TAG, "*************************************************");
2621 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2622 return null;
2623 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 // Set up information for our fall-back user intent resolution
2626 // activity.
2627 mPlatformPackage = pkg;
2628 pkg.mVersionCode = mSdkVersion;
2629 mAndroidApplication = pkg.applicationInfo;
2630 mResolveActivity.applicationInfo = mAndroidApplication;
2631 mResolveActivity.name = ResolverActivity.class.getName();
2632 mResolveActivity.packageName = mAndroidApplication.packageName;
2633 mResolveActivity.processName = mAndroidApplication.processName;
2634 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2635 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2636 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2637 mResolveActivity.exported = true;
2638 mResolveActivity.enabled = true;
2639 mResolveInfo.activityInfo = mResolveActivity;
2640 mResolveInfo.priority = 0;
2641 mResolveInfo.preferredOrder = 0;
2642 mResolveInfo.match = 0;
2643 mResolveComponentName = new ComponentName(
2644 mAndroidApplication.packageName, mResolveActivity.name);
2645 }
2646 }
2647
2648 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002649 TAG, "Scanning package " + pkg.packageName);
2650 if (mPackages.containsKey(pkg.packageName)
2651 || mSharedLibraries.containsKey(pkg.packageName)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 Log.w(TAG, "*************************************************");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002653 Log.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 + " already installed. Skipping duplicate.");
2655 Log.w(TAG, "*************************************************");
2656 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2657 return null;
2658 }
2659
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002660 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002661 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2662 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 SharedUserSetting suid = null;
2665 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002668
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002669 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2670 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002671 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002672 pkg.mRealPackage = null;
2673 pkg.mAdoptPermissions = null;
2674 }
2675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 synchronized (mPackages) {
2677 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002678 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2679 if (mTmpSharedLibraries == null ||
2680 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2681 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2682 }
2683 int num = 0;
2684 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2685 for (int i=0; i<N; i++) {
2686 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687 if (file == null) {
2688 Log.e(TAG, "Package " + pkg.packageName
2689 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002690 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002691 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2692 return null;
2693 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002694 mTmpSharedLibraries[num] = file;
2695 num++;
2696 }
2697 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2698 for (int i=0; i<N; i++) {
2699 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2700 if (file == null) {
2701 Log.w(TAG, "Package " + pkg.packageName
2702 + " desires unavailable shared library "
2703 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2704 } else {
2705 mTmpSharedLibraries[num] = file;
2706 num++;
2707 }
2708 }
2709 if (num > 0) {
2710 pkg.usesLibraryFiles = new String[num];
2711 System.arraycopy(mTmpSharedLibraries, 0,
2712 pkg.usesLibraryFiles, 0, num);
2713 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002714
Dianne Hackborn49237342009-08-27 20:08:01 -07002715 if (pkg.reqFeatures != null) {
2716 N = pkg.reqFeatures.size();
2717 for (int i=0; i<N; i++) {
2718 FeatureInfo fi = pkg.reqFeatures.get(i);
2719 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2720 // Don't care.
2721 continue;
2722 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002723
Dianne Hackborn49237342009-08-27 20:08:01 -07002724 if (fi.name != null) {
2725 if (mAvailableFeatures.get(fi.name) == null) {
2726 Log.e(TAG, "Package " + pkg.packageName
2727 + " requires unavailable feature "
2728 + fi.name + "; failing!");
2729 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2730 return null;
2731 }
2732 }
2733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 }
2735 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 if (pkg.mSharedUserId != null) {
2738 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2739 pkg.applicationInfo.flags, true);
2740 if (suid == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002741 Log.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 + " for shared user failed");
2743 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2744 return null;
2745 }
2746 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2747 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2748 + suid.userId + "): packages=" + suid.packages);
2749 }
2750 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002751
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002752 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002753 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002754 Log.w(TAG, "WAITING FOR DEBUGGER");
2755 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002756 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2757 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002758 }
2759 }
2760
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002761 // Check if we are renaming from an original package name.
2762 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002763 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002764 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002765 // This package may need to be renamed to a previously
2766 // installed name. Let's check on that...
2767 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002768 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002769 // This package had originally been installed as the
2770 // original name, and we have already taken care of
2771 // transitioning to the new one. Just update the new
2772 // one to continue using the old name.
2773 realName = pkg.mRealPackage;
2774 if (!pkg.packageName.equals(renamed)) {
2775 // Callers into this function may have already taken
2776 // care of renaming the package; only do it here if
2777 // it is not already done.
2778 pkg.setPackageName(renamed);
2779 }
2780
Dianne Hackbornc1552392010-03-03 16:19:01 -08002781 } else {
2782 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2783 if ((origPackage=mSettings.peekPackageLP(
2784 pkg.mOriginalPackages.get(i))) != null) {
2785 // We do have the package already installed under its
2786 // original name... should we use it?
2787 if (!verifyPackageUpdate(origPackage, pkg)) {
2788 // New package is not compatible with original.
2789 origPackage = null;
2790 continue;
2791 } else if (origPackage.sharedUser != null) {
2792 // Make sure uid is compatible between packages.
2793 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
2794 Log.w(TAG, "Unable to migrate data from " + origPackage.name
2795 + " to " + pkg.packageName + ": old uid "
2796 + origPackage.sharedUser.name
2797 + " differs from " + pkg.mSharedUserId);
2798 origPackage = null;
2799 continue;
2800 }
2801 } else {
2802 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2803 + pkg.packageName + " to old name " + origPackage.name);
2804 }
2805 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002806 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002807 }
2808 }
2809 }
2810
2811 if (mTransferedPackages.contains(pkg.packageName)) {
2812 Log.w(TAG, "Package " + pkg.packageName
2813 + " was transferred to another, but its .apk remains");
2814 }
2815
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002816 // Just create the setting, don't add it yet. For already existing packages
2817 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002818 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 destResourceFile, pkg.applicationInfo.flags, true, false);
2820 if (pkgSetting == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002821 Log.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2823 return null;
2824 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002825
2826 if (pkgSetting.origPackage != null) {
2827 // If we are first transitioning from an original package,
2828 // fix up the new package's name now. We need to do this after
2829 // looking up the package under its new name, so getPackageLP
2830 // can take care of fiddling things correctly.
2831 pkg.setPackageName(origPackage.name);
2832
2833 // File a report about this.
2834 String msg = "New package " + pkgSetting.realName
2835 + " renamed to replace old package " + pkgSetting.name;
2836 reportSettingsProblem(Log.WARN, msg);
2837
2838 // Make a note of it.
2839 mTransferedPackages.add(origPackage.name);
2840
2841 // No longer need to retain this.
2842 pkgSetting.origPackage = null;
2843 }
2844
2845 if (realName != null) {
2846 // Make a note of it.
2847 mTransferedPackages.add(pkg.packageName);
2848 }
2849
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002850 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2852 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002854 pkg.applicationInfo.uid = pkgSetting.userId;
2855 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002856
2857 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2859 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2860 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2861 return null;
2862 }
2863 // The signature has changed, but this package is in the system
2864 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002865 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 // However... if this package is part of a shared user, but it
2867 // doesn't match the signature of the shared user, let's fail.
2868 // What this means is that you can't change the signatures
2869 // associated with an overall shared user, which doesn't seem all
2870 // that unreasonable.
2871 if (pkgSetting.sharedUser != null) {
2872 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2873 pkg.mSignatures, false)) {
2874 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2875 return null;
2876 }
2877 }
2878 removeExisting = true;
2879 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002880
The Android Open Source Project10592532009-03-18 17:39:46 -07002881 // Verify that this new package doesn't have any content providers
2882 // that conflict with existing packages. Only do this if the
2883 // package isn't already installed, since we don't want to break
2884 // things that are installed.
2885 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2886 int N = pkg.providers.size();
2887 int i;
2888 for (i=0; i<N; i++) {
2889 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08002890 if (p.info.authority != null) {
2891 String names[] = p.info.authority.split(";");
2892 for (int j = 0; j < names.length; j++) {
2893 if (mProviders.containsKey(names[j])) {
2894 PackageParser.Provider other = mProviders.get(names[j]);
2895 Log.w(TAG, "Can't install because provider name " + names[j] +
2896 " (in package " + pkg.applicationInfo.packageName +
2897 ") is already used by "
2898 + ((other != null && other.getComponentName() != null)
2899 ? other.getComponentName().getPackageName() : "?"));
2900 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2901 return null;
2902 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002903 }
2904 }
2905 }
2906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 }
2908
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002909 final String pkgName = pkg.packageName;
2910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002911 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002912 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002914 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 if (ret != 0) {
2916 String msg = "System package " + pkg.packageName
2917 + " could not have data directory erased after signature change.";
2918 reportSettingsProblem(Log.WARN, msg);
2919 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2920 return null;
2921 }
2922 }
2923 Log.w(TAG, "System package " + pkg.packageName
2924 + " signature changed: existing data removed.");
2925 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2926 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002927
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002928 if (pkg.mAdoptPermissions != null) {
2929 // This package wants to adopt ownership of permissions from
2930 // another package.
2931 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2932 String origName = pkg.mAdoptPermissions.get(i);
2933 PackageSetting orig = mSettings.peekPackageLP(origName);
2934 if (orig != null) {
2935 if (verifyPackageUpdate(orig, pkg)) {
2936 Log.i(TAG, "Adopting permissions from "
2937 + origName + " to " + pkg.packageName);
2938 mSettings.transferPermissions(origName, pkg.packageName);
2939 }
2940 }
2941 }
2942 }
2943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 long scanFileTime = scanFile.lastModified();
2945 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2946 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2947 pkg.applicationInfo.processName = fixProcessName(
2948 pkg.applicationInfo.packageName,
2949 pkg.applicationInfo.processName,
2950 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002951
2952 File dataPath;
2953 if (mPlatformPackage == pkg) {
2954 // The system package is special.
2955 dataPath = new File (Environment.getDataDirectory(), "system");
2956 pkg.applicationInfo.dataDir = dataPath.getPath();
2957 } else {
2958 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002959 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002960 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002961
2962 boolean uidError = false;
2963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002964 if (dataPath.exists()) {
2965 mOutPermissions[1] = 0;
2966 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2967 if (mOutPermissions[1] == pkg.applicationInfo.uid
2968 || !Process.supportsProcesses()) {
2969 pkg.applicationInfo.dataDir = dataPath.getPath();
2970 } else {
2971 boolean recovered = false;
2972 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2973 // If this is a system app, we can at least delete its
2974 // current data so the application will still work.
2975 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002976 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002977 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 // Old data gone!
2979 String msg = "System package " + pkg.packageName
2980 + " has changed from uid: "
2981 + mOutPermissions[1] + " to "
2982 + pkg.applicationInfo.uid + "; old data erased";
2983 reportSettingsProblem(Log.WARN, msg);
2984 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002987 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988 pkg.applicationInfo.uid);
2989 if (ret == -1) {
2990 // Ack should not happen!
2991 msg = "System package " + pkg.packageName
2992 + " could not have data directory re-created after delete.";
2993 reportSettingsProblem(Log.WARN, msg);
2994 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2995 return null;
2996 }
2997 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002998 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002999 if (!recovered) {
3000 mHasSystemUidErrors = true;
3001 }
3002 }
3003 if (!recovered) {
3004 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3005 + pkg.applicationInfo.uid + "/fs_"
3006 + mOutPermissions[1];
3007 String msg = "Package " + pkg.packageName
3008 + " has mismatched uid: "
3009 + mOutPermissions[1] + " on disk, "
3010 + pkg.applicationInfo.uid + " in settings";
3011 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003012 mSettings.mReadMessages.append(msg);
3013 mSettings.mReadMessages.append('\n');
3014 uidError = true;
3015 if (!pkgSetting.uidError) {
3016 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003018 }
3019 }
3020 }
3021 pkg.applicationInfo.dataDir = dataPath.getPath();
3022 } else {
3023 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3024 Log.v(TAG, "Want this data dir: " + dataPath);
3025 //invoke installer to do the actual installation
3026 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003027 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003028 pkg.applicationInfo.uid);
3029 if(ret < 0) {
3030 // Error from installer
3031 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3032 return null;
3033 }
3034 } else {
3035 dataPath.mkdirs();
3036 if (dataPath.exists()) {
3037 FileUtils.setPermissions(
3038 dataPath.toString(),
3039 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3040 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3041 }
3042 }
3043 if (dataPath.exists()) {
3044 pkg.applicationInfo.dataDir = dataPath.getPath();
3045 } else {
3046 Log.w(TAG, "Unable to create data directory: " + dataPath);
3047 pkg.applicationInfo.dataDir = null;
3048 }
3049 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003050
3051 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003052 }
3053
3054 // Perform shared library installation and dex validation and
3055 // optimization, if this is not a system app.
3056 if (mInstaller != null) {
3057 String path = scanFile.getPath();
3058 if (scanFileNewer) {
3059 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003060 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3061 if (err != PackageManager.INSTALL_SUCCEEDED) {
3062 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003063 return null;
3064 }
3065 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003066 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003067
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003068 if ((scanMode&SCAN_NO_DEX) == 0) {
3069 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3071 return null;
3072 }
3073 }
3074 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076 if (mFactoryTest && pkg.requestedPermissions.contains(
3077 android.Manifest.permission.FACTORY_TEST)) {
3078 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3079 }
3080
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003081 // Request the ActivityManager to kill the process(only for existing packages)
3082 // so that we do not end up in a confused state while the user is still using the older
3083 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003084 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003085 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003086 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003087 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003089 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003090 // We don't expect installation to fail beyond this point,
3091 if ((scanMode&SCAN_MONITOR) != 0) {
3092 mAppDirs.put(pkg.mPath, pkg);
3093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003094 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003095 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003096 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003097 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003098 // Make sure we don't accidentally delete its data.
3099 mSettings.mPackagesToBeCleaned.remove(pkgName);
3100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003101 int N = pkg.providers.size();
3102 StringBuilder r = null;
3103 int i;
3104 for (i=0; i<N; i++) {
3105 PackageParser.Provider p = pkg.providers.get(i);
3106 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3107 p.info.processName, pkg.applicationInfo.uid);
3108 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3109 p.info.name), p);
3110 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003111 if (p.info.authority != null) {
3112 String names[] = p.info.authority.split(";");
3113 p.info.authority = null;
3114 for (int j = 0; j < names.length; j++) {
3115 if (j == 1 && p.syncable) {
3116 // We only want the first authority for a provider to possibly be
3117 // syncable, so if we already added this provider using a different
3118 // authority clear the syncable flag. We copy the provider before
3119 // changing it because the mProviders object contains a reference
3120 // to a provider that we don't want to change.
3121 // Only do this for the second authority since the resulting provider
3122 // object can be the same for all future authorities for this provider.
3123 p = new PackageParser.Provider(p);
3124 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003126 if (!mProviders.containsKey(names[j])) {
3127 mProviders.put(names[j], p);
3128 if (p.info.authority == null) {
3129 p.info.authority = names[j];
3130 } else {
3131 p.info.authority = p.info.authority + ";" + names[j];
3132 }
3133 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3134 Log.d(TAG, "Registered content provider: " + names[j] +
3135 ", className = " + p.info.name +
3136 ", isSyncable = " + p.info.isSyncable);
3137 } else {
3138 PackageParser.Provider other = mProviders.get(names[j]);
3139 Log.w(TAG, "Skipping provider name " + names[j] +
3140 " (in package " + pkg.applicationInfo.packageName +
3141 "): name already used by "
3142 + ((other != null && other.getComponentName() != null)
3143 ? other.getComponentName().getPackageName() : "?"));
3144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145 }
3146 }
3147 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3148 if (r == null) {
3149 r = new StringBuilder(256);
3150 } else {
3151 r.append(' ');
3152 }
3153 r.append(p.info.name);
3154 }
3155 }
3156 if (r != null) {
3157 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3158 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003160 N = pkg.services.size();
3161 r = null;
3162 for (i=0; i<N; i++) {
3163 PackageParser.Service s = pkg.services.get(i);
3164 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3165 s.info.processName, pkg.applicationInfo.uid);
3166 mServices.addService(s);
3167 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3168 if (r == null) {
3169 r = new StringBuilder(256);
3170 } else {
3171 r.append(' ');
3172 }
3173 r.append(s.info.name);
3174 }
3175 }
3176 if (r != null) {
3177 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3178 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 N = pkg.receivers.size();
3181 r = null;
3182 for (i=0; i<N; i++) {
3183 PackageParser.Activity a = pkg.receivers.get(i);
3184 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3185 a.info.processName, pkg.applicationInfo.uid);
3186 mReceivers.addActivity(a, "receiver");
3187 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3188 if (r == null) {
3189 r = new StringBuilder(256);
3190 } else {
3191 r.append(' ');
3192 }
3193 r.append(a.info.name);
3194 }
3195 }
3196 if (r != null) {
3197 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3198 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003200 N = pkg.activities.size();
3201 r = null;
3202 for (i=0; i<N; i++) {
3203 PackageParser.Activity a = pkg.activities.get(i);
3204 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3205 a.info.processName, pkg.applicationInfo.uid);
3206 mActivities.addActivity(a, "activity");
3207 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3208 if (r == null) {
3209 r = new StringBuilder(256);
3210 } else {
3211 r.append(' ');
3212 }
3213 r.append(a.info.name);
3214 }
3215 }
3216 if (r != null) {
3217 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3218 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 N = pkg.permissionGroups.size();
3221 r = null;
3222 for (i=0; i<N; i++) {
3223 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3224 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3225 if (cur == null) {
3226 mPermissionGroups.put(pg.info.name, pg);
3227 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3228 if (r == null) {
3229 r = new StringBuilder(256);
3230 } else {
3231 r.append(' ');
3232 }
3233 r.append(pg.info.name);
3234 }
3235 } else {
3236 Log.w(TAG, "Permission group " + pg.info.name + " from package "
3237 + pg.info.packageName + " ignored: original from "
3238 + cur.info.packageName);
3239 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3240 if (r == null) {
3241 r = new StringBuilder(256);
3242 } else {
3243 r.append(' ');
3244 }
3245 r.append("DUP:");
3246 r.append(pg.info.name);
3247 }
3248 }
3249 }
3250 if (r != null) {
3251 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3252 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 N = pkg.permissions.size();
3255 r = null;
3256 for (i=0; i<N; i++) {
3257 PackageParser.Permission p = pkg.permissions.get(i);
3258 HashMap<String, BasePermission> permissionMap =
3259 p.tree ? mSettings.mPermissionTrees
3260 : mSettings.mPermissions;
3261 p.group = mPermissionGroups.get(p.info.group);
3262 if (p.info.group == null || p.group != null) {
3263 BasePermission bp = permissionMap.get(p.info.name);
3264 if (bp == null) {
3265 bp = new BasePermission(p.info.name, p.info.packageName,
3266 BasePermission.TYPE_NORMAL);
3267 permissionMap.put(p.info.name, bp);
3268 }
3269 if (bp.perm == null) {
3270 if (bp.sourcePackage == null
3271 || bp.sourcePackage.equals(p.info.packageName)) {
3272 BasePermission tree = findPermissionTreeLP(p.info.name);
3273 if (tree == null
3274 || tree.sourcePackage.equals(p.info.packageName)) {
3275 bp.perm = p;
3276 bp.uid = pkg.applicationInfo.uid;
3277 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3278 if (r == null) {
3279 r = new StringBuilder(256);
3280 } else {
3281 r.append(' ');
3282 }
3283 r.append(p.info.name);
3284 }
3285 } else {
3286 Log.w(TAG, "Permission " + p.info.name + " from package "
3287 + p.info.packageName + " ignored: base tree "
3288 + tree.name + " is from package "
3289 + tree.sourcePackage);
3290 }
3291 } else {
3292 Log.w(TAG, "Permission " + p.info.name + " from package "
3293 + p.info.packageName + " ignored: original from "
3294 + bp.sourcePackage);
3295 }
3296 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3297 if (r == null) {
3298 r = new StringBuilder(256);
3299 } else {
3300 r.append(' ');
3301 }
3302 r.append("DUP:");
3303 r.append(p.info.name);
3304 }
3305 } else {
3306 Log.w(TAG, "Permission " + p.info.name + " from package "
3307 + p.info.packageName + " ignored: no group "
3308 + p.group);
3309 }
3310 }
3311 if (r != null) {
3312 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3313 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 N = pkg.instrumentation.size();
3316 r = null;
3317 for (i=0; i<N; i++) {
3318 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3319 a.info.packageName = pkg.applicationInfo.packageName;
3320 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3321 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3322 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003323 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3325 if (r == null) {
3326 r = new StringBuilder(256);
3327 } else {
3328 r.append(' ');
3329 }
3330 r.append(a.info.name);
3331 }
3332 }
3333 if (r != null) {
3334 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3335 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003336
Dianne Hackborn854060af2009-07-09 18:14:31 -07003337 if (pkg.protectedBroadcasts != null) {
3338 N = pkg.protectedBroadcasts.size();
3339 for (i=0; i<N; i++) {
3340 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3341 }
3342 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 pkgSetting.setTimeStamp(scanFileTime);
3345 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003347 return pkg;
3348 }
3349
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003350 private void killApplication(String pkgName, int uid) {
3351 // Request the ActivityManager to kill the process(only for existing packages)
3352 // so that we do not end up in a confused state while the user is still using the older
3353 // version of the application while the new one gets installed.
3354 IActivityManager am = ActivityManagerNative.getDefault();
3355 if (am != null) {
3356 try {
3357 am.killApplicationWithUid(pkgName, uid);
3358 } catch (RemoteException e) {
3359 }
3360 }
3361 }
3362
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003363 // The following constants are returned by cachePackageSharedLibsForAbiLI
3364 // to indicate if native shared libraries were found in the package.
3365 // Values are:
3366 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3367 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3368 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3369 // in package (and not installed)
3370 //
3371 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3372 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3373 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003375 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3376 // and automatically copy them to /data/data/<appname>/lib if present.
3377 //
3378 // NOTE: this method may throw an IOException if the library cannot
3379 // be copied to its final destination, e.g. if there isn't enough
3380 // room left on the data partition, or a ZipException if the package
3381 // file is malformed.
3382 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003383 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3384 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003385 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3386 final String apkLib = "lib/";
3387 final int apkLibLen = apkLib.length();
3388 final int cpuAbiLen = cpuAbi.length();
3389 final String libPrefix = "lib";
3390 final int libPrefixLen = libPrefix.length();
3391 final String libSuffix = ".so";
3392 final int libSuffixLen = libSuffix.length();
3393 boolean hasNativeLibraries = false;
3394 boolean installedNativeLibraries = false;
3395
3396 // the minimum length of a valid native shared library of the form
3397 // lib/<something>/lib<name>.so.
3398 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3399
3400 ZipFile zipFile = new ZipFile(scanFile);
3401 Enumeration<ZipEntry> entries =
3402 (Enumeration<ZipEntry>) zipFile.entries();
3403
3404 while (entries.hasMoreElements()) {
3405 ZipEntry entry = entries.nextElement();
3406 // skip directories
3407 if (entry.isDirectory()) {
3408 continue;
3409 }
3410 String entryName = entry.getName();
3411
3412 // check that the entry looks like lib/<something>/lib<name>.so
3413 // here, but don't check the ABI just yet.
3414 //
3415 // - must be sufficiently long
3416 // - must end with libSuffix, i.e. ".so"
3417 // - must start with apkLib, i.e. "lib/"
3418 if (entryName.length() < minEntryLen ||
3419 !entryName.endsWith(libSuffix) ||
3420 !entryName.startsWith(apkLib) ) {
3421 continue;
3422 }
3423
3424 // file name must start with libPrefix, i.e. "lib"
3425 int lastSlash = entryName.lastIndexOf('/');
3426
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003427 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003428 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3429 continue;
3430 }
3431
3432 hasNativeLibraries = true;
3433
3434 // check the cpuAbi now, between lib/ and /lib<name>.so
3435 //
3436 if (lastSlash != apkLibLen + cpuAbiLen ||
3437 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3438 continue;
3439
3440 // extract the library file name, ensure it doesn't contain
3441 // weird characters. we're guaranteed here that it doesn't contain
3442 // a directory separator though.
3443 String libFileName = entryName.substring(lastSlash+1);
3444 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3445 continue;
3446 }
3447
3448 installedNativeLibraries = true;
3449
3450 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3451 File.separator + libFileName;
3452 File sharedLibraryFile = new File(sharedLibraryFilePath);
3453 if (! sharedLibraryFile.exists() ||
3454 sharedLibraryFile.length() != entry.getSize() ||
3455 sharedLibraryFile.lastModified() != entry.getTime()) {
3456 if (Config.LOGD) {
3457 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003459 if (mInstaller == null) {
3460 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003461 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003462 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003463 sharedLibraryFile);
3464 }
3465 }
3466 if (!hasNativeLibraries)
3467 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3468
3469 if (!installedNativeLibraries)
3470 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3471
3472 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3473 }
3474
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003475 // Find the gdbserver executable program in a package at
3476 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3477 //
3478 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3479 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3480 //
3481 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3482 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3483 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3484 final String GDBSERVER = "gdbserver";
3485 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3486
3487 ZipFile zipFile = new ZipFile(scanFile);
3488 Enumeration<ZipEntry> entries =
3489 (Enumeration<ZipEntry>) zipFile.entries();
3490
3491 while (entries.hasMoreElements()) {
3492 ZipEntry entry = entries.nextElement();
3493 // skip directories
3494 if (entry.isDirectory()) {
3495 continue;
3496 }
3497 String entryName = entry.getName();
3498
3499 if (!entryName.equals(apkGdbServerPath)) {
3500 continue;
3501 }
3502
3503 String installGdbServerPath = installGdbServerDir.getPath() +
3504 "/" + GDBSERVER;
3505 File installGdbServerFile = new File(installGdbServerPath);
3506 if (! installGdbServerFile.exists() ||
3507 installGdbServerFile.length() != entry.getSize() ||
3508 installGdbServerFile.lastModified() != entry.getTime()) {
3509 if (Config.LOGD) {
3510 Log.d(TAG, "Caching gdbserver " + entry.getName());
3511 }
3512 if (mInstaller == null) {
3513 installGdbServerDir.mkdir();
3514 }
3515 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3516 installGdbServerFile);
3517 }
3518 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3519 }
3520 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3521 }
3522
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003523 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3524 // and copy them to /data/data/<appname>/lib.
3525 //
3526 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3527 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3528 // one if ro.product.cpu.abi2 is defined.
3529 //
3530 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3531 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003532 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003533 try {
3534 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3535
3536 // some architectures are capable of supporting several CPU ABIs
3537 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3538 // this is indicated by the definition of the ro.product.cpu.abi2
3539 // system property.
3540 //
3541 // only scan the package twice in case of ABI mismatch
3542 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003543 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003544 if (cpuAbi2 != null) {
3545 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003546 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003547
3548 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
3549 Log.w(TAG,"Native ABI mismatch from package file");
3550 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003552
3553 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3554 cpuAbi = cpuAbi2;
3555 }
3556 }
3557
3558 // for debuggable packages, also extract gdbserver from lib/<abi>
3559 // into /data/data/<appname>/lib too.
3560 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3561 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3562 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3563 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3564 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003567 } catch (ZipException e) {
3568 Log.w(TAG, "Failed to extract data from package file", e);
3569 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003570 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07003571 Log.w(TAG, "Failed to cache package shared libs", e);
3572 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003573 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003574 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003575 }
3576
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003577 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003578 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003579 File binaryDir,
3580 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003581 InputStream inputStream = zipFile.getInputStream(entry);
3582 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003583 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003584 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003585 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003586 // now need to be left as world readable and owned by the system.
3587 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3588 ! tempFile.setLastModified(entry.getTime()) ||
3589 FileUtils.setPermissions(tempFilePath,
3590 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003591 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003592 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003593 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003594 // Failed to properly write file.
3595 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003596 throw new IOException("Couldn't create cached binary "
3597 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003598 }
3599 } finally {
3600 inputStream.close();
3601 }
3602 }
3603
3604 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3605 if (chatty && Config.LOGD) Log.d(
3606 TAG, "Removing package " + pkg.applicationInfo.packageName );
3607
3608 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003609 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003611 mPackages.remove(pkg.applicationInfo.packageName);
3612 if (pkg.mPath != null) {
3613 mAppDirs.remove(pkg.mPath);
3614 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003616 PackageSetting ps = (PackageSetting)pkg.mExtras;
3617 if (ps != null && ps.sharedUser != null) {
3618 // XXX don't do this until the data is removed.
3619 if (false) {
3620 ps.sharedUser.packages.remove(ps);
3621 if (ps.sharedUser.packages.size() == 0) {
3622 // Remove.
3623 }
3624 }
3625 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003627 int N = pkg.providers.size();
3628 StringBuilder r = null;
3629 int i;
3630 for (i=0; i<N; i++) {
3631 PackageParser.Provider p = pkg.providers.get(i);
3632 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3633 p.info.name));
3634 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636 /* The is another ContentProvider with this authority when
3637 * this app was installed so this authority is null,
3638 * Ignore it as we don't have to unregister the provider.
3639 */
3640 continue;
3641 }
3642 String names[] = p.info.authority.split(";");
3643 for (int j = 0; j < names.length; j++) {
3644 if (mProviders.get(names[j]) == p) {
3645 mProviders.remove(names[j]);
3646 if (chatty && Config.LOGD) Log.d(
3647 TAG, "Unregistered content provider: " + names[j] +
3648 ", className = " + p.info.name +
3649 ", isSyncable = " + p.info.isSyncable);
3650 }
3651 }
3652 if (chatty) {
3653 if (r == null) {
3654 r = new StringBuilder(256);
3655 } else {
3656 r.append(' ');
3657 }
3658 r.append(p.info.name);
3659 }
3660 }
3661 if (r != null) {
3662 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3663 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003665 N = pkg.services.size();
3666 r = null;
3667 for (i=0; i<N; i++) {
3668 PackageParser.Service s = pkg.services.get(i);
3669 mServices.removeService(s);
3670 if (chatty) {
3671 if (r == null) {
3672 r = new StringBuilder(256);
3673 } else {
3674 r.append(' ');
3675 }
3676 r.append(s.info.name);
3677 }
3678 }
3679 if (r != null) {
3680 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3681 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 N = pkg.receivers.size();
3684 r = null;
3685 for (i=0; i<N; i++) {
3686 PackageParser.Activity a = pkg.receivers.get(i);
3687 mReceivers.removeActivity(a, "receiver");
3688 if (chatty) {
3689 if (r == null) {
3690 r = new StringBuilder(256);
3691 } else {
3692 r.append(' ');
3693 }
3694 r.append(a.info.name);
3695 }
3696 }
3697 if (r != null) {
3698 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3699 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003701 N = pkg.activities.size();
3702 r = null;
3703 for (i=0; i<N; i++) {
3704 PackageParser.Activity a = pkg.activities.get(i);
3705 mActivities.removeActivity(a, "activity");
3706 if (chatty) {
3707 if (r == null) {
3708 r = new StringBuilder(256);
3709 } else {
3710 r.append(' ');
3711 }
3712 r.append(a.info.name);
3713 }
3714 }
3715 if (r != null) {
3716 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3717 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003719 N = pkg.permissions.size();
3720 r = null;
3721 for (i=0; i<N; i++) {
3722 PackageParser.Permission p = pkg.permissions.get(i);
3723 boolean tree = false;
3724 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3725 if (bp == null) {
3726 tree = true;
3727 bp = mSettings.mPermissionTrees.get(p.info.name);
3728 }
3729 if (bp != null && bp.perm == p) {
3730 if (bp.type != BasePermission.TYPE_BUILTIN) {
3731 if (tree) {
3732 mSettings.mPermissionTrees.remove(p.info.name);
3733 } else {
3734 mSettings.mPermissions.remove(p.info.name);
3735 }
3736 } else {
3737 bp.perm = null;
3738 }
3739 if (chatty) {
3740 if (r == null) {
3741 r = new StringBuilder(256);
3742 } else {
3743 r.append(' ');
3744 }
3745 r.append(p.info.name);
3746 }
3747 }
3748 }
3749 if (r != null) {
3750 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3751 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003753 N = pkg.instrumentation.size();
3754 r = null;
3755 for (i=0; i<N; i++) {
3756 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003757 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003758 if (chatty) {
3759 if (r == null) {
3760 r = new StringBuilder(256);
3761 } else {
3762 r.append(' ');
3763 }
3764 r.append(a.info.name);
3765 }
3766 }
3767 if (r != null) {
3768 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3769 }
3770 }
3771 }
3772
3773 private static final boolean isPackageFilename(String name) {
3774 return name != null && name.endsWith(".apk");
3775 }
3776
3777 private void updatePermissionsLP() {
3778 // Make sure there are no dangling permission trees.
3779 Iterator<BasePermission> it = mSettings.mPermissionTrees
3780 .values().iterator();
3781 while (it.hasNext()) {
3782 BasePermission bp = it.next();
3783 if (bp.perm == null) {
3784 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3785 + " from package " + bp.sourcePackage);
3786 it.remove();
3787 }
3788 }
3789
3790 // Make sure all dynamic permissions have been assigned to a package,
3791 // and make sure there are no dangling permissions.
3792 it = mSettings.mPermissions.values().iterator();
3793 while (it.hasNext()) {
3794 BasePermission bp = it.next();
3795 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3796 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3797 + bp.name + " pkg=" + bp.sourcePackage
3798 + " info=" + bp.pendingInfo);
3799 if (bp.perm == null && bp.pendingInfo != null) {
3800 BasePermission tree = findPermissionTreeLP(bp.name);
3801 if (tree != null) {
3802 bp.perm = new PackageParser.Permission(tree.perm.owner,
3803 new PermissionInfo(bp.pendingInfo));
3804 bp.perm.info.packageName = tree.perm.info.packageName;
3805 bp.perm.info.name = bp.name;
3806 bp.uid = tree.uid;
3807 }
3808 }
3809 }
3810 if (bp.perm == null) {
3811 Log.w(TAG, "Removing dangling permission: " + bp.name
3812 + " from package " + bp.sourcePackage);
3813 it.remove();
3814 }
3815 }
3816
3817 // Now update the permissions for all packages, in particular
3818 // replace the granted permissions of the system packages.
3819 for (PackageParser.Package pkg : mPackages.values()) {
3820 grantPermissionsLP(pkg, false);
3821 }
3822 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003824 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3825 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3826 if (ps == null) {
3827 return;
3828 }
3829 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3830 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 if (replace) {
3833 ps.permissionsFixed = false;
3834 if (gp == ps) {
3835 gp.grantedPermissions.clear();
3836 gp.gids = mGlobalGids;
3837 }
3838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003840 if (gp.gids == null) {
3841 gp.gids = mGlobalGids;
3842 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003844 final int N = pkg.requestedPermissions.size();
3845 for (int i=0; i<N; i++) {
3846 String name = pkg.requestedPermissions.get(i);
3847 BasePermission bp = mSettings.mPermissions.get(name);
3848 PackageParser.Permission p = bp != null ? bp.perm : null;
3849 if (false) {
3850 if (gp != ps) {
3851 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3852 + ": " + p);
3853 }
3854 }
3855 if (p != null) {
3856 final String perm = p.info.name;
3857 boolean allowed;
3858 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3859 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3860 allowed = true;
3861 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3862 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003863 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003864 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003865 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 == PackageManager.SIGNATURE_MATCH);
3867 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3868 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3869 // For updated system applications, the signatureOrSystem permission
3870 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003871 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003872 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3873 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3874 if(sysPs.grantedPermissions.contains(perm)) {
3875 allowed = true;
3876 } else {
3877 allowed = false;
3878 }
3879 } else {
3880 allowed = true;
3881 }
3882 }
3883 }
3884 } else {
3885 allowed = false;
3886 }
3887 if (false) {
3888 if (gp != ps) {
3889 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3890 }
3891 }
3892 if (allowed) {
3893 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3894 && ps.permissionsFixed) {
3895 // If this is an existing, non-system package, then
3896 // we can't add any new permissions to it.
3897 if (!gp.loadedPermissions.contains(perm)) {
3898 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003899 // Except... if this is a permission that was added
3900 // to the platform (note: need to only do this when
3901 // updating the platform).
3902 final int NP = PackageParser.NEW_PERMISSIONS.length;
3903 for (int ip=0; ip<NP; ip++) {
3904 final PackageParser.NewPermissionInfo npi
3905 = PackageParser.NEW_PERMISSIONS[ip];
3906 if (npi.name.equals(perm)
3907 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3908 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003909 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003910 + pkg.packageName);
3911 break;
3912 }
3913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003914 }
3915 }
3916 if (allowed) {
3917 if (!gp.grantedPermissions.contains(perm)) {
3918 addedPermission = true;
3919 gp.grantedPermissions.add(perm);
3920 gp.gids = appendInts(gp.gids, bp.gids);
3921 }
3922 } else {
3923 Log.w(TAG, "Not granting permission " + perm
3924 + " to package " + pkg.packageName
3925 + " because it was previously installed without");
3926 }
3927 } else {
3928 Log.w(TAG, "Not granting permission " + perm
3929 + " to package " + pkg.packageName
3930 + " (protectionLevel=" + p.info.protectionLevel
3931 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3932 + ")");
3933 }
3934 } else {
3935 Log.w(TAG, "Unknown permission " + name
3936 + " in package " + pkg.packageName);
3937 }
3938 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003941 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3942 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003943 // This is the first that we have heard about this package, so the
3944 // permissions we have now selected are fixed until explicitly
3945 // changed.
3946 ps.permissionsFixed = true;
3947 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3948 }
3949 }
3950
3951 private final class ActivityIntentResolver
3952 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003953 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003955 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003956 }
3957
Mihai Preda074edef2009-05-18 17:13:31 +02003958 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003960 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003961 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3962 }
3963
Mihai Predaeae850c2009-05-13 10:13:48 +02003964 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3965 ArrayList<PackageParser.Activity> packageActivities) {
3966 if (packageActivities == null) {
3967 return null;
3968 }
3969 mFlags = flags;
3970 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3971 int N = packageActivities.size();
3972 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3973 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003974
3975 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003976 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003977 intentFilters = packageActivities.get(i).intents;
3978 if (intentFilters != null && intentFilters.size() > 0) {
3979 listCut.add(intentFilters);
3980 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003981 }
3982 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3983 }
3984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003985 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003986 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 if (SHOW_INFO || Config.LOGV) Log.v(
3988 TAG, " " + type + " " +
3989 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3990 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3991 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003992 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3994 if (SHOW_INFO || Config.LOGV) {
3995 Log.v(TAG, " IntentFilter:");
3996 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3997 }
3998 if (!intent.debugCheck()) {
3999 Log.w(TAG, "==> For Activity " + a.info.name);
4000 }
4001 addFilter(intent);
4002 }
4003 }
4004
4005 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004006 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007 if (SHOW_INFO || Config.LOGV) Log.v(
4008 TAG, " " + type + " " +
4009 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4010 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4011 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004012 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4014 if (SHOW_INFO || Config.LOGV) {
4015 Log.v(TAG, " IntentFilter:");
4016 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4017 }
4018 removeFilter(intent);
4019 }
4020 }
4021
4022 @Override
4023 protected boolean allowFilterResult(
4024 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4025 ActivityInfo filterAi = filter.activity.info;
4026 for (int i=dest.size()-1; i>=0; i--) {
4027 ActivityInfo destAi = dest.get(i).activityInfo;
4028 if (destAi.name == filterAi.name
4029 && destAi.packageName == filterAi.packageName) {
4030 return false;
4031 }
4032 }
4033 return true;
4034 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004036 @Override
4037 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4038 int match) {
4039 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4040 return null;
4041 }
4042 final PackageParser.Activity activity = info.activity;
4043 if (mSafeMode && (activity.info.applicationInfo.flags
4044 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4045 return null;
4046 }
4047 final ResolveInfo res = new ResolveInfo();
4048 res.activityInfo = PackageParser.generateActivityInfo(activity,
4049 mFlags);
4050 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4051 res.filter = info;
4052 }
4053 res.priority = info.getPriority();
4054 res.preferredOrder = activity.owner.mPreferredOrder;
4055 //System.out.println("Result: " + res.activityInfo.className +
4056 // " = " + res.priority);
4057 res.match = match;
4058 res.isDefault = info.hasDefault;
4059 res.labelRes = info.labelRes;
4060 res.nonLocalizedLabel = info.nonLocalizedLabel;
4061 res.icon = info.icon;
4062 return res;
4063 }
4064
4065 @Override
4066 protected void sortResults(List<ResolveInfo> results) {
4067 Collections.sort(results, mResolvePrioritySorter);
4068 }
4069
4070 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004071 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004072 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004073 out.print(prefix); out.print(
4074 Integer.toHexString(System.identityHashCode(filter.activity)));
4075 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004076 out.println(filter.activity.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004077 }
4078
4079// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4080// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4081// final List<ResolveInfo> retList = Lists.newArrayList();
4082// while (i.hasNext()) {
4083// final ResolveInfo resolveInfo = i.next();
4084// if (isEnabledLP(resolveInfo.activityInfo)) {
4085// retList.add(resolveInfo);
4086// }
4087// }
4088// return retList;
4089// }
4090
4091 // Keys are String (activity class name), values are Activity.
4092 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4093 = new HashMap<ComponentName, PackageParser.Activity>();
4094 private int mFlags;
4095 }
4096
4097 private final class ServiceIntentResolver
4098 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004099 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004100 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004101 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 }
4103
Mihai Preda074edef2009-05-18 17:13:31 +02004104 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004106 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004107 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4108 }
4109
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004110 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4111 ArrayList<PackageParser.Service> packageServices) {
4112 if (packageServices == null) {
4113 return null;
4114 }
4115 mFlags = flags;
4116 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4117 int N = packageServices.size();
4118 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4119 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4120
4121 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4122 for (int i = 0; i < N; ++i) {
4123 intentFilters = packageServices.get(i).intents;
4124 if (intentFilters != null && intentFilters.size() > 0) {
4125 listCut.add(intentFilters);
4126 }
4127 }
4128 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4129 }
4130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004131 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004132 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004133 if (SHOW_INFO || Config.LOGV) Log.v(
4134 TAG, " " + (s.info.nonLocalizedLabel != null
4135 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4136 if (SHOW_INFO || Config.LOGV) Log.v(
4137 TAG, " Class=" + s.info.name);
4138 int NI = s.intents.size();
4139 int j;
4140 for (j=0; j<NI; j++) {
4141 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4142 if (SHOW_INFO || Config.LOGV) {
4143 Log.v(TAG, " IntentFilter:");
4144 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4145 }
4146 if (!intent.debugCheck()) {
4147 Log.w(TAG, "==> For Service " + s.info.name);
4148 }
4149 addFilter(intent);
4150 }
4151 }
4152
4153 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004154 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 if (SHOW_INFO || Config.LOGV) Log.v(
4156 TAG, " " + (s.info.nonLocalizedLabel != null
4157 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4158 if (SHOW_INFO || Config.LOGV) Log.v(
4159 TAG, " Class=" + s.info.name);
4160 int NI = s.intents.size();
4161 int j;
4162 for (j=0; j<NI; j++) {
4163 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4164 if (SHOW_INFO || Config.LOGV) {
4165 Log.v(TAG, " IntentFilter:");
4166 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4167 }
4168 removeFilter(intent);
4169 }
4170 }
4171
4172 @Override
4173 protected boolean allowFilterResult(
4174 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4175 ServiceInfo filterSi = filter.service.info;
4176 for (int i=dest.size()-1; i>=0; i--) {
4177 ServiceInfo destAi = dest.get(i).serviceInfo;
4178 if (destAi.name == filterSi.name
4179 && destAi.packageName == filterSi.packageName) {
4180 return false;
4181 }
4182 }
4183 return true;
4184 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004186 @Override
4187 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4188 int match) {
4189 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4190 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4191 return null;
4192 }
4193 final PackageParser.Service service = info.service;
4194 if (mSafeMode && (service.info.applicationInfo.flags
4195 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4196 return null;
4197 }
4198 final ResolveInfo res = new ResolveInfo();
4199 res.serviceInfo = PackageParser.generateServiceInfo(service,
4200 mFlags);
4201 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4202 res.filter = filter;
4203 }
4204 res.priority = info.getPriority();
4205 res.preferredOrder = service.owner.mPreferredOrder;
4206 //System.out.println("Result: " + res.activityInfo.className +
4207 // " = " + res.priority);
4208 res.match = match;
4209 res.isDefault = info.hasDefault;
4210 res.labelRes = info.labelRes;
4211 res.nonLocalizedLabel = info.nonLocalizedLabel;
4212 res.icon = info.icon;
4213 return res;
4214 }
4215
4216 @Override
4217 protected void sortResults(List<ResolveInfo> results) {
4218 Collections.sort(results, mResolvePrioritySorter);
4219 }
4220
4221 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004222 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004223 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004224 out.print(prefix); out.print(
4225 Integer.toHexString(System.identityHashCode(filter.service)));
4226 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004227 out.println(filter.service.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004228 }
4229
4230// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4231// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4232// final List<ResolveInfo> retList = Lists.newArrayList();
4233// while (i.hasNext()) {
4234// final ResolveInfo resolveInfo = (ResolveInfo) i;
4235// if (isEnabledLP(resolveInfo.serviceInfo)) {
4236// retList.add(resolveInfo);
4237// }
4238// }
4239// return retList;
4240// }
4241
4242 // Keys are String (activity class name), values are Activity.
4243 private final HashMap<ComponentName, PackageParser.Service> mServices
4244 = new HashMap<ComponentName, PackageParser.Service>();
4245 private int mFlags;
4246 };
4247
4248 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4249 new Comparator<ResolveInfo>() {
4250 public int compare(ResolveInfo r1, ResolveInfo r2) {
4251 int v1 = r1.priority;
4252 int v2 = r2.priority;
4253 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4254 if (v1 != v2) {
4255 return (v1 > v2) ? -1 : 1;
4256 }
4257 v1 = r1.preferredOrder;
4258 v2 = r2.preferredOrder;
4259 if (v1 != v2) {
4260 return (v1 > v2) ? -1 : 1;
4261 }
4262 if (r1.isDefault != r2.isDefault) {
4263 return r1.isDefault ? -1 : 1;
4264 }
4265 v1 = r1.match;
4266 v2 = r2.match;
4267 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4268 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4269 }
4270 };
4271
4272 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4273 new Comparator<ProviderInfo>() {
4274 public int compare(ProviderInfo p1, ProviderInfo p2) {
4275 final int v1 = p1.initOrder;
4276 final int v2 = p2.initOrder;
4277 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4278 }
4279 };
4280
4281 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4282 IActivityManager am = ActivityManagerNative.getDefault();
4283 if (am != null) {
4284 try {
4285 final Intent intent = new Intent(action,
4286 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4287 if (extras != null) {
4288 intent.putExtras(extras);
4289 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004290 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 am.broadcastIntent(
4292 null, intent,
4293 null, null, 0, null, null, null, false, false);
4294 } catch (RemoteException ex) {
4295 }
4296 }
4297 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004298
4299 public String nextPackageToClean(String lastPackage) {
4300 synchronized (mPackages) {
4301 if (!mMediaMounted) {
4302 // If the external storage is no longer mounted at this point,
4303 // the caller may not have been able to delete all of this
4304 // packages files and can not delete any more. Bail.
4305 return null;
4306 }
4307 if (lastPackage != null) {
4308 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4309 }
4310 return mSettings.mPackagesToBeCleaned.size() > 0
4311 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4312 }
4313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004314
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004315 void schedulePackageCleaning(String packageName) {
4316 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4317 }
4318
4319 void startCleaningPackages() {
4320 synchronized (mPackages) {
4321 if (!mMediaMounted) {
4322 return;
4323 }
4324 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4325 return;
4326 }
4327 }
4328 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4329 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4330 IActivityManager am = ActivityManagerNative.getDefault();
4331 if (am != null) {
4332 try {
4333 am.startService(null, intent, null);
4334 } catch (RemoteException e) {
4335 }
4336 }
4337 }
4338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004339 private final class AppDirObserver extends FileObserver {
4340 public AppDirObserver(String path, int mask, boolean isrom) {
4341 super(path, mask);
4342 mRootDir = path;
4343 mIsRom = isrom;
4344 }
4345
4346 public void onEvent(int event, String path) {
4347 String removedPackage = null;
4348 int removedUid = -1;
4349 String addedPackage = null;
4350 int addedUid = -1;
4351
4352 synchronized (mInstallLock) {
4353 String fullPathStr = null;
4354 File fullPath = null;
4355 if (path != null) {
4356 fullPath = new File(mRootDir, path);
4357 fullPathStr = fullPath.getPath();
4358 }
4359
4360 if (Config.LOGV) Log.v(
4361 TAG, "File " + fullPathStr + " changed: "
4362 + Integer.toHexString(event));
4363
4364 if (!isPackageFilename(path)) {
4365 if (Config.LOGV) Log.v(
4366 TAG, "Ignoring change of non-package file: " + fullPathStr);
4367 return;
4368 }
4369
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004370 // Ignore packages that are being installed or
4371 // have just been installed.
4372 if (ignoreCodePath(fullPathStr)) {
4373 return;
4374 }
4375 PackageParser.Package p = null;
4376 synchronized (mPackages) {
4377 p = mAppDirs.get(fullPathStr);
4378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004379 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004380 if (p != null) {
4381 removePackageLI(p, true);
4382 removedPackage = p.applicationInfo.packageName;
4383 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004384 }
4385 }
4386
4387 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004388 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004389 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004390 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
4391 PackageParser.PARSE_CHATTY |
4392 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004393 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004394 if (p != null) {
4395 synchronized (mPackages) {
4396 grantPermissionsLP(p, false);
4397 }
4398 addedPackage = p.applicationInfo.packageName;
4399 addedUid = p.applicationInfo.uid;
4400 }
4401 }
4402 }
4403
4404 synchronized (mPackages) {
4405 mSettings.writeLP();
4406 }
4407 }
4408
4409 if (removedPackage != null) {
4410 Bundle extras = new Bundle(1);
4411 extras.putInt(Intent.EXTRA_UID, removedUid);
4412 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4413 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4414 }
4415 if (addedPackage != null) {
4416 Bundle extras = new Bundle(1);
4417 extras.putInt(Intent.EXTRA_UID, addedUid);
4418 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4419 }
4420 }
4421
4422 private final String mRootDir;
4423 private final boolean mIsRom;
4424 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004426 /* Called when a downloaded package installation has been confirmed by the user */
4427 public void installPackage(
4428 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004429 installPackage(packageURI, observer, flags, null);
4430 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004431
Jacek Surazski65e13172009-04-28 15:26:38 +02004432 /* Called when a downloaded package installation has been confirmed by the user */
4433 public void installPackage(
4434 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4435 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004436 mContext.enforceCallingOrSelfPermission(
4437 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004438
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004439 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004440 msg.obj = new InstallParams(packageURI, observer, flags,
4441 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004442 mHandler.sendMessage(msg);
4443 }
4444
Christopher Tate1bb69062010-02-19 17:02:12 -08004445 public void finishPackageInstall(int token) {
4446 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4447 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4448 mHandler.sendMessage(msg);
4449 }
4450
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004451 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004452 // Queue up an async operation since the package installation may take a little while.
4453 mHandler.post(new Runnable() {
4454 public void run() {
4455 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004456 // Result object to be returned
4457 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004458 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004459 res.uid = -1;
4460 res.pkg = null;
4461 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004462 args.doPreInstall(res.returnCode);
4463 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004464 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004465 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004466 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004467 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004468 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004469
4470 // A restore should be performed at this point if (a) the install
4471 // succeeded, (b) the operation is not an update, and (c) the new
4472 // package has a backupAgent defined.
4473 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004474 boolean doRestore = (!update
4475 && res.pkg != null
4476 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004477
4478 // Set up the post-install work request bookkeeping. This will be used
4479 // and cleaned up by the post-install event handling regardless of whether
4480 // there's a restore pass performed. Token values are >= 1.
4481 int token;
4482 if (mNextInstallToken < 0) mNextInstallToken = 1;
4483 token = mNextInstallToken++;
4484
4485 PostInstallData data = new PostInstallData(args, res);
4486 mRunningInstalls.put(token, data);
4487 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4488
4489 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4490 // Pass responsibility to the Backup Manager. It will perform a
4491 // restore if appropriate, then pass responsibility back to the
4492 // Package Manager to run the post-install observer callbacks
4493 // and broadcasts.
4494 IBackupManager bm = IBackupManager.Stub.asInterface(
4495 ServiceManager.getService(Context.BACKUP_SERVICE));
4496 if (bm != null) {
4497 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4498 + " to BM for possible restore");
4499 try {
4500 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4501 } catch (RemoteException e) {
4502 // can't happen; the backup manager is local
4503 } catch (Exception e) {
4504 Log.e(TAG, "Exception trying to enqueue restore", e);
4505 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004506 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004507 } else {
4508 Log.e(TAG, "Backup Manager not found!");
4509 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004511 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004512
4513 if (!doRestore) {
4514 // No restore possible, or the Backup Manager was mysteriously not
4515 // available -- just fire the post-install work request directly.
4516 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4517 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4518 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520 }
4521 });
4522 }
4523
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004524 abstract class HandlerParams {
4525 final static int MAX_RETRIES = 4;
4526 int retry = 0;
4527 final void startCopy() {
4528 try {
4529 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4530 retry++;
4531 if (retry > MAX_RETRIES) {
4532 Log.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
4533 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4534 handleServiceError();
4535 return;
4536 } else {
4537 handleStartCopy();
4538 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4539 mHandler.sendEmptyMessage(MCS_UNBIND);
4540 }
4541 } catch (RemoteException e) {
4542 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4543 mHandler.sendEmptyMessage(MCS_RECONNECT);
4544 }
4545 handleReturnCode();
4546 }
4547
4548 final void serviceError() {
4549 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4550 handleServiceError();
4551 handleReturnCode();
4552 }
4553 abstract void handleStartCopy() throws RemoteException;
4554 abstract void handleServiceError();
4555 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004556 }
4557
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004558 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004559 final IPackageInstallObserver observer;
4560 int flags;
4561 final Uri packageURI;
4562 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004563 private InstallArgs mArgs;
4564 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004565 InstallParams(Uri packageURI,
4566 IPackageInstallObserver observer, int flags,
4567 String installerPackageName) {
4568 this.packageURI = packageURI;
4569 this.flags = flags;
4570 this.observer = observer;
4571 this.installerPackageName = installerPackageName;
4572 }
4573
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004574 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4575 String packageName = pkgLite.packageName;
4576 int installLocation = pkgLite.installLocation;
4577 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4578 synchronized (mPackages) {
4579 PackageParser.Package pkg = mPackages.get(packageName);
4580 if (pkg != null) {
4581 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4582 // Check for updated system application.
4583 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4584 if (onSd) {
4585 Log.w(TAG, "Cannot install update to system app on sdcard");
4586 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4587 }
4588 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4589 } else {
4590 // When replacing apps make sure we honour
4591 // the existing app location if not overwritten by other options
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08004592 boolean prevOnSd = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004593 if (onSd) {
4594 // Install flag overrides everything.
4595 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4596 }
4597 // If current upgrade does not specify install location.
4598 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4599 // Application explicitly specified internal.
4600 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4601 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4602 // App explictly prefers external. Let policy decide
4603 } else if (installLocation == PackageInfo.INSTALL_LOCATION_AUTO) {
4604 // Prefer previous location
4605 return prevOnSd ? PackageHelper.RECOMMEND_INSTALL_EXTERNAL:
4606 PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4607 }
4608 }
4609 } else {
4610 // Invalid install. Return error code
4611 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4612 }
4613 }
4614 }
4615 // All the special cases have been taken care of.
4616 // Return result based on recommended install location.
4617 if (onSd) {
4618 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4619 }
4620 return pkgLite.recommendedInstallLocation;
4621 }
4622
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004623 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004624 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004625 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4626 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004627 // Dont need to invoke getInstallLocation for forward locked apps.
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004628 if (fwdLocked && onSd) {
4629 Log.w(TAG, "Cannot install fwd locked apps on sdcard");
4630 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004631 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004632 // Remote call to find out default install location
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004633 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI);
4634 int loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004635 // Use install location to create InstallArgs and temporary
4636 // install location
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004637 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4638 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4639 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4640 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4641 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004642 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4643 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4644 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
4645 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004646 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004647 if ((flags & PackageManager.INSTALL_EXTERNAL) == 0){
4648 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4649 // Set the flag to install on external media.
4650 flags |= PackageManager.INSTALL_EXTERNAL;
4651 } else {
4652 // Make sure the flag for installing on external
4653 // media is unset
4654 flags &= ~PackageManager.INSTALL_EXTERNAL;
4655 }
4656 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004657 }
4658 }
4659 // Create the file args now.
4660 mArgs = createInstallArgs(this);
4661 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4662 // Create copy only if we are not in an erroneous state.
4663 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004664 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004665 }
4666 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004667 }
4668
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004669 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004670 void handleReturnCode() {
4671 processPendingInstall(mArgs, mRet);
4672 }
4673
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004674 @Override
4675 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004676 mArgs = createInstallArgs(this);
4677 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004678 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004679 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004680
4681 /*
4682 * Utility class used in movePackage api.
4683 * srcArgs and targetArgs are not set for invalid flags and make
4684 * sure to do null checks when invoking methods on them.
4685 * We probably want to return ErrorPrams for both failed installs
4686 * and moves.
4687 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004688 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004689 final IPackageMoveObserver observer;
4690 final int flags;
4691 final String packageName;
4692 final InstallArgs srcArgs;
4693 final InstallArgs targetArgs;
4694 int mRet;
4695 MoveParams(InstallArgs srcArgs,
4696 IPackageMoveObserver observer,
4697 int flags, String packageName) {
4698 this.srcArgs = srcArgs;
4699 this.observer = observer;
4700 this.flags = flags;
4701 this.packageName = packageName;
4702 if (srcArgs != null) {
4703 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4704 targetArgs = createInstallArgs(packageUri, flags, packageName);
4705 } else {
4706 targetArgs = null;
4707 }
4708 }
4709
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004710 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004711 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004712 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004713 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004714 if (DEBUG_SD_INSTALL) {
4715 StringBuilder builder = new StringBuilder();
4716 if (srcArgs != null) {
4717 builder.append("src: ");
4718 builder.append(srcArgs.getCodePath());
4719 }
4720 if (targetArgs != null) {
4721 builder.append(" target : ");
4722 builder.append(targetArgs.getCodePath());
4723 }
4724 Log.i(TAG, "Posting move MCS_UNBIND for " + builder.toString());
4725 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004726 }
4727
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004728 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004729 void handleReturnCode() {
4730 targetArgs.doPostInstall(mRet);
4731 // TODO invoke pending move
4732 processPendingMove(this, mRet);
4733 }
4734
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004735 @Override
4736 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004737 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004738 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004739 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004740
4741 private InstallArgs createInstallArgs(InstallParams params) {
4742 if (installOnSd(params.flags)) {
4743 return new SdInstallArgs(params);
4744 } else {
4745 return new FileInstallArgs(params);
4746 }
4747 }
4748
4749 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4750 if (installOnSd(flags)) {
4751 return new SdInstallArgs(fullCodePath, fullResourcePath);
4752 } else {
4753 return new FileInstallArgs(fullCodePath, fullResourcePath);
4754 }
4755 }
4756
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004757 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4758 if (installOnSd(flags)) {
4759 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4760 return new SdInstallArgs(packageURI, cid);
4761 } else {
4762 return new FileInstallArgs(packageURI, pkgName);
4763 }
4764 }
4765
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004766 static abstract class InstallArgs {
4767 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004768 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004769 final int flags;
4770 final Uri packageURI;
4771 final String installerPackageName;
4772
4773 InstallArgs(Uri packageURI,
4774 IPackageInstallObserver observer, int flags,
4775 String installerPackageName) {
4776 this.packageURI = packageURI;
4777 this.flags = flags;
4778 this.observer = observer;
4779 this.installerPackageName = installerPackageName;
4780 }
4781
4782 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004783 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004784 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004785 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004786 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004787 abstract String getCodePath();
4788 abstract String getResourcePath();
4789 // Need installer lock especially for dex file removal.
4790 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004791 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004792 }
4793
4794 class FileInstallArgs extends InstallArgs {
4795 File installDir;
4796 String codeFileName;
4797 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004798 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004799
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004800 FileInstallArgs(InstallParams params) {
4801 super(params.packageURI, params.observer,
4802 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004803 }
4804
4805 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4806 super(null, null, 0, null);
4807 File codeFile = new File(fullCodePath);
4808 installDir = codeFile.getParentFile();
4809 codeFileName = fullCodePath;
4810 resourceFileName = fullResourcePath;
4811 }
4812
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004813 FileInstallArgs(Uri packageURI, String pkgName) {
4814 super(packageURI, null, 0, null);
4815 boolean fwdLocked = isFwdLocked(flags);
4816 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4817 String apkName = getNextCodePath(null, pkgName, ".apk");
4818 codeFileName = new File(installDir, apkName + ".apk").getPath();
4819 resourceFileName = getResourcePathFromCodePath();
4820 }
4821
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004822 String getCodePath() {
4823 return codeFileName;
4824 }
4825
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004826 void createCopyFile() {
4827 boolean fwdLocked = isFwdLocked(flags);
4828 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4829 codeFileName = createTempPackageFile(installDir).getPath();
4830 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004831 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004832 }
4833
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004834 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004835 if (temp) {
4836 // Generate temp file name
4837 createCopyFile();
4838 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004839 // Get a ParcelFileDescriptor to write to the output file
4840 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004841 if (!created) {
4842 try {
4843 codeFile.createNewFile();
4844 // Set permissions
4845 if (!setPermissions()) {
4846 // Failed setting permissions.
4847 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4848 }
4849 } catch (IOException e) {
4850 Log.w(TAG, "Failed to create file " + codeFile);
4851 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4852 }
4853 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004854 ParcelFileDescriptor out = null;
4855 try {
4856 out = ParcelFileDescriptor.open(codeFile,
4857 ParcelFileDescriptor.MODE_READ_WRITE);
4858 } catch (FileNotFoundException e) {
4859 Log.e(TAG, "Failed to create file descritpor for : " + codeFileName);
4860 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4861 }
4862 // Copy the resource now
4863 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4864 try {
4865 if (imcs.copyResource(packageURI, out)) {
4866 ret = PackageManager.INSTALL_SUCCEEDED;
4867 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004868 } finally {
4869 try { if (out != null) out.close(); } catch (IOException e) {}
4870 }
4871 return ret;
4872 }
4873
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004874 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004875 if (status != PackageManager.INSTALL_SUCCEEDED) {
4876 cleanUp();
4877 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004878 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004879 }
4880
4881 boolean doRename(int status, final String pkgName, String oldCodePath) {
4882 if (status != PackageManager.INSTALL_SUCCEEDED) {
4883 cleanUp();
4884 return false;
4885 } else {
4886 // Rename based on packageName
4887 File codeFile = new File(getCodePath());
4888 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
4889 File desFile = new File(installDir, apkName + ".apk");
4890 if (!codeFile.renameTo(desFile)) {
4891 return false;
4892 }
4893 // Reset paths since the file has been renamed.
4894 codeFileName = desFile.getPath();
4895 resourceFileName = getResourcePathFromCodePath();
4896 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004897 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004898 // Failed setting permissions.
4899 return false;
4900 }
4901 return true;
4902 }
4903 }
4904
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004905 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004906 if (status != PackageManager.INSTALL_SUCCEEDED) {
4907 cleanUp();
4908 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004909 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004910 }
4911
4912 String getResourcePath() {
4913 return resourceFileName;
4914 }
4915
4916 String getResourcePathFromCodePath() {
4917 String codePath = getCodePath();
4918 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4919 String apkNameOnly = getApkName(codePath);
4920 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
4921 } else {
4922 return codePath;
4923 }
4924 }
4925
4926 private boolean cleanUp() {
4927 boolean ret = true;
4928 String sourceDir = getCodePath();
4929 String publicSourceDir = getResourcePath();
4930 if (sourceDir != null) {
4931 File sourceFile = new File(sourceDir);
4932 if (!sourceFile.exists()) {
4933 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4934 ret = false;
4935 }
4936 // Delete application's code and resources
4937 sourceFile.delete();
4938 }
4939 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4940 final File publicSourceFile = new File(publicSourceDir);
4941 if (!publicSourceFile.exists()) {
4942 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4943 }
4944 if (publicSourceFile.exists()) {
4945 publicSourceFile.delete();
4946 }
4947 }
4948 return ret;
4949 }
4950
4951 void cleanUpResourcesLI() {
4952 String sourceDir = getCodePath();
4953 if (cleanUp() && mInstaller != null) {
4954 int retCode = mInstaller.rmdex(sourceDir);
4955 if (retCode < 0) {
4956 Log.w(TAG, "Couldn't remove dex file for package: "
4957 + " at location "
4958 + sourceDir + ", retcode=" + retCode);
4959 // we don't consider this to be a failure of the core package deletion
4960 }
4961 }
4962 }
4963
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004964 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004965 // TODO Do this in a more elegant way later on. for now just a hack
4966 if (!isFwdLocked(flags)) {
4967 final int filePermissions =
4968 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4969 |FileUtils.S_IROTH;
4970 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
4971 if (retCode != 0) {
4972 Log.e(TAG, "Couldn't set new package file permissions for " +
4973 getCodePath()
4974 + ". The return code was: " + retCode);
4975 // TODO Define new internal error
4976 return false;
4977 }
4978 return true;
4979 }
4980 return true;
4981 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004982
4983 boolean doPostDeleteLI(boolean delete) {
4984 cleanUpResourcesLI();
4985 return true;
4986 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004987 }
4988
4989 class SdInstallArgs extends InstallArgs {
4990 String cid;
4991 String cachePath;
4992 static final String RES_FILE_NAME = "pkg.apk";
4993
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004994 SdInstallArgs(InstallParams params) {
4995 super(params.packageURI, params.observer,
4996 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004997 }
4998
4999 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005000 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005001 // Extract cid from fullCodePath
5002 int eidx = fullCodePath.lastIndexOf("/");
5003 String subStr1 = fullCodePath.substring(0, eidx);
5004 int sidx = subStr1.lastIndexOf("/");
5005 cid = subStr1.substring(sidx+1, eidx);
5006 cachePath = subStr1;
5007 }
5008
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005009 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005010 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5011 this.cid = cid;
5012 }
5013
5014 SdInstallArgs(Uri packageURI, String cid) {
5015 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005016 this.cid = cid;
5017 }
5018
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005019 void createCopyFile() {
5020 cid = getTempContainerId();
5021 }
5022
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005023 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005024 if (temp) {
5025 createCopyFile();
5026 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005027 cachePath = imcs.copyResourceToContainer(
5028 packageURI, cid,
5029 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005030 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5031 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005032 }
5033
5034 @Override
5035 String getCodePath() {
5036 return cachePath + "/" + RES_FILE_NAME;
5037 }
5038
5039 @Override
5040 String getResourcePath() {
5041 return cachePath + "/" + RES_FILE_NAME;
5042 }
5043
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005044 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005045 if (status != PackageManager.INSTALL_SUCCEEDED) {
5046 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005047 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005048 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005049 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005050 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005051 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005052 if (cachePath == null) {
5053 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5054 }
5055 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005056 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005057 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005058 }
5059
5060 boolean doRename(int status, final String pkgName,
5061 String oldCodePath) {
5062 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005063 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005064 if (PackageHelper.isContainerMounted(cid)) {
5065 // Unmount the container
5066 if (!PackageHelper.unMountSdDir(cid)) {
5067 Log.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005068 return false;
5069 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005070 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005071 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5072 Log.e(TAG, "Failed to rename " + cid + " to " + newCacheId);
5073 return false;
5074 }
5075 if (!PackageHelper.isContainerMounted(newCacheId)) {
5076 Log.w(TAG, "Mounting container " + newCacheId);
5077 newCachePath = PackageHelper.mountSdDir(newCacheId,
5078 getEncryptKey(), Process.SYSTEM_UID);
5079 } else {
5080 newCachePath = PackageHelper.getSdDir(newCacheId);
5081 }
5082 if (newCachePath == null) {
5083 Log.w(TAG, "Failed to get cache path for " + newCacheId);
5084 return false;
5085 }
5086 Log.i(TAG, "Succesfully renamed " + cid +
5087 " at path: " + cachePath + " to " + newCacheId +
5088 " at new path: " + newCachePath);
5089 cid = newCacheId;
5090 cachePath = newCachePath;
5091 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005092 }
5093
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005094 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005095 if (status != PackageManager.INSTALL_SUCCEEDED) {
5096 cleanUp();
5097 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005098 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005099 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005100 PackageHelper.mountSdDir(cid,
5101 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005102 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005103 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005104 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005105 }
5106
5107 private void cleanUp() {
5108 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005109 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005110 }
5111
5112 void cleanUpResourcesLI() {
5113 String sourceFile = getCodePath();
5114 // Remove dex file
5115 if (mInstaller != null) {
5116 int retCode = mInstaller.rmdex(sourceFile.toString());
5117 if (retCode < 0) {
5118 Log.w(TAG, "Couldn't remove dex file for package: "
5119 + " at location "
5120 + sourceFile.toString() + ", retcode=" + retCode);
5121 // we don't consider this to be a failure of the core package deletion
5122 }
5123 }
5124 cleanUp();
5125 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005126
5127 boolean matchContainer(String app) {
5128 if (cid.startsWith(app)) {
5129 return true;
5130 }
5131 return false;
5132 }
5133
5134 String getPackageName() {
5135 int idx = cid.lastIndexOf("-");
5136 if (idx == -1) {
5137 return cid;
5138 }
5139 return cid.substring(0, idx);
5140 }
5141
5142 boolean doPostDeleteLI(boolean delete) {
5143 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005144 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005145 if (mounted) {
5146 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005147 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005148 }
5149 if (ret && delete) {
5150 cleanUpResourcesLI();
5151 }
5152 return ret;
5153 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005154 };
5155
5156 // Utility method used to create code paths based on package name and available index.
5157 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5158 String idxStr = "";
5159 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005160 // Fall back to default value of idx=1 if prefix is not
5161 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005162 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005163 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005164 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005165 if (subStr.endsWith(suffix)) {
5166 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005167 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005168 // If oldCodePath already contains prefix find out the
5169 // ending index to either increment or decrement.
5170 int sidx = subStr.lastIndexOf(prefix);
5171 if (sidx != -1) {
5172 subStr = subStr.substring(sidx + prefix.length());
5173 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005174 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5175 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005176 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005177 try {
5178 idx = Integer.parseInt(subStr);
5179 if (idx <= 1) {
5180 idx++;
5181 } else {
5182 idx--;
5183 }
5184 } catch(NumberFormatException e) {
5185 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005186 }
5187 }
5188 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005189 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005190 return prefix + idxStr;
5191 }
5192
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005193 // Utility method used to ignore ADD/REMOVE events
5194 // by directory observer.
5195 private static boolean ignoreCodePath(String fullPathStr) {
5196 String apkName = getApkName(fullPathStr);
5197 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5198 if (idx != -1 && ((idx+1) < apkName.length())) {
5199 // Make sure the package ends with a numeral
5200 String version = apkName.substring(idx+1);
5201 try {
5202 Integer.parseInt(version);
5203 return true;
5204 } catch (NumberFormatException e) {}
5205 }
5206 return false;
5207 }
5208
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005209 // Utility method that returns the relative package path with respect
5210 // to the installation directory. Like say for /data/data/com.test-1.apk
5211 // string com.test-1 is returned.
5212 static String getApkName(String codePath) {
5213 if (codePath == null) {
5214 return null;
5215 }
5216 int sidx = codePath.lastIndexOf("/");
5217 int eidx = codePath.lastIndexOf(".");
5218 if (eidx == -1) {
5219 eidx = codePath.length();
5220 } else if (eidx == 0) {
5221 Log.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
5222 return null;
5223 }
5224 return codePath.substring(sidx+1, eidx);
5225 }
5226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005227 class PackageInstalledInfo {
5228 String name;
5229 int uid;
5230 PackageParser.Package pkg;
5231 int returnCode;
5232 PackageRemovedInfo removedInfo;
5233 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005235 /*
5236 * Install a non-existing package.
5237 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005238 private void installNewPackageLI(PackageParser.Package pkg,
5239 int parseFlags,
5240 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005241 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005242 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005243 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005244
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005245 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005246 res.name = pkgName;
5247 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005248 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005249 // Don't allow installation over an existing package with the same name.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005250 Log.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005251 + " without first uninstalling.");
5252 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5253 return;
5254 }
5255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005256 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005257 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005258 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005259 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005260 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5261 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5262 }
5263 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005264 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005265 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005266 res);
5267 // delete the partially installed application. the data directory will have to be
5268 // restored if it was already existing
5269 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5270 // remove package from internal structures. Note that we want deletePackageX to
5271 // delete the package data and cache directories that it created in
5272 // scanPackageLocked, unless those directories existed before we even tried to
5273 // install.
5274 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005275 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005276 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5277 res.removedInfo);
5278 }
5279 }
5280 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005281
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005282 private void replacePackageLI(PackageParser.Package pkg,
5283 int parseFlags,
5284 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005285 String installerPackageName, PackageInstalledInfo res) {
5286
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005287 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005288 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005289 // First find the old package info and check signatures
5290 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005291 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005292 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005293 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005294 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5295 return;
5296 }
5297 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005298 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005299 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005300 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005301 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005302 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005303 }
5304 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005306 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005307 PackageParser.Package pkg,
5308 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005309 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005310 PackageParser.Package newPackage = null;
5311 String pkgName = deletedPackage.packageName;
5312 boolean deletedPkg = true;
5313 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005314
Jacek Surazski65e13172009-04-28 15:26:38 +02005315 String oldInstallerPackageName = null;
5316 synchronized (mPackages) {
5317 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5318 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005319
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005320 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005321 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005322 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005323 res.removedInfo)) {
5324 // If the existing package was'nt successfully deleted
5325 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5326 deletedPkg = false;
5327 } else {
5328 // Successfully deleted the old package. Now proceed with re-installation
5329 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005330 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005331 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005332 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005333 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5334 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005335 }
5336 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005337 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005338 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005339 res);
5340 updatedSettings = true;
5341 }
5342 }
5343
5344 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5345 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005346 // were keeping around in case we needed them (see below) can now be deleted.
5347 // This info will be set on the res.removedInfo to clean up later on as post
5348 // install action.
5349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005350 //update signature on the new package setting
5351 //this should always succeed, since we checked the
5352 //signature earlier.
5353 synchronized(mPackages) {
5354 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
5355 parseFlags, true);
5356 }
5357 } else {
5358 // remove package from internal structures. Note that we want deletePackageX to
5359 // delete the package data and cache directories that it created in
5360 // scanPackageLocked, unless those directories existed before we even tried to
5361 // install.
5362 if(updatedSettings) {
5363 deletePackageLI(
5364 pkgName, true,
5365 PackageManager.DONT_DELETE_DATA,
5366 res.removedInfo);
5367 }
5368 // Since we failed to install the new package we need to restore the old
5369 // package that we deleted.
5370 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005371 File restoreFile = new File(deletedPackage.mPath);
5372 if (restoreFile == null) {
5373 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
5374 return;
5375 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005376 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5377 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005378 // Parse old package
5379 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5380 scanPackageLI(restoreFile, parseFlags, scanMode);
5381 synchronized (mPackages) {
5382 grantPermissionsLP(deletedPackage, false);
5383 mSettings.writeLP();
5384 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005385 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5386 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
5387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005388 }
5389 }
5390 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005392 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005393 PackageParser.Package pkg,
5394 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005395 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005396 PackageParser.Package newPackage = null;
5397 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005398 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005399 PackageParser.PARSE_IS_SYSTEM;
5400 String packageName = deletedPackage.packageName;
5401 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5402 if (packageName == null) {
5403 Log.w(TAG, "Attempt to delete null packageName.");
5404 return;
5405 }
5406 PackageParser.Package oldPkg;
5407 PackageSetting oldPkgSetting;
5408 synchronized (mPackages) {
5409 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005410 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005411 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5412 (oldPkgSetting == null)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005413 Log.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005414 return;
5415 }
5416 }
5417 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5418 res.removedInfo.removedPackage = packageName;
5419 // Remove existing system package
5420 removePackageLI(oldPkg, true);
5421 synchronized (mPackages) {
5422 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5423 }
5424
5425 // Successfully disabled the old package. Now proceed with re-installation
5426 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5427 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005428 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005429 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005430 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005431 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5432 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5433 }
5434 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005435 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005436 updatedSettings = true;
5437 }
5438
5439 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5440 //update signature on the new package setting
5441 //this should always succeed, since we checked the
5442 //signature earlier.
5443 synchronized(mPackages) {
5444 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5445 parseFlags, true);
5446 }
5447 } else {
5448 // Re installation failed. Restore old information
5449 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005450 if (newPackage != null) {
5451 removePackageLI(newPackage, true);
5452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005453 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005454 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005455 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005456 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005457 // Restore the old system information in Settings
5458 synchronized(mPackages) {
5459 if(updatedSettings) {
5460 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005461 mSettings.setInstallerPackageName(packageName,
5462 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005463 }
5464 mSettings.writeLP();
5465 }
5466 }
5467 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005468
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005469 // Utility method used to move dex files during install.
5470 private int moveDexFiles(PackageParser.Package newPackage) {
5471 int retCode;
5472 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5473 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5474 if (retCode != 0) {
5475 Log.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5476 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5477 }
5478 }
5479 return PackageManager.INSTALL_SUCCEEDED;
5480 }
5481
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005482 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005483 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005484 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005485 synchronized (mPackages) {
5486 //write settings. the installStatus will be incomplete at this stage.
5487 //note that the new package setting would have already been
5488 //added to mPackages. It hasn't been persisted yet.
5489 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5490 mSettings.writeLP();
5491 }
5492
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005493 if ((res.returnCode = moveDexFiles(newPackage))
5494 != PackageManager.INSTALL_SUCCEEDED) {
5495 // Discontinue if moving dex files failed.
5496 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005497 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005498 if((res.returnCode = setPermissionsLI(newPackage))
5499 != PackageManager.INSTALL_SUCCEEDED) {
5500 if (mInstaller != null) {
5501 mInstaller.rmdex(newPackage.mScanPath);
5502 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005503 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005504 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005505 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005507 synchronized (mPackages) {
5508 grantPermissionsLP(newPackage, true);
5509 res.name = pkgName;
5510 res.uid = newPackage.applicationInfo.uid;
5511 res.pkg = newPackage;
5512 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005513 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005514 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5515 //to update install status
5516 mSettings.writeLP();
5517 }
5518 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005519
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005520 private void installPackageLI(InstallArgs args,
5521 boolean newInstall, PackageInstalledInfo res) {
5522 int pFlags = args.flags;
5523 String installerPackageName = args.installerPackageName;
5524 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005525 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005526 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005527 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005528 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5529 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005530 // Result object to be returned
5531 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5532
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005533 // Retrieve PackageSettings and parse package
5534 int parseFlags = PackageParser.PARSE_CHATTY |
5535 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5536 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5537 parseFlags |= mDefParseFlags;
5538 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5539 pp.setSeparateProcesses(mSeparateProcesses);
5540 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5541 null, mMetrics, parseFlags);
5542 if (pkg == null) {
5543 res.returnCode = pp.getParseError();
5544 return;
5545 }
5546 String pkgName = res.name = pkg.packageName;
5547 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5548 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5549 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5550 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005551 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005552 }
5553 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5554 res.returnCode = pp.getParseError();
5555 return;
5556 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005557 // Get rid of all references to package scan path via parser.
5558 pp = null;
5559 String oldCodePath = null;
5560 boolean systemApp = false;
5561 synchronized (mPackages) {
5562 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005563 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5564 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005565 if (pkg.mOriginalPackages != null
5566 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005567 && mPackages.containsKey(oldName)) {
5568 // This package is derived from an original package,
5569 // and this device has been updating from that original
5570 // name. We must continue using the original name, so
5571 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005572 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005573 pkgName = pkg.packageName;
5574 replace = true;
5575 } else if (mPackages.containsKey(pkgName)) {
5576 // This package, under its official name, already exists
5577 // on the device; we should replace it.
5578 replace = true;
5579 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005580 }
5581 PackageSetting ps = mSettings.mPackages.get(pkgName);
5582 if (ps != null) {
5583 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5584 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5585 systemApp = (ps.pkg.applicationInfo.flags &
5586 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005587 }
5588 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005589 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005590
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005591 if (systemApp && onSd) {
5592 // Disable updates to system apps on sdcard
5593 Log.w(TAG, "Cannot install updates to system apps on sdcard");
5594 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5595 return;
5596 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005597
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005598 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5599 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5600 return;
5601 }
5602 // Set application objects path explicitly after the rename
5603 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005604 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005605 replacePackageLI(pkg, parseFlags, scanMode,
5606 installerPackageName, res);
5607 } else {
5608 installNewPackageLI(pkg, parseFlags, scanMode,
5609 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005610 }
5611 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005612
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005613 private int setPermissionsLI(PackageParser.Package newPackage) {
5614 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005615 int retCode = 0;
5616 // TODO Gross hack but fix later. Ideally move this to be a post installation
5617 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005618 if ((newPackage.applicationInfo.flags
5619 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5620 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005621 try {
5622 extractPublicFiles(newPackage, destResourceFile);
5623 } catch (IOException e) {
5624 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
5625 " forward-locked app.");
5626 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5627 } finally {
5628 //TODO clean up the extracted public files
5629 }
5630 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005631 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005632 newPackage.applicationInfo.uid);
5633 } else {
5634 final int filePermissions =
5635 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005636 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005637 newPackage.applicationInfo.uid);
5638 }
5639 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005640 // The permissions on the resource file was set when it was copied for
5641 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005644 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005645 Log.e(TAG, "Couldn't set new package file permissions for " +
5646 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005647 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005648 // TODO Define new internal error
5649 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005650 }
5651 return PackageManager.INSTALL_SUCCEEDED;
5652 }
5653
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005654 private boolean isForwardLocked(PackageParser.Package pkg) {
5655 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005656 }
5657
5658 private void extractPublicFiles(PackageParser.Package newPackage,
5659 File publicZipFile) throws IOException {
5660 final ZipOutputStream publicZipOutStream =
5661 new ZipOutputStream(new FileOutputStream(publicZipFile));
5662 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5663
5664 // Copy manifest, resources.arsc and res directory to public zip
5665
5666 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5667 while (privateZipEntries.hasMoreElements()) {
5668 final ZipEntry zipEntry = privateZipEntries.nextElement();
5669 final String zipEntryName = zipEntry.getName();
5670 if ("AndroidManifest.xml".equals(zipEntryName)
5671 || "resources.arsc".equals(zipEntryName)
5672 || zipEntryName.startsWith("res/")) {
5673 try {
5674 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5675 } catch (IOException e) {
5676 try {
5677 publicZipOutStream.close();
5678 throw e;
5679 } finally {
5680 publicZipFile.delete();
5681 }
5682 }
5683 }
5684 }
5685
5686 publicZipOutStream.close();
5687 FileUtils.setPermissions(
5688 publicZipFile.getAbsolutePath(),
5689 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5690 -1, -1);
5691 }
5692
5693 private static void copyZipEntry(ZipEntry zipEntry,
5694 ZipFile inZipFile,
5695 ZipOutputStream outZipStream) throws IOException {
5696 byte[] buffer = new byte[4096];
5697 int num;
5698
5699 ZipEntry newEntry;
5700 if (zipEntry.getMethod() == ZipEntry.STORED) {
5701 // Preserve the STORED method of the input entry.
5702 newEntry = new ZipEntry(zipEntry);
5703 } else {
5704 // Create a new entry so that the compressed len is recomputed.
5705 newEntry = new ZipEntry(zipEntry.getName());
5706 }
5707 outZipStream.putNextEntry(newEntry);
5708
5709 InputStream data = inZipFile.getInputStream(zipEntry);
5710 while ((num = data.read(buffer)) > 0) {
5711 outZipStream.write(buffer, 0, num);
5712 }
5713 outZipStream.flush();
5714 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005716 private void deleteTempPackageFiles() {
5717 FilenameFilter filter = new FilenameFilter() {
5718 public boolean accept(File dir, String name) {
5719 return name.startsWith("vmdl") && name.endsWith(".tmp");
5720 }
5721 };
5722 String tmpFilesList[] = mAppInstallDir.list(filter);
5723 if(tmpFilesList == null) {
5724 return;
5725 }
5726 for(int i = 0; i < tmpFilesList.length; i++) {
5727 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5728 tmpFile.delete();
5729 }
5730 }
5731
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005732 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005733 File tmpPackageFile;
5734 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005735 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 } catch (IOException e) {
5737 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
5738 return null;
5739 }
5740 try {
5741 FileUtils.setPermissions(
5742 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5743 -1, -1);
5744 } catch (IOException e) {
5745 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
5746 return null;
5747 }
5748 return tmpPackageFile;
5749 }
5750
5751 public void deletePackage(final String packageName,
5752 final IPackageDeleteObserver observer,
5753 final int flags) {
5754 mContext.enforceCallingOrSelfPermission(
5755 android.Manifest.permission.DELETE_PACKAGES, null);
5756 // Queue up an async operation since the package deletion may take a little while.
5757 mHandler.post(new Runnable() {
5758 public void run() {
5759 mHandler.removeCallbacks(this);
5760 final boolean succeded = deletePackageX(packageName, true, true, flags);
5761 if (observer != null) {
5762 try {
5763 observer.packageDeleted(succeded);
5764 } catch (RemoteException e) {
5765 Log.i(TAG, "Observer no longer exists.");
5766 } //end catch
5767 } //end if
5768 } //end run
5769 });
5770 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005772 /**
5773 * This method is an internal method that could be get invoked either
5774 * to delete an installed package or to clean up a failed installation.
5775 * After deleting an installed package, a broadcast is sent to notify any
5776 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005777 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005778 * installation wouldn't have sent the initial broadcast either
5779 * The key steps in deleting a package are
5780 * deleting the package information in internal structures like mPackages,
5781 * deleting the packages base directories through installd
5782 * updating mSettings to reflect current status
5783 * persisting settings for later use
5784 * sending a broadcast if necessary
5785 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005786 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5787 boolean deleteCodeAndResources, int flags) {
5788 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005789 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005791 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
5792 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
5793 try {
5794 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
5795 Log.w(TAG, "Not removing package " + packageName + ": has active device admin");
5796 return false;
5797 }
5798 } catch (RemoteException e) {
5799 }
5800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005801 synchronized (mInstallLock) {
5802 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5803 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005805 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005806 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5807 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5808
5809 // If the removed package was a system update, the old system packaged
5810 // was re-enabled; we need to broadcast this information
5811 if (systemUpdate) {
5812 Bundle extras = new Bundle(1);
5813 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5814 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5815
5816 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5817 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5818 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005819 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005820 // Force a gc here.
5821 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005822 // Delete the resources here after sending the broadcast to let
5823 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005824 if (info.args != null) {
5825 synchronized (mInstallLock) {
5826 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005827 }
5828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005829 return res;
5830 }
5831
5832 static class PackageRemovedInfo {
5833 String removedPackage;
5834 int uid = -1;
5835 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005836 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005837 // Clean up resources deleted packages.
5838 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005840 void sendBroadcast(boolean fullRemove, boolean replacing) {
5841 Bundle extras = new Bundle(1);
5842 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5843 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5844 if (replacing) {
5845 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5846 }
5847 if (removedPackage != null) {
5848 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5849 }
5850 if (removedUid >= 0) {
5851 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5852 }
5853 }
5854 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005856 /*
5857 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5858 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005859 * 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 -08005860 * delete a partially installed application.
5861 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005862 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005863 int flags) {
5864 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005865 if (outInfo != null) {
5866 outInfo.removedPackage = packageName;
5867 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005868 removePackageLI(p, true);
5869 // Retrieve object to delete permissions for shared user later on
5870 PackageSetting deletedPs;
5871 synchronized (mPackages) {
5872 deletedPs = mSettings.mPackages.get(packageName);
5873 }
5874 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005875 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005876 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005877 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005878 if (retCode < 0) {
5879 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
5880 + packageName + ", retcode=" + retCode);
5881 // we don't consider this to be a failure of the core package deletion
5882 }
5883 } else {
5884 //for emulator
5885 PackageParser.Package pkg = mPackages.get(packageName);
5886 File dataDir = new File(pkg.applicationInfo.dataDir);
5887 dataDir.delete();
5888 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005889 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005890 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005891 if (outInfo != null) {
5892 outInfo.removedUid = mSettings.removePackageLP(packageName);
5893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005894 }
5895 }
5896 synchronized (mPackages) {
5897 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5898 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005899 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005900 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005901 if (deletedPs != null) {
5902 // remove from preferred activities.
5903 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
5904 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
5905 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
5906 removed.add(pa);
5907 }
5908 }
5909 for (PreferredActivity pa : removed) {
5910 mSettings.mPreferredActivities.removeFilter(pa);
5911 }
5912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005913 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005914 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005915 }
5916 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005918 /*
5919 * Tries to delete system package.
5920 */
5921 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005922 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005923 ApplicationInfo applicationInfo = p.applicationInfo;
5924 //applicable for non-partially installed applications only
5925 if (applicationInfo == null) {
5926 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5927 return false;
5928 }
5929 PackageSetting ps = null;
5930 // Confirm if the system package has been updated
5931 // An updated system app can be deleted. This will also have to restore
5932 // the system pkg from system partition
5933 synchronized (mPackages) {
5934 ps = mSettings.getDisabledSystemPkg(p.packageName);
5935 }
5936 if (ps == null) {
5937 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
5938 return false;
5939 } else {
5940 Log.i(TAG, "Deleting system pkg from data partition");
5941 }
5942 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005943 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005944 boolean deleteCodeAndResources = false;
5945 if (ps.versionCode < p.mVersionCode) {
5946 // Delete code and resources for downgrades
5947 deleteCodeAndResources = true;
5948 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5949 flags &= ~PackageManager.DONT_DELETE_DATA;
5950 }
5951 } else {
5952 // Preserve data by setting flag
5953 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5954 flags |= PackageManager.DONT_DELETE_DATA;
5955 }
5956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005957 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5958 if (!ret) {
5959 return false;
5960 }
5961 synchronized (mPackages) {
5962 // Reinstate the old system package
5963 mSettings.enableSystemPackageLP(p.packageName);
5964 }
5965 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005966 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005967 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005968 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970 if (newPkg == null) {
5971 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
5972 return false;
5973 }
5974 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07005975 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 mSettings.writeLP();
5977 }
5978 return true;
5979 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005981 private boolean deleteInstalledPackageLI(PackageParser.Package p,
5982 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5983 ApplicationInfo applicationInfo = p.applicationInfo;
5984 if (applicationInfo == null) {
5985 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5986 return false;
5987 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005988 if (outInfo != null) {
5989 outInfo.uid = applicationInfo.uid;
5990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005991
5992 // Delete package data from internal structures and also remove data if flag is set
5993 removePackageDataLI(p, outInfo, flags);
5994
5995 // Delete application code and resources
5996 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005997 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08005998 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005999 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006000 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6001 PackageManager.INSTALL_FORWARD_LOCK : 0;
6002 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006003 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006004 }
6005 return true;
6006 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006008 /*
6009 * This method handles package deletion in general
6010 */
6011 private boolean deletePackageLI(String packageName,
6012 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6013 if (packageName == null) {
6014 Log.w(TAG, "Attempt to delete null packageName.");
6015 return false;
6016 }
6017 PackageParser.Package p;
6018 boolean dataOnly = false;
6019 synchronized (mPackages) {
6020 p = mPackages.get(packageName);
6021 if (p == null) {
6022 //this retrieves partially installed apps
6023 dataOnly = true;
6024 PackageSetting ps = mSettings.mPackages.get(packageName);
6025 if (ps == null) {
6026 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6027 return false;
6028 }
6029 p = ps.pkg;
6030 }
6031 }
6032 if (p == null) {
6033 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6034 return false;
6035 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006037 if (dataOnly) {
6038 // Delete application data first
6039 removePackageDataLI(p, outInfo, flags);
6040 return true;
6041 }
6042 // At this point the package should have ApplicationInfo associated with it
6043 if (p.applicationInfo == null) {
6044 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
6045 return false;
6046 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006047 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006048 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6049 Log.i(TAG, "Removing system package:"+p.packageName);
6050 // When an updated system application is deleted we delete the existing resources as well and
6051 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006052 ret = deleteSystemPackageLI(p, flags, outInfo);
6053 } else {
6054 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006055 // Kill application pre-emptively especially for apps on sd.
6056 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006057 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006058 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006059 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006060 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006062 public void clearApplicationUserData(final String packageName,
6063 final IPackageDataObserver observer) {
6064 mContext.enforceCallingOrSelfPermission(
6065 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6066 // Queue up an async operation since the package deletion may take a little while.
6067 mHandler.post(new Runnable() {
6068 public void run() {
6069 mHandler.removeCallbacks(this);
6070 final boolean succeeded;
6071 synchronized (mInstallLock) {
6072 succeeded = clearApplicationUserDataLI(packageName);
6073 }
6074 if (succeeded) {
6075 // invoke DeviceStorageMonitor's update method to clear any notifications
6076 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6077 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6078 if (dsm != null) {
6079 dsm.updateMemory();
6080 }
6081 }
6082 if(observer != null) {
6083 try {
6084 observer.onRemoveCompleted(packageName, succeeded);
6085 } catch (RemoteException e) {
6086 Log.i(TAG, "Observer no longer exists.");
6087 }
6088 } //end if observer
6089 } //end run
6090 });
6091 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093 private boolean clearApplicationUserDataLI(String packageName) {
6094 if (packageName == null) {
6095 Log.w(TAG, "Attempt to delete null packageName.");
6096 return false;
6097 }
6098 PackageParser.Package p;
6099 boolean dataOnly = false;
6100 synchronized (mPackages) {
6101 p = mPackages.get(packageName);
6102 if(p == null) {
6103 dataOnly = true;
6104 PackageSetting ps = mSettings.mPackages.get(packageName);
6105 if((ps == null) || (ps.pkg == null)) {
6106 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6107 return false;
6108 }
6109 p = ps.pkg;
6110 }
6111 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006112 boolean useEncryptedFSDir = false;
6113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006114 if(!dataOnly) {
6115 //need to check this only for fully installed applications
6116 if (p == null) {
6117 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6118 return false;
6119 }
6120 final ApplicationInfo applicationInfo = p.applicationInfo;
6121 if (applicationInfo == null) {
6122 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
6123 return false;
6124 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006125 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006126 }
6127 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006128 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006129 if (retCode < 0) {
6130 Log.w(TAG, "Couldn't remove cache files for package: "
6131 + packageName);
6132 return false;
6133 }
6134 }
6135 return true;
6136 }
6137
6138 public void deleteApplicationCacheFiles(final String packageName,
6139 final IPackageDataObserver observer) {
6140 mContext.enforceCallingOrSelfPermission(
6141 android.Manifest.permission.DELETE_CACHE_FILES, null);
6142 // Queue up an async operation since the package deletion may take a little while.
6143 mHandler.post(new Runnable() {
6144 public void run() {
6145 mHandler.removeCallbacks(this);
6146 final boolean succeded;
6147 synchronized (mInstallLock) {
6148 succeded = deleteApplicationCacheFilesLI(packageName);
6149 }
6150 if(observer != null) {
6151 try {
6152 observer.onRemoveCompleted(packageName, succeded);
6153 } catch (RemoteException e) {
6154 Log.i(TAG, "Observer no longer exists.");
6155 }
6156 } //end if observer
6157 } //end run
6158 });
6159 }
6160
6161 private boolean deleteApplicationCacheFilesLI(String packageName) {
6162 if (packageName == null) {
6163 Log.w(TAG, "Attempt to delete null packageName.");
6164 return false;
6165 }
6166 PackageParser.Package p;
6167 synchronized (mPackages) {
6168 p = mPackages.get(packageName);
6169 }
6170 if (p == null) {
6171 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6172 return false;
6173 }
6174 final ApplicationInfo applicationInfo = p.applicationInfo;
6175 if (applicationInfo == null) {
6176 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
6177 return false;
6178 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006179 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006180 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006181 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 if (retCode < 0) {
6183 Log.w(TAG, "Couldn't remove cache files for package: "
6184 + packageName);
6185 return false;
6186 }
6187 }
6188 return true;
6189 }
6190
6191 public void getPackageSizeInfo(final String packageName,
6192 final IPackageStatsObserver observer) {
6193 mContext.enforceCallingOrSelfPermission(
6194 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6195 // Queue up an async operation since the package deletion may take a little while.
6196 mHandler.post(new Runnable() {
6197 public void run() {
6198 mHandler.removeCallbacks(this);
6199 PackageStats lStats = new PackageStats(packageName);
6200 final boolean succeded;
6201 synchronized (mInstallLock) {
6202 succeded = getPackageSizeInfoLI(packageName, lStats);
6203 }
6204 if(observer != null) {
6205 try {
6206 observer.onGetStatsCompleted(lStats, succeded);
6207 } catch (RemoteException e) {
6208 Log.i(TAG, "Observer no longer exists.");
6209 }
6210 } //end if observer
6211 } //end run
6212 });
6213 }
6214
6215 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6216 if (packageName == null) {
6217 Log.w(TAG, "Attempt to get size of null packageName.");
6218 return false;
6219 }
6220 PackageParser.Package p;
6221 boolean dataOnly = false;
6222 synchronized (mPackages) {
6223 p = mPackages.get(packageName);
6224 if(p == null) {
6225 dataOnly = true;
6226 PackageSetting ps = mSettings.mPackages.get(packageName);
6227 if((ps == null) || (ps.pkg == null)) {
6228 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6229 return false;
6230 }
6231 p = ps.pkg;
6232 }
6233 }
6234 String publicSrcDir = null;
6235 if(!dataOnly) {
6236 final ApplicationInfo applicationInfo = p.applicationInfo;
6237 if (applicationInfo == null) {
6238 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
6239 return false;
6240 }
6241 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6242 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006243 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006244 if (mInstaller != null) {
6245 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006246 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006247 if (res < 0) {
6248 return false;
6249 } else {
6250 return true;
6251 }
6252 }
6253 return true;
6254 }
6255
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 public void addPackageToPreferred(String packageName) {
6258 mContext.enforceCallingOrSelfPermission(
6259 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006260 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006261 }
6262
6263 public void removePackageFromPreferred(String packageName) {
6264 mContext.enforceCallingOrSelfPermission(
6265 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006266 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006267 }
6268
6269 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006270 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 }
6272
6273 public void addPreferredActivity(IntentFilter filter, int match,
6274 ComponentName[] set, ComponentName activity) {
6275 mContext.enforceCallingOrSelfPermission(
6276 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6277
6278 synchronized (mPackages) {
6279 Log.i(TAG, "Adding preferred activity " + activity + ":");
6280 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6281 mSettings.mPreferredActivities.addFilter(
6282 new PreferredActivity(filter, match, set, activity));
6283 mSettings.writeLP();
6284 }
6285 }
6286
Satish Sampath8dbe6122009-06-02 23:35:54 +01006287 public void replacePreferredActivity(IntentFilter filter, int match,
6288 ComponentName[] set, ComponentName activity) {
6289 mContext.enforceCallingOrSelfPermission(
6290 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6291 if (filter.countActions() != 1) {
6292 throw new IllegalArgumentException(
6293 "replacePreferredActivity expects filter to have only 1 action.");
6294 }
6295 if (filter.countCategories() != 1) {
6296 throw new IllegalArgumentException(
6297 "replacePreferredActivity expects filter to have only 1 category.");
6298 }
6299 if (filter.countDataAuthorities() != 0
6300 || filter.countDataPaths() != 0
6301 || filter.countDataSchemes() != 0
6302 || filter.countDataTypes() != 0) {
6303 throw new IllegalArgumentException(
6304 "replacePreferredActivity expects filter to have no data authorities, " +
6305 "paths, schemes or types.");
6306 }
6307 synchronized (mPackages) {
6308 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6309 String action = filter.getAction(0);
6310 String category = filter.getCategory(0);
6311 while (it.hasNext()) {
6312 PreferredActivity pa = it.next();
6313 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6314 it.remove();
6315 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6316 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6317 }
6318 }
6319 addPreferredActivity(filter, match, set, activity);
6320 }
6321 }
6322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323 public void clearPackagePreferredActivities(String packageName) {
6324 mContext.enforceCallingOrSelfPermission(
6325 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6326
6327 synchronized (mPackages) {
6328 if (clearPackagePreferredActivitiesLP(packageName)) {
6329 mSettings.writeLP();
6330 }
6331 }
6332 }
6333
6334 boolean clearPackagePreferredActivitiesLP(String packageName) {
6335 boolean changed = false;
6336 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6337 while (it.hasNext()) {
6338 PreferredActivity pa = it.next();
6339 if (pa.mActivity.getPackageName().equals(packageName)) {
6340 it.remove();
6341 changed = true;
6342 }
6343 }
6344 return changed;
6345 }
6346
6347 public int getPreferredActivities(List<IntentFilter> outFilters,
6348 List<ComponentName> outActivities, String packageName) {
6349
6350 int num = 0;
6351 synchronized (mPackages) {
6352 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6353 while (it.hasNext()) {
6354 PreferredActivity pa = it.next();
6355 if (packageName == null
6356 || pa.mActivity.getPackageName().equals(packageName)) {
6357 if (outFilters != null) {
6358 outFilters.add(new IntentFilter(pa));
6359 }
6360 if (outActivities != null) {
6361 outActivities.add(pa.mActivity);
6362 }
6363 }
6364 }
6365 }
6366
6367 return num;
6368 }
6369
6370 public void setApplicationEnabledSetting(String appPackageName,
6371 int newState, int flags) {
6372 setEnabledSetting(appPackageName, null, newState, flags);
6373 }
6374
6375 public void setComponentEnabledSetting(ComponentName componentName,
6376 int newState, int flags) {
6377 setEnabledSetting(componentName.getPackageName(),
6378 componentName.getClassName(), newState, flags);
6379 }
6380
6381 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006382 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006383 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6384 || newState == COMPONENT_ENABLED_STATE_ENABLED
6385 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6386 throw new IllegalArgumentException("Invalid new component state: "
6387 + newState);
6388 }
6389 PackageSetting pkgSetting;
6390 final int uid = Binder.getCallingUid();
6391 final int permission = mContext.checkCallingPermission(
6392 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6393 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006394 boolean sendNow = false;
6395 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006396 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006397 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006398 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006399 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006400 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006401 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006402 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006404 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006405 }
6406 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006407 "Unknown component: " + packageName
6408 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006409 }
6410 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6411 throw new SecurityException(
6412 "Permission Denial: attempt to change component state from pid="
6413 + Binder.getCallingPid()
6414 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6415 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006416 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006417 // We're dealing with an application/package level state change
6418 pkgSetting.enabled = newState;
6419 } else {
6420 // We're dealing with a component level state change
6421 switch (newState) {
6422 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006423 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006424 break;
6425 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006426 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006427 break;
6428 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006429 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006430 break;
6431 default:
6432 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006433 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006434 }
6435 }
6436 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006437 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006438 components = mPendingBroadcasts.get(packageName);
6439 boolean newPackage = components == null;
6440 if (newPackage) {
6441 components = new ArrayList<String>();
6442 }
6443 if (!components.contains(componentName)) {
6444 components.add(componentName);
6445 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006446 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6447 sendNow = true;
6448 // Purge entry from pending broadcast list if another one exists already
6449 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006450 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006451 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006452 if (newPackage) {
6453 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006454 }
6455 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6456 // Schedule a message
6457 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6458 }
6459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006460 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 long callingId = Binder.clearCallingIdentity();
6463 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006464 if (sendNow) {
6465 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006466 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006468 } finally {
6469 Binder.restoreCallingIdentity(callingId);
6470 }
6471 }
6472
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006473 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006474 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6475 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6476 + " components=" + componentNames);
6477 Bundle extras = new Bundle(4);
6478 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6479 String nameList[] = new String[componentNames.size()];
6480 componentNames.toArray(nameList);
6481 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006482 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6483 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006484 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006485 }
6486
Jacek Surazski65e13172009-04-28 15:26:38 +02006487 public String getInstallerPackageName(String packageName) {
6488 synchronized (mPackages) {
6489 PackageSetting pkg = mSettings.mPackages.get(packageName);
6490 if (pkg == null) {
6491 throw new IllegalArgumentException("Unknown package: " + packageName);
6492 }
6493 return pkg.installerPackageName;
6494 }
6495 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006497 public int getApplicationEnabledSetting(String appPackageName) {
6498 synchronized (mPackages) {
6499 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6500 if (pkg == null) {
6501 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6502 }
6503 return pkg.enabled;
6504 }
6505 }
6506
6507 public int getComponentEnabledSetting(ComponentName componentName) {
6508 synchronized (mPackages) {
6509 final String packageNameStr = componentName.getPackageName();
6510 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6511 if (pkg == null) {
6512 throw new IllegalArgumentException("Unknown component: " + componentName);
6513 }
6514 final String classNameStr = componentName.getClassName();
6515 return pkg.currentEnabledStateLP(classNameStr);
6516 }
6517 }
6518
6519 public void enterSafeMode() {
6520 if (!mSystemReady) {
6521 mSafeMode = true;
6522 }
6523 }
6524
6525 public void systemReady() {
6526 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006527
6528 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006529 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006530 mContext.getContentResolver(),
6531 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006532 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006533 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006534 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 }
6537
6538 public boolean isSafeMode() {
6539 return mSafeMode;
6540 }
6541
6542 public boolean hasSystemUidErrors() {
6543 return mHasSystemUidErrors;
6544 }
6545
6546 static String arrayToString(int[] array) {
6547 StringBuffer buf = new StringBuffer(128);
6548 buf.append('[');
6549 if (array != null) {
6550 for (int i=0; i<array.length; i++) {
6551 if (i > 0) buf.append(", ");
6552 buf.append(array[i]);
6553 }
6554 }
6555 buf.append(']');
6556 return buf.toString();
6557 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006559 @Override
6560 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6561 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6562 != PackageManager.PERMISSION_GRANTED) {
6563 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6564 + Binder.getCallingPid()
6565 + ", uid=" + Binder.getCallingUid()
6566 + " without permission "
6567 + android.Manifest.permission.DUMP);
6568 return;
6569 }
6570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006571 synchronized (mPackages) {
6572 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006573 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006574 pw.println(" ");
6575 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006576 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006577 pw.println(" ");
6578 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006579 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006580 pw.println(" ");
6581 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006582 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006583 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006584 pw.println("Permissions:");
6585 {
6586 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006587 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6588 pw.print(Integer.toHexString(System.identityHashCode(p)));
6589 pw.println("):");
6590 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6591 pw.print(" uid="); pw.print(p.uid);
6592 pw.print(" gids="); pw.print(arrayToString(p.gids));
6593 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006594 }
6595 }
6596 pw.println(" ");
6597 pw.println("Packages:");
6598 {
6599 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006600 pw.print(" Package [");
6601 pw.print(ps.realName != null ? ps.realName : ps.name);
6602 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006603 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6604 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006605 if (ps.realName != null) {
6606 pw.print(" compat name="); pw.println(ps.name);
6607 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006608 pw.print(" userId="); pw.print(ps.userId);
6609 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6610 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6611 pw.print(" pkg="); pw.println(ps.pkg);
6612 pw.print(" codePath="); pw.println(ps.codePathString);
6613 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006615 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006616 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006617 pw.print(" supportsScreens=[");
6618 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006619 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006620 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006621 if (!first) pw.print(", ");
6622 first = false;
6623 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006624 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006625 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006626 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006627 if (!first) pw.print(", ");
6628 first = false;
6629 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006630 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006631 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006632 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006633 if (!first) pw.print(", ");
6634 first = false;
6635 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006636 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006637 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006638 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006639 if (!first) pw.print(", ");
6640 first = false;
6641 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006642 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006643 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006644 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6645 if (!first) pw.print(", ");
6646 first = false;
6647 pw.print("anyDensity");
6648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006649 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006650 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006651 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6652 pw.print(" signatures="); pw.println(ps.signatures);
6653 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6654 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6655 pw.print(" installStatus="); pw.print(ps.installStatus);
6656 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006657 if (ps.disabledComponents.size() > 0) {
6658 pw.println(" disabledComponents:");
6659 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006660 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006661 }
6662 }
6663 if (ps.enabledComponents.size() > 0) {
6664 pw.println(" enabledComponents:");
6665 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006666 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 }
6668 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006669 if (ps.grantedPermissions.size() > 0) {
6670 pw.println(" grantedPermissions:");
6671 for (String s : ps.grantedPermissions) {
6672 pw.print(" "); pw.println(s);
6673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006674 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006675 if (ps.loadedPermissions.size() > 0) {
6676 pw.println(" loadedPermissions:");
6677 for (String s : ps.loadedPermissions) {
6678 pw.print(" "); pw.println(s);
6679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006680 }
6681 }
6682 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006683 if (mSettings.mRenamedPackages.size() > 0) {
6684 pw.println(" ");
6685 pw.println("Renamed packages:");
6686 for (HashMap.Entry<String, String> e
6687 : mSettings.mRenamedPackages.entrySet()) {
6688 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6689 pw.println(e.getValue());
6690 }
6691 }
6692 if (mSettings.mDisabledSysPackages.size() > 0) {
6693 pw.println(" ");
6694 pw.println("Hidden system packages:");
6695 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
6696 pw.print(" Package [");
6697 pw.print(ps.realName != null ? ps.realName : ps.name);
6698 pw.print("] (");
6699 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6700 pw.println("):");
6701 if (ps.realName != null) {
6702 pw.print(" compat name="); pw.println(ps.name);
6703 }
6704 pw.print(" userId="); pw.println(ps.userId);
6705 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6706 pw.print(" codePath="); pw.println(ps.codePathString);
6707 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
6708 }
6709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006710 pw.println(" ");
6711 pw.println("Shared Users:");
6712 {
6713 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006714 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6715 pw.print(Integer.toHexString(System.identityHashCode(su)));
6716 pw.println("):");
6717 pw.print(" userId="); pw.print(su.userId);
6718 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006719 pw.println(" grantedPermissions:");
6720 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006721 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006722 }
6723 pw.println(" loadedPermissions:");
6724 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006725 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006726 }
6727 }
6728 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006730 pw.println(" ");
6731 pw.println("Settings parse messages:");
6732 pw.println(mSettings.mReadMessages.toString());
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006733
6734 pw.println(" ");
6735 pw.println("Package warning messages:");
6736 File fname = getSettingsProblemFile();
6737 FileInputStream in;
6738 try {
6739 in = new FileInputStream(fname);
6740 int avail = in.available();
6741 byte[] data = new byte[avail];
6742 in.read(data);
6743 pw.println(new String(data));
6744 } catch (FileNotFoundException e) {
6745 } catch (IOException e) {
6746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006747 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006748
6749 synchronized (mProviders) {
6750 pw.println(" ");
6751 pw.println("Registered ContentProviders:");
6752 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006753 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006754 pw.println(p.toString());
6755 }
6756 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006757 }
6758
6759 static final class BasePermission {
6760 final static int TYPE_NORMAL = 0;
6761 final static int TYPE_BUILTIN = 1;
6762 final static int TYPE_DYNAMIC = 2;
6763
6764 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006765 String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006766 final int type;
6767 PackageParser.Permission perm;
6768 PermissionInfo pendingInfo;
6769 int uid;
6770 int[] gids;
6771
6772 BasePermission(String _name, String _sourcePackage, int _type) {
6773 name = _name;
6774 sourcePackage = _sourcePackage;
6775 type = _type;
6776 }
6777 }
6778
6779 static class PackageSignatures {
6780 private Signature[] mSignatures;
6781
6782 PackageSignatures(Signature[] sigs) {
6783 assignSignatures(sigs);
6784 }
6785
6786 PackageSignatures() {
6787 }
6788
6789 void writeXml(XmlSerializer serializer, String tagName,
6790 ArrayList<Signature> pastSignatures) throws IOException {
6791 if (mSignatures == null) {
6792 return;
6793 }
6794 serializer.startTag(null, tagName);
6795 serializer.attribute(null, "count",
6796 Integer.toString(mSignatures.length));
6797 for (int i=0; i<mSignatures.length; i++) {
6798 serializer.startTag(null, "cert");
6799 final Signature sig = mSignatures[i];
6800 final int sigHash = sig.hashCode();
6801 final int numPast = pastSignatures.size();
6802 int j;
6803 for (j=0; j<numPast; j++) {
6804 Signature pastSig = pastSignatures.get(j);
6805 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
6806 serializer.attribute(null, "index", Integer.toString(j));
6807 break;
6808 }
6809 }
6810 if (j >= numPast) {
6811 pastSignatures.add(sig);
6812 serializer.attribute(null, "index", Integer.toString(numPast));
6813 serializer.attribute(null, "key", sig.toCharsString());
6814 }
6815 serializer.endTag(null, "cert");
6816 }
6817 serializer.endTag(null, tagName);
6818 }
6819
6820 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
6821 throws IOException, XmlPullParserException {
6822 String countStr = parser.getAttributeValue(null, "count");
6823 if (countStr == null) {
6824 reportSettingsProblem(Log.WARN,
6825 "Error in package manager settings: <signatures> has"
6826 + " no count at " + parser.getPositionDescription());
6827 XmlUtils.skipCurrentTag(parser);
6828 }
6829 final int count = Integer.parseInt(countStr);
6830 mSignatures = new Signature[count];
6831 int pos = 0;
6832
6833 int outerDepth = parser.getDepth();
6834 int type;
6835 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6836 && (type != XmlPullParser.END_TAG
6837 || parser.getDepth() > outerDepth)) {
6838 if (type == XmlPullParser.END_TAG
6839 || type == XmlPullParser.TEXT) {
6840 continue;
6841 }
6842
6843 String tagName = parser.getName();
6844 if (tagName.equals("cert")) {
6845 if (pos < count) {
6846 String index = parser.getAttributeValue(null, "index");
6847 if (index != null) {
6848 try {
6849 int idx = Integer.parseInt(index);
6850 String key = parser.getAttributeValue(null, "key");
6851 if (key == null) {
6852 if (idx >= 0 && idx < pastSignatures.size()) {
6853 Signature sig = pastSignatures.get(idx);
6854 if (sig != null) {
6855 mSignatures[pos] = pastSignatures.get(idx);
6856 pos++;
6857 } else {
6858 reportSettingsProblem(Log.WARN,
6859 "Error in package manager settings: <cert> "
6860 + "index " + index + " is not defined at "
6861 + parser.getPositionDescription());
6862 }
6863 } else {
6864 reportSettingsProblem(Log.WARN,
6865 "Error in package manager settings: <cert> "
6866 + "index " + index + " is out of bounds at "
6867 + parser.getPositionDescription());
6868 }
6869 } else {
6870 while (pastSignatures.size() <= idx) {
6871 pastSignatures.add(null);
6872 }
6873 Signature sig = new Signature(key);
6874 pastSignatures.set(idx, sig);
6875 mSignatures[pos] = sig;
6876 pos++;
6877 }
6878 } catch (NumberFormatException e) {
6879 reportSettingsProblem(Log.WARN,
6880 "Error in package manager settings: <cert> "
6881 + "index " + index + " is not a number at "
6882 + parser.getPositionDescription());
6883 }
6884 } else {
6885 reportSettingsProblem(Log.WARN,
6886 "Error in package manager settings: <cert> has"
6887 + " no index at " + parser.getPositionDescription());
6888 }
6889 } else {
6890 reportSettingsProblem(Log.WARN,
6891 "Error in package manager settings: too "
6892 + "many <cert> tags, expected " + count
6893 + " at " + parser.getPositionDescription());
6894 }
6895 } else {
6896 reportSettingsProblem(Log.WARN,
6897 "Unknown element under <cert>: "
6898 + parser.getName());
6899 }
6900 XmlUtils.skipCurrentTag(parser);
6901 }
6902
6903 if (pos < count) {
6904 // Should never happen -- there is an error in the written
6905 // settings -- but if it does we don't want to generate
6906 // a bad array.
6907 Signature[] newSigs = new Signature[pos];
6908 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6909 mSignatures = newSigs;
6910 }
6911 }
6912
6913 /**
6914 * If any of the given 'sigs' is contained in the existing signatures,
6915 * then completely replace the current signatures with the ones in
6916 * 'sigs'. This is used for updating an existing package to a newly
6917 * installed version.
6918 */
6919 boolean updateSignatures(Signature[] sigs, boolean update) {
6920 if (mSignatures == null) {
6921 if (update) {
6922 assignSignatures(sigs);
6923 }
6924 return true;
6925 }
6926 if (sigs == null) {
6927 return false;
6928 }
6929
6930 for (int i=0; i<sigs.length; i++) {
6931 Signature sig = sigs[i];
6932 for (int j=0; j<mSignatures.length; j++) {
6933 if (mSignatures[j].equals(sig)) {
6934 if (update) {
6935 assignSignatures(sigs);
6936 }
6937 return true;
6938 }
6939 }
6940 }
6941 return false;
6942 }
6943
6944 /**
6945 * If any of the given 'sigs' is contained in the existing signatures,
6946 * then add in any new signatures found in 'sigs'. This is used for
6947 * including a new package into an existing shared user id.
6948 */
6949 boolean mergeSignatures(Signature[] sigs, boolean update) {
6950 if (mSignatures == null) {
6951 if (update) {
6952 assignSignatures(sigs);
6953 }
6954 return true;
6955 }
6956 if (sigs == null) {
6957 return false;
6958 }
6959
6960 Signature[] added = null;
6961 int addedCount = 0;
6962 boolean haveMatch = false;
6963 for (int i=0; i<sigs.length; i++) {
6964 Signature sig = sigs[i];
6965 boolean found = false;
6966 for (int j=0; j<mSignatures.length; j++) {
6967 if (mSignatures[j].equals(sig)) {
6968 found = true;
6969 haveMatch = true;
6970 break;
6971 }
6972 }
6973
6974 if (!found) {
6975 if (added == null) {
6976 added = new Signature[sigs.length];
6977 }
6978 added[i] = sig;
6979 addedCount++;
6980 }
6981 }
6982
6983 if (!haveMatch) {
6984 // Nothing matched -- reject the new signatures.
6985 return false;
6986 }
6987 if (added == null) {
6988 // Completely matched -- nothing else to do.
6989 return true;
6990 }
6991
6992 // Add additional signatures in.
6993 if (update) {
6994 Signature[] total = new Signature[addedCount+mSignatures.length];
6995 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
6996 int j = mSignatures.length;
6997 for (int i=0; i<added.length; i++) {
6998 if (added[i] != null) {
6999 total[j] = added[i];
7000 j++;
7001 }
7002 }
7003 mSignatures = total;
7004 }
7005 return true;
7006 }
7007
7008 private void assignSignatures(Signature[] sigs) {
7009 if (sigs == null) {
7010 mSignatures = null;
7011 return;
7012 }
7013 mSignatures = new Signature[sigs.length];
7014 for (int i=0; i<sigs.length; i++) {
7015 mSignatures[i] = sigs[i];
7016 }
7017 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007019 @Override
7020 public String toString() {
7021 StringBuffer buf = new StringBuffer(128);
7022 buf.append("PackageSignatures{");
7023 buf.append(Integer.toHexString(System.identityHashCode(this)));
7024 buf.append(" [");
7025 if (mSignatures != null) {
7026 for (int i=0; i<mSignatures.length; i++) {
7027 if (i > 0) buf.append(", ");
7028 buf.append(Integer.toHexString(
7029 System.identityHashCode(mSignatures[i])));
7030 }
7031 }
7032 buf.append("]}");
7033 return buf.toString();
7034 }
7035 }
7036
7037 static class PreferredActivity extends IntentFilter {
7038 final int mMatch;
7039 final String[] mSetPackages;
7040 final String[] mSetClasses;
7041 final String[] mSetComponents;
7042 final ComponentName mActivity;
7043 final String mShortActivity;
7044 String mParseError;
7045
7046 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7047 ComponentName activity) {
7048 super(filter);
7049 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7050 mActivity = activity;
7051 mShortActivity = activity.flattenToShortString();
7052 mParseError = null;
7053 if (set != null) {
7054 final int N = set.length;
7055 String[] myPackages = new String[N];
7056 String[] myClasses = new String[N];
7057 String[] myComponents = new String[N];
7058 for (int i=0; i<N; i++) {
7059 ComponentName cn = set[i];
7060 if (cn == null) {
7061 mSetPackages = null;
7062 mSetClasses = null;
7063 mSetComponents = null;
7064 return;
7065 }
7066 myPackages[i] = cn.getPackageName().intern();
7067 myClasses[i] = cn.getClassName().intern();
7068 myComponents[i] = cn.flattenToShortString().intern();
7069 }
7070 mSetPackages = myPackages;
7071 mSetClasses = myClasses;
7072 mSetComponents = myComponents;
7073 } else {
7074 mSetPackages = null;
7075 mSetClasses = null;
7076 mSetComponents = null;
7077 }
7078 }
7079
7080 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7081 IOException {
7082 mShortActivity = parser.getAttributeValue(null, "name");
7083 mActivity = ComponentName.unflattenFromString(mShortActivity);
7084 if (mActivity == null) {
7085 mParseError = "Bad activity name " + mShortActivity;
7086 }
7087 String matchStr = parser.getAttributeValue(null, "match");
7088 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7089 String setCountStr = parser.getAttributeValue(null, "set");
7090 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7091
7092 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7093 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7094 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7095
7096 int setPos = 0;
7097
7098 int outerDepth = parser.getDepth();
7099 int type;
7100 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7101 && (type != XmlPullParser.END_TAG
7102 || parser.getDepth() > outerDepth)) {
7103 if (type == XmlPullParser.END_TAG
7104 || type == XmlPullParser.TEXT) {
7105 continue;
7106 }
7107
7108 String tagName = parser.getName();
7109 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7110 // + parser.getDepth() + " tag=" + tagName);
7111 if (tagName.equals("set")) {
7112 String name = parser.getAttributeValue(null, "name");
7113 if (name == null) {
7114 if (mParseError == null) {
7115 mParseError = "No name in set tag in preferred activity "
7116 + mShortActivity;
7117 }
7118 } else if (setPos >= setCount) {
7119 if (mParseError == null) {
7120 mParseError = "Too many set tags in preferred activity "
7121 + mShortActivity;
7122 }
7123 } else {
7124 ComponentName cn = ComponentName.unflattenFromString(name);
7125 if (cn == null) {
7126 if (mParseError == null) {
7127 mParseError = "Bad set name " + name + " in preferred activity "
7128 + mShortActivity;
7129 }
7130 } else {
7131 myPackages[setPos] = cn.getPackageName();
7132 myClasses[setPos] = cn.getClassName();
7133 myComponents[setPos] = name;
7134 setPos++;
7135 }
7136 }
7137 XmlUtils.skipCurrentTag(parser);
7138 } else if (tagName.equals("filter")) {
7139 //Log.i(TAG, "Starting to parse filter...");
7140 readFromXml(parser);
7141 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7142 // + parser.getDepth() + " tag=" + parser.getName());
7143 } else {
7144 reportSettingsProblem(Log.WARN,
7145 "Unknown element under <preferred-activities>: "
7146 + parser.getName());
7147 XmlUtils.skipCurrentTag(parser);
7148 }
7149 }
7150
7151 if (setPos != setCount) {
7152 if (mParseError == null) {
7153 mParseError = "Not enough set tags (expected " + setCount
7154 + " but found " + setPos + ") in " + mShortActivity;
7155 }
7156 }
7157
7158 mSetPackages = myPackages;
7159 mSetClasses = myClasses;
7160 mSetComponents = myComponents;
7161 }
7162
7163 public void writeToXml(XmlSerializer serializer) throws IOException {
7164 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7165 serializer.attribute(null, "name", mShortActivity);
7166 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7167 serializer.attribute(null, "set", Integer.toString(NS));
7168 for (int s=0; s<NS; s++) {
7169 serializer.startTag(null, "set");
7170 serializer.attribute(null, "name", mSetComponents[s]);
7171 serializer.endTag(null, "set");
7172 }
7173 serializer.startTag(null, "filter");
7174 super.writeToXml(serializer);
7175 serializer.endTag(null, "filter");
7176 }
7177
7178 boolean sameSet(List<ResolveInfo> query, int priority) {
7179 if (mSetPackages == null) return false;
7180 final int NQ = query.size();
7181 final int NS = mSetPackages.length;
7182 int numMatch = 0;
7183 for (int i=0; i<NQ; i++) {
7184 ResolveInfo ri = query.get(i);
7185 if (ri.priority != priority) continue;
7186 ActivityInfo ai = ri.activityInfo;
7187 boolean good = false;
7188 for (int j=0; j<NS; j++) {
7189 if (mSetPackages[j].equals(ai.packageName)
7190 && mSetClasses[j].equals(ai.name)) {
7191 numMatch++;
7192 good = true;
7193 break;
7194 }
7195 }
7196 if (!good) return false;
7197 }
7198 return numMatch == NS;
7199 }
7200 }
7201
7202 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007203 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007205 HashSet<String> grantedPermissions = new HashSet<String>();
7206 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007208 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007210 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007211 setFlags(pkgFlags);
7212 }
7213
7214 void setFlags(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007215 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007216 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08007217 (pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) |
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08007218 (pkgFlags & ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007219 }
7220 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007222 /**
7223 * Settings base class for pending and resolved classes.
7224 */
7225 static class PackageSettingBase extends GrantedPermissions {
7226 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007227 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007228 File codePath;
7229 String codePathString;
7230 File resourcePath;
7231 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007232 private long timeStamp;
7233 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007234 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007235
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007236 boolean uidError;
7237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007238 PackageSignatures signatures = new PackageSignatures();
7239
7240 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007242 /* Explicitly disabled components */
7243 HashSet<String> disabledComponents = new HashSet<String>(0);
7244 /* Explicitly enabled components */
7245 HashSet<String> enabledComponents = new HashSet<String>(0);
7246 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7247 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007248
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007249 PackageSettingBase origPackage;
7250
Jacek Surazski65e13172009-04-28 15:26:38 +02007251 /* package name of the app that installed this package */
7252 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007253
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007254 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007255 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007256 super(pkgFlags);
7257 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007258 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007259 init(codePath, resourcePath, pVersionCode);
7260 }
7261
7262 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007263 this.codePath = codePath;
7264 this.codePathString = codePath.toString();
7265 this.resourcePath = resourcePath;
7266 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007267 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007268 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007269
Jacek Surazski65e13172009-04-28 15:26:38 +02007270 public void setInstallerPackageName(String packageName) {
7271 installerPackageName = packageName;
7272 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007273
Jacek Surazski65e13172009-04-28 15:26:38 +02007274 String getInstallerPackageName() {
7275 return installerPackageName;
7276 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007278 public void setInstallStatus(int newStatus) {
7279 installStatus = newStatus;
7280 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007282 public int getInstallStatus() {
7283 return installStatus;
7284 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007286 public void setTimeStamp(long newStamp) {
7287 if (newStamp != timeStamp) {
7288 timeStamp = newStamp;
7289 timeStampString = Long.toString(newStamp);
7290 }
7291 }
7292
7293 public void setTimeStamp(long newStamp, String newStampStr) {
7294 timeStamp = newStamp;
7295 timeStampString = newStampStr;
7296 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007298 public long getTimeStamp() {
7299 return timeStamp;
7300 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007302 public String getTimeStampStr() {
7303 return timeStampString;
7304 }
7305
7306 public void copyFrom(PackageSettingBase base) {
7307 grantedPermissions = base.grantedPermissions;
7308 gids = base.gids;
7309 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007311 timeStamp = base.timeStamp;
7312 timeStampString = base.timeStampString;
7313 signatures = base.signatures;
7314 permissionsFixed = base.permissionsFixed;
7315 disabledComponents = base.disabledComponents;
7316 enabledComponents = base.enabledComponents;
7317 enabled = base.enabled;
7318 installStatus = base.installStatus;
7319 }
7320
7321 void enableComponentLP(String componentClassName) {
7322 disabledComponents.remove(componentClassName);
7323 enabledComponents.add(componentClassName);
7324 }
7325
7326 void disableComponentLP(String componentClassName) {
7327 enabledComponents.remove(componentClassName);
7328 disabledComponents.add(componentClassName);
7329 }
7330
7331 void restoreComponentLP(String componentClassName) {
7332 enabledComponents.remove(componentClassName);
7333 disabledComponents.remove(componentClassName);
7334 }
7335
7336 int currentEnabledStateLP(String componentName) {
7337 if (enabledComponents.contains(componentName)) {
7338 return COMPONENT_ENABLED_STATE_ENABLED;
7339 } else if (disabledComponents.contains(componentName)) {
7340 return COMPONENT_ENABLED_STATE_DISABLED;
7341 } else {
7342 return COMPONENT_ENABLED_STATE_DEFAULT;
7343 }
7344 }
7345 }
7346
7347 /**
7348 * Settings data for a particular package we know about.
7349 */
7350 static final class PackageSetting extends PackageSettingBase {
7351 int userId;
7352 PackageParser.Package pkg;
7353 SharedUserSetting sharedUser;
7354
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007355 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007356 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007357 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007358 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007360 @Override
7361 public String toString() {
7362 return "PackageSetting{"
7363 + Integer.toHexString(System.identityHashCode(this))
7364 + " " + name + "/" + userId + "}";
7365 }
7366 }
7367
7368 /**
7369 * Settings data for a particular shared user ID we know about.
7370 */
7371 static final class SharedUserSetting extends GrantedPermissions {
7372 final String name;
7373 int userId;
7374 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7375 final PackageSignatures signatures = new PackageSignatures();
7376
7377 SharedUserSetting(String _name, int _pkgFlags) {
7378 super(_pkgFlags);
7379 name = _name;
7380 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007382 @Override
7383 public String toString() {
7384 return "SharedUserSetting{"
7385 + Integer.toHexString(System.identityHashCode(this))
7386 + " " + name + "/" + userId + "}";
7387 }
7388 }
7389
7390 /**
7391 * Holds information about dynamic settings.
7392 */
7393 private static final class Settings {
7394 private final File mSettingsFilename;
7395 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007396 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007397 private final HashMap<String, PackageSetting> mPackages =
7398 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007399 // List of replaced system applications
7400 final HashMap<String, PackageSetting> mDisabledSysPackages =
7401 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007403 // The user's preferred activities associated with particular intent
7404 // filters.
7405 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7406 new IntentResolver<PreferredActivity, PreferredActivity>() {
7407 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007408 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007409 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007410 out.print(prefix); out.print(
7411 Integer.toHexString(System.identityHashCode(filter)));
7412 out.print(' ');
7413 out.print(filter.mActivity.flattenToShortString());
7414 out.print(" match=0x");
7415 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007416 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007417 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007418 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007419 out.print(prefix); out.print(" ");
7420 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007421 }
7422 }
7423 }
7424 };
7425 private final HashMap<String, SharedUserSetting> mSharedUsers =
7426 new HashMap<String, SharedUserSetting>();
7427 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7428 private final SparseArray<Object> mOtherUserIds =
7429 new SparseArray<Object>();
7430
7431 // For reading/writing settings file.
7432 private final ArrayList<Signature> mPastSignatures =
7433 new ArrayList<Signature>();
7434
7435 // Mapping from permission names to info about them.
7436 final HashMap<String, BasePermission> mPermissions =
7437 new HashMap<String, BasePermission>();
7438
7439 // Mapping from permission tree names to info about them.
7440 final HashMap<String, BasePermission> mPermissionTrees =
7441 new HashMap<String, BasePermission>();
7442
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007443 // Packages that have been uninstalled and still need their external
7444 // storage data deleted.
7445 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7446
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007447 // Packages that have been renamed since they were first installed.
7448 // Keys are the new names of the packages, values are the original
7449 // names. The packages appear everwhere else under their original
7450 // names.
7451 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007453 private final StringBuilder mReadMessages = new StringBuilder();
7454
7455 private static final class PendingPackage extends PackageSettingBase {
7456 final int sharedId;
7457
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007458 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007459 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007460 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007461 this.sharedId = sharedId;
7462 }
7463 }
7464 private final ArrayList<PendingPackage> mPendingPackages
7465 = new ArrayList<PendingPackage>();
7466
7467 Settings() {
7468 File dataDir = Environment.getDataDirectory();
7469 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007470 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7471 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007472 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007473 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007474 FileUtils.setPermissions(systemDir.toString(),
7475 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7476 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7477 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007478 FileUtils.setPermissions(systemSecureDir.toString(),
7479 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7480 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7481 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007482 mSettingsFilename = new File(systemDir, "packages.xml");
7483 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007484 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007485 }
7486
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007487 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007488 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007489 int pkgFlags, boolean create, boolean add) {
7490 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007491 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007492 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007493 return p;
7494 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007495
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007496 PackageSetting peekPackageLP(String name) {
7497 return mPackages.get(name);
7498 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007499 PackageSetting p = mPackages.get(name);
7500 if (p != null && p.codePath.getPath().equals(codePath)) {
7501 return p;
7502 }
7503 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007504 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007505 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007507 void setInstallStatus(String pkgName, int status) {
7508 PackageSetting p = mPackages.get(pkgName);
7509 if(p != null) {
7510 if(p.getInstallStatus() != status) {
7511 p.setInstallStatus(status);
7512 }
7513 }
7514 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007515
Jacek Surazski65e13172009-04-28 15:26:38 +02007516 void setInstallerPackageName(String pkgName,
7517 String installerPkgName) {
7518 PackageSetting p = mPackages.get(pkgName);
7519 if(p != null) {
7520 p.setInstallerPackageName(installerPkgName);
7521 }
7522 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007523
Jacek Surazski65e13172009-04-28 15:26:38 +02007524 String getInstallerPackageName(String pkgName) {
7525 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007526 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007527 }
7528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007529 int getInstallStatus(String pkgName) {
7530 PackageSetting p = mPackages.get(pkgName);
7531 if(p != null) {
7532 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007533 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007534 return -1;
7535 }
7536
7537 SharedUserSetting getSharedUserLP(String name,
7538 int pkgFlags, boolean create) {
7539 SharedUserSetting s = mSharedUsers.get(name);
7540 if (s == null) {
7541 if (!create) {
7542 return null;
7543 }
7544 s = new SharedUserSetting(name, pkgFlags);
7545 if (MULTIPLE_APPLICATION_UIDS) {
7546 s.userId = newUserIdLP(s);
7547 } else {
7548 s.userId = FIRST_APPLICATION_UID;
7549 }
7550 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7551 // < 0 means we couldn't assign a userid; fall out and return
7552 // s, which is currently null
7553 if (s.userId >= 0) {
7554 mSharedUsers.put(name, s);
7555 }
7556 }
7557
7558 return s;
7559 }
7560
7561 int disableSystemPackageLP(String name) {
7562 PackageSetting p = mPackages.get(name);
7563 if(p == null) {
7564 Log.w(TAG, "Package:"+name+" is not an installed package");
7565 return -1;
7566 }
7567 PackageSetting dp = mDisabledSysPackages.get(name);
7568 // always make sure the system package code and resource paths dont change
7569 if(dp == null) {
7570 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7571 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7572 }
7573 mDisabledSysPackages.put(name, p);
7574 }
7575 return removePackageLP(name);
7576 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007578 PackageSetting enableSystemPackageLP(String name) {
7579 PackageSetting p = mDisabledSysPackages.get(name);
7580 if(p == null) {
7581 Log.w(TAG, "Package:"+name+" is not disabled");
7582 return null;
7583 }
7584 // Reset flag in ApplicationInfo object
7585 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7586 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7587 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007588 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007589 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007590 mDisabledSysPackages.remove(name);
7591 return ret;
7592 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007593
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007594 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007595 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007596 PackageSetting p = mPackages.get(name);
7597 if (p != null) {
7598 if (p.userId == uid) {
7599 return p;
7600 }
7601 reportSettingsProblem(Log.ERROR,
7602 "Adding duplicate package, keeping first: " + name);
7603 return null;
7604 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007605 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007606 p.userId = uid;
7607 if (addUserIdLP(uid, p, name)) {
7608 mPackages.put(name, p);
7609 return p;
7610 }
7611 return null;
7612 }
7613
7614 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7615 SharedUserSetting s = mSharedUsers.get(name);
7616 if (s != null) {
7617 if (s.userId == uid) {
7618 return s;
7619 }
7620 reportSettingsProblem(Log.ERROR,
7621 "Adding duplicate shared user, keeping first: " + name);
7622 return null;
7623 }
7624 s = new SharedUserSetting(name, pkgFlags);
7625 s.userId = uid;
7626 if (addUserIdLP(uid, s, name)) {
7627 mSharedUsers.put(name, s);
7628 return s;
7629 }
7630 return null;
7631 }
7632
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007633 // Transfer ownership of permissions from one package to another.
7634 private void transferPermissions(String origPkg, String newPkg) {
7635 // Transfer ownership of permissions to the new package.
7636 for (int i=0; i<2; i++) {
7637 HashMap<String, BasePermission> permissions =
7638 i == 0 ? mPermissionTrees : mPermissions;
7639 for (BasePermission bp : permissions.values()) {
7640 if (origPkg.equals(bp.sourcePackage)) {
7641 if (DEBUG_UPGRADE) Log.v(TAG,
7642 "Moving permission " + bp.name
7643 + " from pkg " + bp.sourcePackage
7644 + " to " + newPkg);
7645 bp.sourcePackage = newPkg;
7646 bp.perm = null;
7647 if (bp.pendingInfo != null) {
7648 bp.sourcePackage = newPkg;
7649 }
7650 bp.uid = 0;
7651 bp.gids = null;
7652 }
7653 }
7654 }
7655 }
7656
7657 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007658 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007659 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007660 PackageSetting p = mPackages.get(name);
7661 if (p != null) {
7662 if (!p.codePath.equals(codePath)) {
7663 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007664 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007665 // This is an updated system app with versions in both system
7666 // and data partition. Just let the most recent version
7667 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007668 Log.w(TAG, "Trying to update system app code path from " +
7669 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007670 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007671 // Just a change in the code path is not an issue, but
7672 // let's log a message about it.
7673 Log.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007674 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007675 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007676 }
7677 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007678 reportSettingsProblem(Log.WARN,
7679 "Package " + name + " shared user changed from "
7680 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7681 + " to "
7682 + (sharedUser != null ? sharedUser.name : "<nothing>")
7683 + "; replacing with new");
7684 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007685 } else {
7686 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7687 // If what we are scanning is a system package, then
7688 // make it so, regardless of whether it was previously
7689 // installed only in the data partition.
7690 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007692 }
7693 }
7694 if (p == null) {
7695 // Create a new PackageSettings entry. this can end up here because
7696 // of code path mismatch or user id mismatch of an updated system partition
7697 if (!create) {
7698 return null;
7699 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007700 if (origPackage != null) {
7701 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007702 p = new PackageSetting(origPackage.name, name, codePath,
7703 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007704 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
7705 + " is adopting original package " + origPackage.name);
7706 p.copyFrom(origPackage);
7707 p.sharedUser = origPackage.sharedUser;
7708 p.userId = origPackage.userId;
7709 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007710 mRenamedPackages.put(name, origPackage.name);
7711 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007712 // Update new package state.
7713 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007714 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007715 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007716 p.setTimeStamp(codePath.lastModified());
7717 p.sharedUser = sharedUser;
7718 if (sharedUser != null) {
7719 p.userId = sharedUser.userId;
7720 } else if (MULTIPLE_APPLICATION_UIDS) {
7721 // Clone the setting here for disabled system packages
7722 PackageSetting dis = mDisabledSysPackages.get(name);
7723 if (dis != null) {
7724 // For disabled packages a new setting is created
7725 // from the existing user id. This still has to be
7726 // added to list of user id's
7727 // Copy signatures from previous setting
7728 if (dis.signatures.mSignatures != null) {
7729 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
7730 }
7731 p.userId = dis.userId;
7732 // Clone permissions
7733 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
7734 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
7735 // Clone component info
7736 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
7737 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
7738 // Add new setting to list of user ids
7739 addUserIdLP(p.userId, p, name);
7740 } else {
7741 // Assign new user id
7742 p.userId = newUserIdLP(p);
7743 }
7744 } else {
7745 p.userId = FIRST_APPLICATION_UID;
7746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007747 }
7748 if (p.userId < 0) {
7749 reportSettingsProblem(Log.WARN,
7750 "Package " + name + " could not be assigned a valid uid");
7751 return null;
7752 }
7753 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007754 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007755 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007756 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007757 }
7758 }
7759 return p;
7760 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007761
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007762 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007763 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007764 String codePath = pkg.applicationInfo.sourceDir;
7765 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007766 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007767 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007768 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007769 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007770 p.codePath = new File(codePath);
7771 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007772 }
7773 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007774 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007775 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007776 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007777 p.resourcePath = new File(resourcePath);
7778 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007779 }
7780 // Update version code if needed
7781 if (pkg.mVersionCode != p.versionCode) {
7782 p.versionCode = pkg.mVersionCode;
7783 }
7784 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
7785 }
7786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007787 // Utility method that adds a PackageSetting to mPackages and
7788 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007789 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007790 SharedUserSetting sharedUser) {
7791 mPackages.put(name, p);
7792 if (sharedUser != null) {
7793 if (p.sharedUser != null && p.sharedUser != sharedUser) {
7794 reportSettingsProblem(Log.ERROR,
7795 "Package " + p.name + " was user "
7796 + p.sharedUser + " but is now " + sharedUser
7797 + "; I am not changing its files so it will probably fail!");
7798 p.sharedUser.packages.remove(p);
7799 } else if (p.userId != sharedUser.userId) {
7800 reportSettingsProblem(Log.ERROR,
7801 "Package " + p.name + " was user id " + p.userId
7802 + " but is now user " + sharedUser
7803 + " with id " + sharedUser.userId
7804 + "; I am not changing its files so it will probably fail!");
7805 }
7806
7807 sharedUser.packages.add(p);
7808 p.sharedUser = sharedUser;
7809 p.userId = sharedUser.userId;
7810 }
7811 }
7812
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007813 /*
7814 * Update the shared user setting when a package using
7815 * specifying the shared user id is removed. The gids
7816 * associated with each permission of the deleted package
7817 * are removed from the shared user's gid list only if its
7818 * not in use by other permissions of packages in the
7819 * shared user setting.
7820 */
7821 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007822 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
7823 Log.i(TAG, "Trying to update info for null package. Just ignoring");
7824 return;
7825 }
7826 // No sharedUserId
7827 if (deletedPs.sharedUser == null) {
7828 return;
7829 }
7830 SharedUserSetting sus = deletedPs.sharedUser;
7831 // Update permissions
7832 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
7833 boolean used = false;
7834 if (!sus.grantedPermissions.contains (eachPerm)) {
7835 continue;
7836 }
7837 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007838 if (pkg.pkg != null &&
7839 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
7840 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007841 used = true;
7842 break;
7843 }
7844 }
7845 if (!used) {
7846 // can safely delete this permission from list
7847 sus.grantedPermissions.remove(eachPerm);
7848 sus.loadedPermissions.remove(eachPerm);
7849 }
7850 }
7851 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007852 int newGids[] = globalGids;
7853 for (String eachPerm : sus.grantedPermissions) {
7854 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007855 if (bp != null) {
7856 newGids = appendInts(newGids, bp.gids);
7857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007858 }
7859 sus.gids = newGids;
7860 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007862 private int removePackageLP(String name) {
7863 PackageSetting p = mPackages.get(name);
7864 if (p != null) {
7865 mPackages.remove(name);
7866 if (p.sharedUser != null) {
7867 p.sharedUser.packages.remove(p);
7868 if (p.sharedUser.packages.size() == 0) {
7869 mSharedUsers.remove(p.sharedUser.name);
7870 removeUserIdLP(p.sharedUser.userId);
7871 return p.sharedUser.userId;
7872 }
7873 } else {
7874 removeUserIdLP(p.userId);
7875 return p.userId;
7876 }
7877 }
7878 return -1;
7879 }
7880
7881 private boolean addUserIdLP(int uid, Object obj, Object name) {
7882 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
7883 return false;
7884 }
7885
7886 if (uid >= FIRST_APPLICATION_UID) {
7887 int N = mUserIds.size();
7888 final int index = uid - FIRST_APPLICATION_UID;
7889 while (index >= N) {
7890 mUserIds.add(null);
7891 N++;
7892 }
7893 if (mUserIds.get(index) != null) {
7894 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007895 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007896 + " name=" + name);
7897 return false;
7898 }
7899 mUserIds.set(index, obj);
7900 } else {
7901 if (mOtherUserIds.get(uid) != null) {
7902 reportSettingsProblem(Log.ERROR,
7903 "Adding duplicate shared id: " + uid
7904 + " name=" + name);
7905 return false;
7906 }
7907 mOtherUserIds.put(uid, obj);
7908 }
7909 return true;
7910 }
7911
7912 public Object getUserIdLP(int uid) {
7913 if (uid >= FIRST_APPLICATION_UID) {
7914 int N = mUserIds.size();
7915 final int index = uid - FIRST_APPLICATION_UID;
7916 return index < N ? mUserIds.get(index) : null;
7917 } else {
7918 return mOtherUserIds.get(uid);
7919 }
7920 }
7921
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007922 private Set<String> findPackagesWithFlag(int flag) {
7923 Set<String> ret = new HashSet<String>();
7924 for (PackageSetting ps : mPackages.values()) {
7925 // Has to match atleast all the flag bits set on flag
7926 if ((ps.pkgFlags & flag) == flag) {
7927 ret.add(ps.name);
7928 }
7929 }
7930 return ret;
7931 }
7932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007933 private void removeUserIdLP(int uid) {
7934 if (uid >= FIRST_APPLICATION_UID) {
7935 int N = mUserIds.size();
7936 final int index = uid - FIRST_APPLICATION_UID;
7937 if (index < N) mUserIds.set(index, null);
7938 } else {
7939 mOtherUserIds.remove(uid);
7940 }
7941 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007943 void writeLP() {
7944 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
7945
7946 // Keep the old settings around until we know the new ones have
7947 // been successfully written.
7948 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007949 // Presence of backup settings file indicates that we failed
7950 // to persist settings earlier. So preserve the older
7951 // backup for future reference since the current settings
7952 // might have been corrupted.
7953 if (!mBackupSettingsFilename.exists()) {
7954 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
7955 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
7956 return;
7957 }
7958 } else {
7959 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07007960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007961 }
7962
7963 mPastSignatures.clear();
7964
7965 try {
7966 FileOutputStream str = new FileOutputStream(mSettingsFilename);
7967
7968 //XmlSerializer serializer = XmlUtils.serializerInstance();
7969 XmlSerializer serializer = new FastXmlSerializer();
7970 serializer.setOutput(str, "utf-8");
7971 serializer.startDocument(null, true);
7972 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
7973
7974 serializer.startTag(null, "packages");
7975
7976 serializer.startTag(null, "permission-trees");
7977 for (BasePermission bp : mPermissionTrees.values()) {
7978 writePermission(serializer, bp);
7979 }
7980 serializer.endTag(null, "permission-trees");
7981
7982 serializer.startTag(null, "permissions");
7983 for (BasePermission bp : mPermissions.values()) {
7984 writePermission(serializer, bp);
7985 }
7986 serializer.endTag(null, "permissions");
7987
7988 for (PackageSetting pkg : mPackages.values()) {
7989 writePackage(serializer, pkg);
7990 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007992 for (PackageSetting pkg : mDisabledSysPackages.values()) {
7993 writeDisabledSysPackage(serializer, pkg);
7994 }
7995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007996 serializer.startTag(null, "preferred-activities");
7997 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
7998 serializer.startTag(null, "item");
7999 pa.writeToXml(serializer);
8000 serializer.endTag(null, "item");
8001 }
8002 serializer.endTag(null, "preferred-activities");
8003
8004 for (SharedUserSetting usr : mSharedUsers.values()) {
8005 serializer.startTag(null, "shared-user");
8006 serializer.attribute(null, "name", usr.name);
8007 serializer.attribute(null, "userId",
8008 Integer.toString(usr.userId));
8009 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8010 serializer.startTag(null, "perms");
8011 for (String name : usr.grantedPermissions) {
8012 serializer.startTag(null, "item");
8013 serializer.attribute(null, "name", name);
8014 serializer.endTag(null, "item");
8015 }
8016 serializer.endTag(null, "perms");
8017 serializer.endTag(null, "shared-user");
8018 }
8019
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008020 if (mPackagesToBeCleaned.size() > 0) {
8021 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8022 serializer.startTag(null, "cleaning-package");
8023 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8024 serializer.endTag(null, "cleaning-package");
8025 }
8026 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008027
8028 if (mRenamedPackages.size() > 0) {
8029 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8030 serializer.startTag(null, "renamed-package");
8031 serializer.attribute(null, "new", e.getKey());
8032 serializer.attribute(null, "old", e.getValue());
8033 serializer.endTag(null, "renamed-package");
8034 }
8035 }
8036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008037 serializer.endTag(null, "packages");
8038
8039 serializer.endDocument();
8040
8041 str.flush();
8042 str.close();
8043
8044 // New settings successfully written, old ones are no longer
8045 // needed.
8046 mBackupSettingsFilename.delete();
8047 FileUtils.setPermissions(mSettingsFilename.toString(),
8048 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8049 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8050 |FileUtils.S_IROTH,
8051 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008052
8053 // Write package list file now, use a JournaledFile.
8054 //
8055 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8056 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8057
8058 str = new FileOutputStream(journal.chooseForWrite());
8059 try {
8060 StringBuilder sb = new StringBuilder();
8061 for (PackageSetting pkg : mPackages.values()) {
8062 ApplicationInfo ai = pkg.pkg.applicationInfo;
8063 String dataPath = ai.dataDir;
8064 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8065
8066 // Avoid any application that has a space in its path
8067 // or that is handled by the system.
8068 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8069 continue;
8070
8071 // we store on each line the following information for now:
8072 //
8073 // pkgName - package name
8074 // userId - application-specific user id
8075 // debugFlag - 0 or 1 if the package is debuggable.
8076 // dataPath - path to package's data path
8077 //
8078 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8079 //
8080 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8081 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8082 // system/core/run-as/run-as.c
8083 //
8084 sb.setLength(0);
8085 sb.append(ai.packageName);
8086 sb.append(" ");
8087 sb.append((int)ai.uid);
8088 sb.append(isDebug ? " 1 " : " 0 ");
8089 sb.append(dataPath);
8090 sb.append("\n");
8091 str.write(sb.toString().getBytes());
8092 }
8093 str.flush();
8094 str.close();
8095 journal.commit();
8096 }
8097 catch (Exception e) {
8098 journal.rollback();
8099 }
8100
8101 FileUtils.setPermissions(mPackageListFilename.toString(),
8102 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8103 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8104 |FileUtils.S_IROTH,
8105 -1, -1);
8106
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008107 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008108
8109 } catch(XmlPullParserException e) {
8110 Log.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 -08008111 } catch(java.io.IOException e) {
8112 Log.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 -08008113 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008114 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008115 if (mSettingsFilename.exists()) {
8116 if (!mSettingsFilename.delete()) {
8117 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8118 }
8119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008120 //Debug.stopMethodTracing();
8121 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008122
8123 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008124 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008125 serializer.startTag(null, "updated-package");
8126 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008127 if (pkg.realName != null) {
8128 serializer.attribute(null, "realName", pkg.realName);
8129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008130 serializer.attribute(null, "codePath", pkg.codePathString);
8131 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008132 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008133 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8134 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8135 }
8136 if (pkg.sharedUser == null) {
8137 serializer.attribute(null, "userId",
8138 Integer.toString(pkg.userId));
8139 } else {
8140 serializer.attribute(null, "sharedUserId",
8141 Integer.toString(pkg.userId));
8142 }
8143 serializer.startTag(null, "perms");
8144 if (pkg.sharedUser == null) {
8145 // If this is a shared user, the permissions will
8146 // be written there. We still need to write an
8147 // empty permissions list so permissionsFixed will
8148 // be set.
8149 for (final String name : pkg.grantedPermissions) {
8150 BasePermission bp = mPermissions.get(name);
8151 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
8152 // We only need to write signature or system permissions but this wont
8153 // match the semantics of grantedPermissions. So write all permissions.
8154 serializer.startTag(null, "item");
8155 serializer.attribute(null, "name", name);
8156 serializer.endTag(null, "item");
8157 }
8158 }
8159 }
8160 serializer.endTag(null, "perms");
8161 serializer.endTag(null, "updated-package");
8162 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008163
8164 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008165 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008166 serializer.startTag(null, "package");
8167 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008168 if (pkg.realName != null) {
8169 serializer.attribute(null, "realName", pkg.realName);
8170 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008171 serializer.attribute(null, "codePath", pkg.codePathString);
8172 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8173 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8174 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008175 serializer.attribute(null, "flags",
8176 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008177 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008178 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008179 if (pkg.sharedUser == null) {
8180 serializer.attribute(null, "userId",
8181 Integer.toString(pkg.userId));
8182 } else {
8183 serializer.attribute(null, "sharedUserId",
8184 Integer.toString(pkg.userId));
8185 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008186 if (pkg.uidError) {
8187 serializer.attribute(null, "uidError", "true");
8188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008189 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8190 serializer.attribute(null, "enabled",
8191 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8192 ? "true" : "false");
8193 }
8194 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8195 serializer.attribute(null, "installStatus", "false");
8196 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008197 if (pkg.installerPackageName != null) {
8198 serializer.attribute(null, "installer", pkg.installerPackageName);
8199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008200 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8201 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8202 serializer.startTag(null, "perms");
8203 if (pkg.sharedUser == null) {
8204 // If this is a shared user, the permissions will
8205 // be written there. We still need to write an
8206 // empty permissions list so permissionsFixed will
8207 // be set.
8208 for (final String name : pkg.grantedPermissions) {
8209 serializer.startTag(null, "item");
8210 serializer.attribute(null, "name", name);
8211 serializer.endTag(null, "item");
8212 }
8213 }
8214 serializer.endTag(null, "perms");
8215 }
8216 if (pkg.disabledComponents.size() > 0) {
8217 serializer.startTag(null, "disabled-components");
8218 for (final String name : pkg.disabledComponents) {
8219 serializer.startTag(null, "item");
8220 serializer.attribute(null, "name", name);
8221 serializer.endTag(null, "item");
8222 }
8223 serializer.endTag(null, "disabled-components");
8224 }
8225 if (pkg.enabledComponents.size() > 0) {
8226 serializer.startTag(null, "enabled-components");
8227 for (final String name : pkg.enabledComponents) {
8228 serializer.startTag(null, "item");
8229 serializer.attribute(null, "name", name);
8230 serializer.endTag(null, "item");
8231 }
8232 serializer.endTag(null, "enabled-components");
8233 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008235 serializer.endTag(null, "package");
8236 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008238 void writePermission(XmlSerializer serializer, BasePermission bp)
8239 throws XmlPullParserException, java.io.IOException {
8240 if (bp.type != BasePermission.TYPE_BUILTIN
8241 && bp.sourcePackage != null) {
8242 serializer.startTag(null, "item");
8243 serializer.attribute(null, "name", bp.name);
8244 serializer.attribute(null, "package", bp.sourcePackage);
8245 if (DEBUG_SETTINGS) Log.v(TAG,
8246 "Writing perm: name=" + bp.name + " type=" + bp.type);
8247 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8248 PermissionInfo pi = bp.perm != null ? bp.perm.info
8249 : bp.pendingInfo;
8250 if (pi != null) {
8251 serializer.attribute(null, "type", "dynamic");
8252 if (pi.icon != 0) {
8253 serializer.attribute(null, "icon",
8254 Integer.toString(pi.icon));
8255 }
8256 if (pi.nonLocalizedLabel != null) {
8257 serializer.attribute(null, "label",
8258 pi.nonLocalizedLabel.toString());
8259 }
8260 if (pi.protectionLevel !=
8261 PermissionInfo.PROTECTION_NORMAL) {
8262 serializer.attribute(null, "protection",
8263 Integer.toString(pi.protectionLevel));
8264 }
8265 }
8266 }
8267 serializer.endTag(null, "item");
8268 }
8269 }
8270
8271 String getReadMessagesLP() {
8272 return mReadMessages.toString();
8273 }
8274
Oscar Montemayora8529f62009-11-18 10:14:20 -08008275 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008276 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8277 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008278 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008279 while(its.hasNext()) {
8280 String key = its.next();
8281 PackageSetting ps = mPackages.get(key);
8282 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008283 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008284 }
8285 }
8286 return ret;
8287 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008289 boolean readLP() {
8290 FileInputStream str = null;
8291 if (mBackupSettingsFilename.exists()) {
8292 try {
8293 str = new FileInputStream(mBackupSettingsFilename);
8294 mReadMessages.append("Reading from backup settings file\n");
8295 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008296 if (mSettingsFilename.exists()) {
8297 // If both the backup and settings file exist, we
8298 // ignore the settings since it might have been
8299 // corrupted.
8300 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
8301 mSettingsFilename.delete();
8302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008303 } catch (java.io.IOException e) {
8304 // We'll try for the normal settings file.
8305 }
8306 }
8307
8308 mPastSignatures.clear();
8309
8310 try {
8311 if (str == null) {
8312 if (!mSettingsFilename.exists()) {
8313 mReadMessages.append("No settings file found\n");
8314 Log.i(TAG, "No current settings file!");
8315 return false;
8316 }
8317 str = new FileInputStream(mSettingsFilename);
8318 }
8319 XmlPullParser parser = Xml.newPullParser();
8320 parser.setInput(str, null);
8321
8322 int type;
8323 while ((type=parser.next()) != XmlPullParser.START_TAG
8324 && type != XmlPullParser.END_DOCUMENT) {
8325 ;
8326 }
8327
8328 if (type != XmlPullParser.START_TAG) {
8329 mReadMessages.append("No start tag found in settings file\n");
8330 Log.e(TAG, "No start tag found in package manager settings");
8331 return false;
8332 }
8333
8334 int outerDepth = parser.getDepth();
8335 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8336 && (type != XmlPullParser.END_TAG
8337 || parser.getDepth() > outerDepth)) {
8338 if (type == XmlPullParser.END_TAG
8339 || type == XmlPullParser.TEXT) {
8340 continue;
8341 }
8342
8343 String tagName = parser.getName();
8344 if (tagName.equals("package")) {
8345 readPackageLP(parser);
8346 } else if (tagName.equals("permissions")) {
8347 readPermissionsLP(mPermissions, parser);
8348 } else if (tagName.equals("permission-trees")) {
8349 readPermissionsLP(mPermissionTrees, parser);
8350 } else if (tagName.equals("shared-user")) {
8351 readSharedUserLP(parser);
8352 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008353 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008354 } else if (tagName.equals("preferred-activities")) {
8355 readPreferredActivitiesLP(parser);
8356 } else if(tagName.equals("updated-package")) {
8357 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008358 } else if (tagName.equals("cleaning-package")) {
8359 String name = parser.getAttributeValue(null, "name");
8360 if (name != null) {
8361 mPackagesToBeCleaned.add(name);
8362 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008363 } else if (tagName.equals("renamed-package")) {
8364 String nname = parser.getAttributeValue(null, "new");
8365 String oname = parser.getAttributeValue(null, "old");
8366 if (nname != null && oname != null) {
8367 mRenamedPackages.put(nname, oname);
8368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008369 } else {
8370 Log.w(TAG, "Unknown element under <packages>: "
8371 + parser.getName());
8372 XmlUtils.skipCurrentTag(parser);
8373 }
8374 }
8375
8376 str.close();
8377
8378 } catch(XmlPullParserException e) {
8379 mReadMessages.append("Error reading: " + e.toString());
8380 Log.e(TAG, "Error reading package manager settings", e);
8381
8382 } catch(java.io.IOException e) {
8383 mReadMessages.append("Error reading: " + e.toString());
8384 Log.e(TAG, "Error reading package manager settings", e);
8385
8386 }
8387
8388 int N = mPendingPackages.size();
8389 for (int i=0; i<N; i++) {
8390 final PendingPackage pp = mPendingPackages.get(i);
8391 Object idObj = getUserIdLP(pp.sharedId);
8392 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008393 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008394 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008395 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008396 if (p == null) {
8397 Log.w(TAG, "Unable to create application package for "
8398 + pp.name);
8399 continue;
8400 }
8401 p.copyFrom(pp);
8402 } else if (idObj != null) {
8403 String msg = "Bad package setting: package " + pp.name
8404 + " has shared uid " + pp.sharedId
8405 + " that is not a shared uid\n";
8406 mReadMessages.append(msg);
8407 Log.e(TAG, msg);
8408 } else {
8409 String msg = "Bad package setting: package " + pp.name
8410 + " has shared uid " + pp.sharedId
8411 + " that is not defined\n";
8412 mReadMessages.append(msg);
8413 Log.e(TAG, msg);
8414 }
8415 }
8416 mPendingPackages.clear();
8417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008418 mReadMessages.append("Read completed successfully: "
8419 + mPackages.size() + " packages, "
8420 + mSharedUsers.size() + " shared uids\n");
8421
8422 return true;
8423 }
8424
8425 private int readInt(XmlPullParser parser, String ns, String name,
8426 int defValue) {
8427 String v = parser.getAttributeValue(ns, name);
8428 try {
8429 if (v == null) {
8430 return defValue;
8431 }
8432 return Integer.parseInt(v);
8433 } catch (NumberFormatException e) {
8434 reportSettingsProblem(Log.WARN,
8435 "Error in package manager settings: attribute " +
8436 name + " has bad integer value " + v + " at "
8437 + parser.getPositionDescription());
8438 }
8439 return defValue;
8440 }
8441
8442 private void readPermissionsLP(HashMap<String, BasePermission> out,
8443 XmlPullParser parser)
8444 throws IOException, XmlPullParserException {
8445 int outerDepth = parser.getDepth();
8446 int type;
8447 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8448 && (type != XmlPullParser.END_TAG
8449 || parser.getDepth() > outerDepth)) {
8450 if (type == XmlPullParser.END_TAG
8451 || type == XmlPullParser.TEXT) {
8452 continue;
8453 }
8454
8455 String tagName = parser.getName();
8456 if (tagName.equals("item")) {
8457 String name = parser.getAttributeValue(null, "name");
8458 String sourcePackage = parser.getAttributeValue(null, "package");
8459 String ptype = parser.getAttributeValue(null, "type");
8460 if (name != null && sourcePackage != null) {
8461 boolean dynamic = "dynamic".equals(ptype);
8462 BasePermission bp = new BasePermission(name, sourcePackage,
8463 dynamic
8464 ? BasePermission.TYPE_DYNAMIC
8465 : BasePermission.TYPE_NORMAL);
8466 if (dynamic) {
8467 PermissionInfo pi = new PermissionInfo();
8468 pi.packageName = sourcePackage.intern();
8469 pi.name = name.intern();
8470 pi.icon = readInt(parser, null, "icon", 0);
8471 pi.nonLocalizedLabel = parser.getAttributeValue(
8472 null, "label");
8473 pi.protectionLevel = readInt(parser, null, "protection",
8474 PermissionInfo.PROTECTION_NORMAL);
8475 bp.pendingInfo = pi;
8476 }
8477 out.put(bp.name, bp);
8478 } else {
8479 reportSettingsProblem(Log.WARN,
8480 "Error in package manager settings: permissions has"
8481 + " no name at " + parser.getPositionDescription());
8482 }
8483 } else {
8484 reportSettingsProblem(Log.WARN,
8485 "Unknown element reading permissions: "
8486 + parser.getName() + " at "
8487 + parser.getPositionDescription());
8488 }
8489 XmlUtils.skipCurrentTag(parser);
8490 }
8491 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008493 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008494 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008495 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008496 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008497 String codePathStr = parser.getAttributeValue(null, "codePath");
8498 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008499 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008500 resourcePathStr = codePathStr;
8501 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008502 String version = parser.getAttributeValue(null, "version");
8503 int versionCode = 0;
8504 if (version != null) {
8505 try {
8506 versionCode = Integer.parseInt(version);
8507 } catch (NumberFormatException e) {
8508 }
8509 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008511 int pkgFlags = 0;
8512 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008513 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008514 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008515 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008516 String timeStampStr = parser.getAttributeValue(null, "ts");
8517 if (timeStampStr != null) {
8518 try {
8519 long timeStamp = Long.parseLong(timeStampStr);
8520 ps.setTimeStamp(timeStamp, timeStampStr);
8521 } catch (NumberFormatException e) {
8522 }
8523 }
8524 String idStr = parser.getAttributeValue(null, "userId");
8525 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8526 if(ps.userId <= 0) {
8527 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8528 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8529 }
8530 int outerDepth = parser.getDepth();
8531 int type;
8532 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8533 && (type != XmlPullParser.END_TAG
8534 || parser.getDepth() > outerDepth)) {
8535 if (type == XmlPullParser.END_TAG
8536 || type == XmlPullParser.TEXT) {
8537 continue;
8538 }
8539
8540 String tagName = parser.getName();
8541 if (tagName.equals("perms")) {
8542 readGrantedPermissionsLP(parser,
8543 ps.grantedPermissions);
8544 } else {
8545 reportSettingsProblem(Log.WARN,
8546 "Unknown element under <updated-package>: "
8547 + parser.getName());
8548 XmlUtils.skipCurrentTag(parser);
8549 }
8550 }
8551 mDisabledSysPackages.put(name, ps);
8552 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008554 private void readPackageLP(XmlPullParser parser)
8555 throws XmlPullParserException, IOException {
8556 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008557 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008558 String idStr = null;
8559 String sharedIdStr = null;
8560 String codePathStr = null;
8561 String resourcePathStr = null;
8562 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008563 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008564 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008565 int pkgFlags = 0;
8566 String timeStampStr;
8567 long timeStamp = 0;
8568 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008569 String version = null;
8570 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008571 try {
8572 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008573 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008574 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008575 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008576 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8577 codePathStr = parser.getAttributeValue(null, "codePath");
8578 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008579 version = parser.getAttributeValue(null, "version");
8580 if (version != null) {
8581 try {
8582 versionCode = Integer.parseInt(version);
8583 } catch (NumberFormatException e) {
8584 }
8585 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008586 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008587
8588 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008589 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008590 try {
8591 pkgFlags = Integer.parseInt(systemStr);
8592 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008593 }
8594 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008595 // For backward compatibility
8596 systemStr = parser.getAttributeValue(null, "system");
8597 if (systemStr != null) {
8598 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8599 } else {
8600 // Old settings that don't specify system... just treat
8601 // them as system, good enough.
8602 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008604 }
8605 timeStampStr = parser.getAttributeValue(null, "ts");
8606 if (timeStampStr != null) {
8607 try {
8608 timeStamp = Long.parseLong(timeStampStr);
8609 } catch (NumberFormatException e) {
8610 }
8611 }
8612 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8613 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8614 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8615 if (resourcePathStr == null) {
8616 resourcePathStr = codePathStr;
8617 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008618 if (realName != null) {
8619 realName = realName.intern();
8620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008621 if (name == null) {
8622 reportSettingsProblem(Log.WARN,
8623 "Error in package manager settings: <package> has no name at "
8624 + parser.getPositionDescription());
8625 } else if (codePathStr == null) {
8626 reportSettingsProblem(Log.WARN,
8627 "Error in package manager settings: <package> has no codePath at "
8628 + parser.getPositionDescription());
8629 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008630 packageSetting = addPackageLP(name.intern(), realName,
8631 new File(codePathStr), new File(resourcePathStr),
8632 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008633 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8634 + ": userId=" + userId + " pkg=" + packageSetting);
8635 if (packageSetting == null) {
8636 reportSettingsProblem(Log.ERROR,
8637 "Failure adding uid " + userId
8638 + " while parsing settings at "
8639 + parser.getPositionDescription());
8640 } else {
8641 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8642 }
8643 } else if (sharedIdStr != null) {
8644 userId = sharedIdStr != null
8645 ? Integer.parseInt(sharedIdStr) : 0;
8646 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008647 packageSetting = new PendingPackage(name.intern(), realName,
8648 new File(codePathStr), new File(resourcePathStr),
8649 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008650 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8651 mPendingPackages.add((PendingPackage) packageSetting);
8652 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8653 + ": sharedUserId=" + userId + " pkg="
8654 + packageSetting);
8655 } else {
8656 reportSettingsProblem(Log.WARN,
8657 "Error in package manager settings: package "
8658 + name + " has bad sharedId " + sharedIdStr
8659 + " at " + parser.getPositionDescription());
8660 }
8661 } else {
8662 reportSettingsProblem(Log.WARN,
8663 "Error in package manager settings: package "
8664 + name + " has bad userId " + idStr + " at "
8665 + parser.getPositionDescription());
8666 }
8667 } catch (NumberFormatException e) {
8668 reportSettingsProblem(Log.WARN,
8669 "Error in package manager settings: package "
8670 + name + " has bad userId " + idStr + " at "
8671 + parser.getPositionDescription());
8672 }
8673 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008674 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008675 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008676 final String enabledStr = parser.getAttributeValue(null, "enabled");
8677 if (enabledStr != null) {
8678 if (enabledStr.equalsIgnoreCase("true")) {
8679 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8680 } else if (enabledStr.equalsIgnoreCase("false")) {
8681 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
8682 } else if (enabledStr.equalsIgnoreCase("default")) {
8683 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8684 } else {
8685 reportSettingsProblem(Log.WARN,
8686 "Error in package manager settings: package "
8687 + name + " has bad enabled value: " + idStr
8688 + " at " + parser.getPositionDescription());
8689 }
8690 } else {
8691 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8692 }
8693 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
8694 if (installStatusStr != null) {
8695 if (installStatusStr.equalsIgnoreCase("false")) {
8696 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
8697 } else {
8698 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
8699 }
8700 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008702 int outerDepth = parser.getDepth();
8703 int type;
8704 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8705 && (type != XmlPullParser.END_TAG
8706 || parser.getDepth() > outerDepth)) {
8707 if (type == XmlPullParser.END_TAG
8708 || type == XmlPullParser.TEXT) {
8709 continue;
8710 }
8711
8712 String tagName = parser.getName();
8713 if (tagName.equals("disabled-components")) {
8714 readDisabledComponentsLP(packageSetting, parser);
8715 } else if (tagName.equals("enabled-components")) {
8716 readEnabledComponentsLP(packageSetting, parser);
8717 } else if (tagName.equals("sigs")) {
8718 packageSetting.signatures.readXml(parser, mPastSignatures);
8719 } else if (tagName.equals("perms")) {
8720 readGrantedPermissionsLP(parser,
8721 packageSetting.loadedPermissions);
8722 packageSetting.permissionsFixed = true;
8723 } else {
8724 reportSettingsProblem(Log.WARN,
8725 "Unknown element under <package>: "
8726 + parser.getName());
8727 XmlUtils.skipCurrentTag(parser);
8728 }
8729 }
8730 } else {
8731 XmlUtils.skipCurrentTag(parser);
8732 }
8733 }
8734
8735 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
8736 XmlPullParser parser)
8737 throws IOException, XmlPullParserException {
8738 int outerDepth = parser.getDepth();
8739 int type;
8740 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8741 && (type != XmlPullParser.END_TAG
8742 || parser.getDepth() > outerDepth)) {
8743 if (type == XmlPullParser.END_TAG
8744 || type == XmlPullParser.TEXT) {
8745 continue;
8746 }
8747
8748 String tagName = parser.getName();
8749 if (tagName.equals("item")) {
8750 String name = parser.getAttributeValue(null, "name");
8751 if (name != null) {
8752 packageSetting.disabledComponents.add(name.intern());
8753 } else {
8754 reportSettingsProblem(Log.WARN,
8755 "Error in package manager settings: <disabled-components> has"
8756 + " no name at " + parser.getPositionDescription());
8757 }
8758 } else {
8759 reportSettingsProblem(Log.WARN,
8760 "Unknown element under <disabled-components>: "
8761 + parser.getName());
8762 }
8763 XmlUtils.skipCurrentTag(parser);
8764 }
8765 }
8766
8767 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
8768 XmlPullParser parser)
8769 throws IOException, XmlPullParserException {
8770 int outerDepth = parser.getDepth();
8771 int type;
8772 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8773 && (type != XmlPullParser.END_TAG
8774 || parser.getDepth() > outerDepth)) {
8775 if (type == XmlPullParser.END_TAG
8776 || type == XmlPullParser.TEXT) {
8777 continue;
8778 }
8779
8780 String tagName = parser.getName();
8781 if (tagName.equals("item")) {
8782 String name = parser.getAttributeValue(null, "name");
8783 if (name != null) {
8784 packageSetting.enabledComponents.add(name.intern());
8785 } else {
8786 reportSettingsProblem(Log.WARN,
8787 "Error in package manager settings: <enabled-components> has"
8788 + " no name at " + parser.getPositionDescription());
8789 }
8790 } else {
8791 reportSettingsProblem(Log.WARN,
8792 "Unknown element under <enabled-components>: "
8793 + parser.getName());
8794 }
8795 XmlUtils.skipCurrentTag(parser);
8796 }
8797 }
8798
8799 private void readSharedUserLP(XmlPullParser parser)
8800 throws XmlPullParserException, IOException {
8801 String name = null;
8802 String idStr = null;
8803 int pkgFlags = 0;
8804 SharedUserSetting su = null;
8805 try {
8806 name = parser.getAttributeValue(null, "name");
8807 idStr = parser.getAttributeValue(null, "userId");
8808 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8809 if ("true".equals(parser.getAttributeValue(null, "system"))) {
8810 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8811 }
8812 if (name == null) {
8813 reportSettingsProblem(Log.WARN,
8814 "Error in package manager settings: <shared-user> has no name at "
8815 + parser.getPositionDescription());
8816 } else if (userId == 0) {
8817 reportSettingsProblem(Log.WARN,
8818 "Error in package manager settings: shared-user "
8819 + name + " has bad userId " + idStr + " at "
8820 + parser.getPositionDescription());
8821 } else {
8822 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
8823 reportSettingsProblem(Log.ERROR,
8824 "Occurred while parsing settings at "
8825 + parser.getPositionDescription());
8826 }
8827 }
8828 } catch (NumberFormatException e) {
8829 reportSettingsProblem(Log.WARN,
8830 "Error in package manager settings: package "
8831 + name + " has bad userId " + idStr + " at "
8832 + parser.getPositionDescription());
8833 };
8834
8835 if (su != null) {
8836 int outerDepth = parser.getDepth();
8837 int type;
8838 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8839 && (type != XmlPullParser.END_TAG
8840 || parser.getDepth() > outerDepth)) {
8841 if (type == XmlPullParser.END_TAG
8842 || type == XmlPullParser.TEXT) {
8843 continue;
8844 }
8845
8846 String tagName = parser.getName();
8847 if (tagName.equals("sigs")) {
8848 su.signatures.readXml(parser, mPastSignatures);
8849 } else if (tagName.equals("perms")) {
8850 readGrantedPermissionsLP(parser, su.loadedPermissions);
8851 } else {
8852 reportSettingsProblem(Log.WARN,
8853 "Unknown element under <shared-user>: "
8854 + parser.getName());
8855 XmlUtils.skipCurrentTag(parser);
8856 }
8857 }
8858
8859 } else {
8860 XmlUtils.skipCurrentTag(parser);
8861 }
8862 }
8863
8864 private void readGrantedPermissionsLP(XmlPullParser parser,
8865 HashSet<String> outPerms) throws IOException, XmlPullParserException {
8866 int outerDepth = parser.getDepth();
8867 int type;
8868 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8869 && (type != XmlPullParser.END_TAG
8870 || parser.getDepth() > outerDepth)) {
8871 if (type == XmlPullParser.END_TAG
8872 || type == XmlPullParser.TEXT) {
8873 continue;
8874 }
8875
8876 String tagName = parser.getName();
8877 if (tagName.equals("item")) {
8878 String name = parser.getAttributeValue(null, "name");
8879 if (name != null) {
8880 outPerms.add(name.intern());
8881 } else {
8882 reportSettingsProblem(Log.WARN,
8883 "Error in package manager settings: <perms> has"
8884 + " no name at " + parser.getPositionDescription());
8885 }
8886 } else {
8887 reportSettingsProblem(Log.WARN,
8888 "Unknown element under <perms>: "
8889 + parser.getName());
8890 }
8891 XmlUtils.skipCurrentTag(parser);
8892 }
8893 }
8894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008895 private void readPreferredActivitiesLP(XmlPullParser parser)
8896 throws XmlPullParserException, IOException {
8897 int outerDepth = parser.getDepth();
8898 int type;
8899 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8900 && (type != XmlPullParser.END_TAG
8901 || parser.getDepth() > outerDepth)) {
8902 if (type == XmlPullParser.END_TAG
8903 || type == XmlPullParser.TEXT) {
8904 continue;
8905 }
8906
8907 String tagName = parser.getName();
8908 if (tagName.equals("item")) {
8909 PreferredActivity pa = new PreferredActivity(parser);
8910 if (pa.mParseError == null) {
8911 mPreferredActivities.addFilter(pa);
8912 } else {
8913 reportSettingsProblem(Log.WARN,
8914 "Error in package manager settings: <preferred-activity> "
8915 + pa.mParseError + " at "
8916 + parser.getPositionDescription());
8917 }
8918 } else {
8919 reportSettingsProblem(Log.WARN,
8920 "Unknown element under <preferred-activities>: "
8921 + parser.getName());
8922 XmlUtils.skipCurrentTag(parser);
8923 }
8924 }
8925 }
8926
8927 // Returns -1 if we could not find an available UserId to assign
8928 private int newUserIdLP(Object obj) {
8929 // Let's be stupidly inefficient for now...
8930 final int N = mUserIds.size();
8931 for (int i=0; i<N; i++) {
8932 if (mUserIds.get(i) == null) {
8933 mUserIds.set(i, obj);
8934 return FIRST_APPLICATION_UID + i;
8935 }
8936 }
8937
8938 // None left?
8939 if (N >= MAX_APPLICATION_UIDS) {
8940 return -1;
8941 }
8942
8943 mUserIds.add(obj);
8944 return FIRST_APPLICATION_UID + N;
8945 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008947 public PackageSetting getDisabledSystemPkg(String name) {
8948 synchronized(mPackages) {
8949 PackageSetting ps = mDisabledSysPackages.get(name);
8950 return ps;
8951 }
8952 }
8953
8954 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
8955 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
8956 if (Config.LOGV) {
8957 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
8958 + " componentName = " + componentInfo.name);
8959 Log.v(TAG, "enabledComponents: "
8960 + Arrays.toString(packageSettings.enabledComponents.toArray()));
8961 Log.v(TAG, "disabledComponents: "
8962 + Arrays.toString(packageSettings.disabledComponents.toArray()));
8963 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008964 if (packageSettings == null) {
8965 if (false) {
8966 Log.w(TAG, "WAITING FOR DEBUGGER");
8967 Debug.waitForDebugger();
8968 Log.i(TAG, "We will crash!");
8969 }
8970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008971 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
8972 || ((componentInfo.enabled
8973 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
8974 || (componentInfo.applicationInfo.enabled
8975 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
8976 && !packageSettings.disabledComponents.contains(componentInfo.name))
8977 || packageSettings.enabledComponents.contains(componentInfo.name));
8978 }
8979 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008980
8981 // ------- apps on sdcard specific code -------
8982 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008983 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08008984 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008985 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008986 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008987
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008988 private String getEncryptKey() {
8989 try {
8990 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8991 if (sdEncKey == null) {
8992 sdEncKey = SystemKeyStore.getInstance().
8993 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8994 if (sdEncKey == null) {
8995 Log.e(TAG, "Failed to create encryption keys");
8996 return null;
8997 }
8998 }
8999 return sdEncKey;
9000 } catch (NoSuchAlgorithmException nsae) {
9001 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
9002 return null;
9003 }
9004 }
9005
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009006 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009007 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009008 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009009 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009010 if (list != null) {
9011 int idx = 0;
9012 int idList[] = new int[MAX_CONTAINERS];
9013 boolean neverFound = true;
9014 for (String name : list) {
9015 // Ignore null entries
9016 if (name == null) {
9017 continue;
9018 }
9019 int sidx = name.indexOf(prefix);
9020 if (sidx == -1) {
9021 // Not a temp file. just ignore
9022 continue;
9023 }
9024 String subStr = name.substring(sidx + prefix.length());
9025 idList[idx] = -1;
9026 if (subStr != null) {
9027 try {
9028 int cid = Integer.parseInt(subStr);
9029 idList[idx++] = cid;
9030 neverFound = false;
9031 } catch (NumberFormatException e) {
9032 }
9033 }
9034 }
9035 if (!neverFound) {
9036 // Sort idList
9037 Arrays.sort(idList);
9038 for (int j = 1; j <= idList.length; j++) {
9039 if (idList[j-1] != j) {
9040 tmpIdx = j;
9041 break;
9042 }
9043 }
9044 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009045 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009046 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009047 }
9048
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009049 /*
9050 * Return true if PackageManager does have packages to be updated.
9051 */
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009052 public boolean updateExternalMediaStatus(final boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009053 final boolean ret;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009054 synchronized (mPackages) {
9055 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9056 mediaStatus+", mMediaMounted=" + mMediaMounted);
9057 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009058 return false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009059 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009060 mMediaMounted = mediaStatus;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009061 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_EXTERNAL_STORAGE);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009062 ret = appList != null && appList.size() > 0;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009063 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009064 // Queue up an async operation since the package installation may take a little while.
9065 mHandler.post(new Runnable() {
9066 public void run() {
9067 mHandler.removeCallbacks(this);
9068 updateExternalMediaStatusInner(mediaStatus, ret);
9069 }
9070 });
9071 return ret;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009072 }
9073
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009074 private void updateExternalMediaStatusInner(boolean mediaStatus,
9075 boolean sendUpdateBroadcast) {
9076 // If we are up here that means there are packages to be
9077 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009078 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009079 if (list == null || list.length == 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009080 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009081 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009082
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009083 int uidList[] = new int[list.length];
9084 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009085 HashSet<String> removeCids = new HashSet<String>();
9086 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9087 /*HashMap<String, String> cidPathMap = new HashMap<String, String>();
9088 // Don't hold any locks when getting cache paths
9089 for (String cid : list) {
9090 String cpath = PackageHelper.getSdDir(cid);
9091 if (cpath == null) {
9092 removeCids.add(cid);
9093 } else {
9094 cidPathMap.put(cid, cpath);
9095 }
9096 }*/
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009097 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009098 for (String cid : list) {
9099 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009100 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9101 boolean failed = true;
9102 try {
9103 String pkgName = args.getPackageName();
9104 if (pkgName == null) {
9105 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009106 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009107 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9108 PackageSetting ps = mSettings.mPackages.get(pkgName);
9109 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009110 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009111 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9112 " corresponds to pkg : " + pkgName +
9113 " at code path: " + ps.codePathString);
9114 // We do have a valid package installed on sdcard
9115 processCids.put(args, ps.codePathString);
9116 failed = false;
9117 int uid = ps.userId;
9118 if (uid != -1) {
9119 uidList[num++] = uid;
9120 }
9121 }
9122 } finally {
9123 if (failed) {
9124 // Stale container on sdcard. Just delete
9125 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9126 removeCids.add(cid);
9127 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009128 }
9129 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009130 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009131 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009132 int uidArr[] = null;
9133 if (num > 0) {
9134 // Sort uid list
9135 Arrays.sort(uidList, 0, num);
9136 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009137 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009138 uidArr[0] = uidList[0];
9139 int di = 0;
9140 for (int i = 1; i < num; i++) {
9141 if (uidList[i-1] != uidList[i]) {
9142 uidArr[di++] = uidList[i];
9143 }
9144 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009145 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009146 // Process packages with valid entries.
9147 if (mediaStatus) {
9148 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
9149 loadMediaPackages(processCids, uidArr, sendUpdateBroadcast, removeCids);
9150 startCleaningPackages();
9151 } else {
9152 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
9153 unloadMediaPackages(processCids, uidArr, sendUpdateBroadcast);
9154 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009155 }
9156
9157 private void sendResourcesChangedBroadcast(boolean mediaStatus,
9158 ArrayList<String> pkgList, int uidArr[]) {
9159 int size = pkgList.size();
9160 if (size > 0) {
9161 // Send broadcasts here
9162 Bundle extras = new Bundle();
9163 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9164 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009165 if (uidArr != null) {
9166 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9167 }
9168 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9169 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009170 sendPackageBroadcast(action, null, extras);
9171 }
9172 }
9173
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009174 /*
9175 * Look at potentially valid container ids from processCids
9176 * If package information doesn't match the one on record
9177 * or package scanning fails, the cid is added to list of
9178 * removeCids and cleaned up. Since cleaning up containers
9179 * involves destroying them, we do not want any parse
9180 * references to such stale containers. So force gc's
9181 * to avoid unnecessary crashes.
9182 */
9183 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
9184 int uidArr[], boolean sendUpdateBroadcast,
9185 HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009186 ArrayList<String> pkgList = new ArrayList<String>();
9187 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009188 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009189 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009190 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009191 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9192 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009193 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009194 try {
9195 // Make sure there are no container errors first.
9196 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9197 != PackageManager.INSTALL_SUCCEEDED) {
9198 Log.e(TAG, "Failed to mount cid : " + args.cid +
9199 " when installing from sdcard");
9200 continue;
9201 }
9202 // Check code path here.
9203 if (codePath == null || !codePath.equals(args.getCodePath())) {
9204 Log.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
9205 " does not match one in settings " + codePath);
9206 continue;
9207 }
9208 // Parse package
9209 int parseFlags = PackageParser.PARSE_CHATTY |
9210 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
9211 PackageParser pp = new PackageParser(codePath);
9212 pp.setSeparateProcesses(mSeparateProcesses);
9213 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
9214 codePath, mMetrics, parseFlags);
9215 pp = null;
9216 doGc = true;
9217 // Check for parse errors
9218 if (pkg == null) {
9219 Log.e(TAG, "Parse error when installing install pkg : "
9220 + args.cid + " from " + args.cachePath);
9221 continue;
9222 }
9223 setApplicationInfoPaths(pkg, codePath, codePath);
9224 synchronized (mInstallLock) {
9225 // Scan the package
9226 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
9227 synchronized (mPackages) {
9228 // Grant permissions
9229 grantPermissionsLP(pkg, false);
9230 // Persist settings
9231 mSettings.writeLP();
9232 retCode = PackageManager.INSTALL_SUCCEEDED;
9233 pkgList.add(pkg.packageName);
9234 // Post process args
9235 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9236 }
9237 } else {
9238 Log.i(TAG, "Failed to install pkg: " +
9239 pkg.packageName + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009240 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009241 }
9242
9243 } finally {
9244 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9245 // Don't destroy container here. Wait till gc clears things up.
9246 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009247 }
9248 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009249 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009250 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009251 if (sendUpdateBroadcast) {
9252 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9253 }
9254 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009255 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009256 }
9257 // Delete any stale containers if needed.
9258 if (removeCids != null) {
9259 for (String cid : removeCids) {
9260 Log.i(TAG, "Destroying stale container : " + cid);
9261 PackageHelper.destroySdDir(cid);
9262 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009263 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009264 }
9265
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009266 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
9267 int uidArr[], boolean sendUpdateBroadcast) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009268 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009269 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009270 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009271 Set<SdInstallArgs> keys = processCids.keySet();
9272 for (SdInstallArgs args : keys) {
9273 String cid = args.cid;
9274 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009275 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009276 // Delete package internally
9277 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9278 synchronized (mInstallLock) {
9279 boolean res = deletePackageLI(pkgName, false,
9280 PackageManager.DONT_DELETE_DATA, outInfo);
9281 if (res) {
9282 pkgList.add(pkgName);
9283 } else {
9284 Log.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009285 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009286 }
9287 }
9288 }
9289 // Send broadcasts
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009290 if (sendUpdateBroadcast) {
9291 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009292 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009293 // Force gc
9294 Runtime.getRuntime().gc();
9295 // Just unmount all valid containers.
9296 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009297 synchronized (mInstallLock) {
9298 args.doPostDeleteLI(false);
9299 }
9300 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009301 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009302
9303 public void movePackage(final String packageName,
9304 final IPackageMoveObserver observer, final int flags) {
9305 if (packageName == null) {
9306 return;
9307 }
9308 mContext.enforceCallingOrSelfPermission(
9309 android.Manifest.permission.MOVE_PACKAGE, null);
9310 int returnCode = PackageManager.MOVE_SUCCEEDED;
9311 int currFlags = 0;
9312 int newFlags = 0;
9313 synchronized (mPackages) {
9314 PackageParser.Package pkg = mPackages.get(packageName);
9315 if (pkg == null) {
9316 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9317 }
9318 // Disable moving fwd locked apps and system packages
9319 if (pkg.applicationInfo != null &&
9320 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9321 Log.w(TAG, "Cannot move system application");
9322 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9323 } else if (pkg.applicationInfo != null &&
9324 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9325 Log.w(TAG, "Cannot move forward locked app.");
9326 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9327 } else {
9328 // Find install location first
9329 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9330 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9331 Log.w(TAG, "Ambigous flags specified for move location.");
9332 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9333 } else {
9334 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9335 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009336 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009337 PackageManager.INSTALL_EXTERNAL : 0;
9338 if (newFlags == currFlags) {
9339 Log.w(TAG, "No move required. Trying to move to same location");
9340 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9341 }
9342 }
9343 }
9344 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9345 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9346 } else {
9347 Message msg = mHandler.obtainMessage(INIT_COPY);
9348 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9349 pkg.applicationInfo.publicSourceDir);
9350 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9351 packageName);
9352 msg.obj = mp;
9353 mHandler.sendMessage(msg);
9354 }
9355 }
9356 }
9357
9358 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9359 // Queue up an async operation since the package deletion may take a little while.
9360 mHandler.post(new Runnable() {
9361 public void run() {
9362 mHandler.removeCallbacks(this);
9363 int returnCode = currentStatus;
9364 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9365 if (moveSucceeded) {
9366 int uid = -1;
9367 synchronized (mPackages) {
9368 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9369 }
9370 ArrayList<String> pkgList = new ArrayList<String>();
9371 pkgList.add(mp.packageName);
9372 int uidArr[] = new int[] { uid };
9373 // Send resources unavailable broadcast
9374 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9375
9376 // Update package code and resource paths
9377 synchronized (mPackages) {
9378 PackageParser.Package pkg = mPackages.get(mp.packageName);
9379 if (pkg != null) {
9380 String oldCodePath = pkg.mPath;
9381 String newCodePath = mp.targetArgs.getCodePath();
9382 String newResPath = mp.targetArgs.getResourcePath();
9383 pkg.mPath = newCodePath;
9384 // Move dex files around
9385 if (moveDexFiles(pkg)
9386 != PackageManager.INSTALL_SUCCEEDED) {
9387 // Moving of dex files failed. Set
9388 // error code and abort move.
9389 pkg.mPath = pkg.mScanPath;
9390 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9391 moveSucceeded = false;
9392 } else {
9393 pkg.mScanPath = newCodePath;
9394 pkg.applicationInfo.sourceDir = newCodePath;
9395 pkg.applicationInfo.publicSourceDir = newResPath;
9396 PackageSetting ps = (PackageSetting) pkg.mExtras;
9397 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9398 ps.codePathString = ps.codePath.getPath();
9399 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9400 ps.resourcePathString = ps.resourcePath.getPath();
9401 // Set the application info flag correctly.
9402 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009403 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009404 } else {
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009405 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009406 }
9407 ps.setFlags(pkg.applicationInfo.flags);
9408 mAppDirs.remove(oldCodePath);
9409 mAppDirs.put(newCodePath, pkg);
9410 // Persist settings
9411 mSettings.writeLP();
9412 }
9413 }
9414 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009415 // Send resources available broadcast
9416 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009417 }
9418 if (!moveSucceeded){
9419 // Clean up failed installation
9420 if (mp.targetArgs != null) {
9421 mp.targetArgs.doPostInstall(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009422 returnCode);
9423 }
9424 } else {
9425 // Force a gc to clear things up.
9426 Runtime.getRuntime().gc();
9427 // Delete older code
9428 synchronized (mInstallLock) {
9429 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009430 }
9431 }
9432 IPackageMoveObserver observer = mp.observer;
9433 if (observer != null) {
9434 try {
9435 observer.packageMoved(mp.packageName, returnCode);
9436 } catch (RemoteException e) {
9437 Log.i(TAG, "Observer no longer exists.");
9438 }
9439 }
9440 }
9441 });
9442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009443}