blob: ed8e22bcb5a35883e6045d661925b041693e0bf3 [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) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006325 int uid = Binder.getCallingUid();
6326 PackageParser.Package pkg = mPackages.get(packageName);
6327 if (pkg.applicationInfo.uid != uid) {
6328 mContext.enforceCallingOrSelfPermission(
6329 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6330 }
6331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 if (clearPackagePreferredActivitiesLP(packageName)) {
6333 mSettings.writeLP();
6334 }
6335 }
6336 }
6337
6338 boolean clearPackagePreferredActivitiesLP(String packageName) {
6339 boolean changed = false;
6340 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6341 while (it.hasNext()) {
6342 PreferredActivity pa = it.next();
6343 if (pa.mActivity.getPackageName().equals(packageName)) {
6344 it.remove();
6345 changed = true;
6346 }
6347 }
6348 return changed;
6349 }
6350
6351 public int getPreferredActivities(List<IntentFilter> outFilters,
6352 List<ComponentName> outActivities, String packageName) {
6353
6354 int num = 0;
6355 synchronized (mPackages) {
6356 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6357 while (it.hasNext()) {
6358 PreferredActivity pa = it.next();
6359 if (packageName == null
6360 || pa.mActivity.getPackageName().equals(packageName)) {
6361 if (outFilters != null) {
6362 outFilters.add(new IntentFilter(pa));
6363 }
6364 if (outActivities != null) {
6365 outActivities.add(pa.mActivity);
6366 }
6367 }
6368 }
6369 }
6370
6371 return num;
6372 }
6373
6374 public void setApplicationEnabledSetting(String appPackageName,
6375 int newState, int flags) {
6376 setEnabledSetting(appPackageName, null, newState, flags);
6377 }
6378
6379 public void setComponentEnabledSetting(ComponentName componentName,
6380 int newState, int flags) {
6381 setEnabledSetting(componentName.getPackageName(),
6382 componentName.getClassName(), newState, flags);
6383 }
6384
6385 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006386 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006387 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6388 || newState == COMPONENT_ENABLED_STATE_ENABLED
6389 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6390 throw new IllegalArgumentException("Invalid new component state: "
6391 + newState);
6392 }
6393 PackageSetting pkgSetting;
6394 final int uid = Binder.getCallingUid();
6395 final int permission = mContext.checkCallingPermission(
6396 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6397 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006398 boolean sendNow = false;
6399 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006400 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006401 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006402 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006404 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006405 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006406 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006407 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006408 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006409 }
6410 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006411 "Unknown component: " + packageName
6412 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006413 }
6414 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6415 throw new SecurityException(
6416 "Permission Denial: attempt to change component state from pid="
6417 + Binder.getCallingPid()
6418 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6419 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006420 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006421 // We're dealing with an application/package level state change
6422 pkgSetting.enabled = newState;
6423 } else {
6424 // We're dealing with a component level state change
6425 switch (newState) {
6426 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006427 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006428 break;
6429 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006430 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006431 break;
6432 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006433 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006434 break;
6435 default:
6436 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006437 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006438 }
6439 }
6440 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006441 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006442 components = mPendingBroadcasts.get(packageName);
6443 boolean newPackage = components == null;
6444 if (newPackage) {
6445 components = new ArrayList<String>();
6446 }
6447 if (!components.contains(componentName)) {
6448 components.add(componentName);
6449 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006450 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6451 sendNow = true;
6452 // Purge entry from pending broadcast list if another one exists already
6453 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006454 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006455 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006456 if (newPackage) {
6457 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006458 }
6459 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6460 // Schedule a message
6461 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6462 }
6463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006464 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006466 long callingId = Binder.clearCallingIdentity();
6467 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006468 if (sendNow) {
6469 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006470 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006472 } finally {
6473 Binder.restoreCallingIdentity(callingId);
6474 }
6475 }
6476
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006477 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006478 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6479 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6480 + " components=" + componentNames);
6481 Bundle extras = new Bundle(4);
6482 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6483 String nameList[] = new String[componentNames.size()];
6484 componentNames.toArray(nameList);
6485 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006486 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6487 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006488 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006489 }
6490
Jacek Surazski65e13172009-04-28 15:26:38 +02006491 public String getInstallerPackageName(String packageName) {
6492 synchronized (mPackages) {
6493 PackageSetting pkg = mSettings.mPackages.get(packageName);
6494 if (pkg == null) {
6495 throw new IllegalArgumentException("Unknown package: " + packageName);
6496 }
6497 return pkg.installerPackageName;
6498 }
6499 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006501 public int getApplicationEnabledSetting(String appPackageName) {
6502 synchronized (mPackages) {
6503 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6504 if (pkg == null) {
6505 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6506 }
6507 return pkg.enabled;
6508 }
6509 }
6510
6511 public int getComponentEnabledSetting(ComponentName componentName) {
6512 synchronized (mPackages) {
6513 final String packageNameStr = componentName.getPackageName();
6514 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6515 if (pkg == null) {
6516 throw new IllegalArgumentException("Unknown component: " + componentName);
6517 }
6518 final String classNameStr = componentName.getClassName();
6519 return pkg.currentEnabledStateLP(classNameStr);
6520 }
6521 }
6522
6523 public void enterSafeMode() {
6524 if (!mSystemReady) {
6525 mSafeMode = true;
6526 }
6527 }
6528
6529 public void systemReady() {
6530 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006531
6532 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006533 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006534 mContext.getContentResolver(),
6535 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006536 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006537 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006538 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006540 }
6541
6542 public boolean isSafeMode() {
6543 return mSafeMode;
6544 }
6545
6546 public boolean hasSystemUidErrors() {
6547 return mHasSystemUidErrors;
6548 }
6549
6550 static String arrayToString(int[] array) {
6551 StringBuffer buf = new StringBuffer(128);
6552 buf.append('[');
6553 if (array != null) {
6554 for (int i=0; i<array.length; i++) {
6555 if (i > 0) buf.append(", ");
6556 buf.append(array[i]);
6557 }
6558 }
6559 buf.append(']');
6560 return buf.toString();
6561 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006563 @Override
6564 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6565 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6566 != PackageManager.PERMISSION_GRANTED) {
6567 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6568 + Binder.getCallingPid()
6569 + ", uid=" + Binder.getCallingUid()
6570 + " without permission "
6571 + android.Manifest.permission.DUMP);
6572 return;
6573 }
6574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006575 synchronized (mPackages) {
6576 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006577 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006578 pw.println(" ");
6579 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006580 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006581 pw.println(" ");
6582 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006583 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006584 pw.println(" ");
6585 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006586 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006587 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 pw.println("Permissions:");
6589 {
6590 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006591 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6592 pw.print(Integer.toHexString(System.identityHashCode(p)));
6593 pw.println("):");
6594 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6595 pw.print(" uid="); pw.print(p.uid);
6596 pw.print(" gids="); pw.print(arrayToString(p.gids));
6597 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006598 }
6599 }
6600 pw.println(" ");
6601 pw.println("Packages:");
6602 {
6603 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006604 pw.print(" Package [");
6605 pw.print(ps.realName != null ? ps.realName : ps.name);
6606 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006607 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6608 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006609 if (ps.realName != null) {
6610 pw.print(" compat name="); pw.println(ps.name);
6611 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006612 pw.print(" userId="); pw.print(ps.userId);
6613 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6614 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6615 pw.print(" pkg="); pw.println(ps.pkg);
6616 pw.print(" codePath="); pw.println(ps.codePathString);
6617 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006618 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006619 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006620 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006621 pw.print(" supportsScreens=[");
6622 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006623 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006624 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006625 if (!first) pw.print(", ");
6626 first = false;
6627 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006628 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006629 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006630 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006631 if (!first) pw.print(", ");
6632 first = false;
6633 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006634 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006635 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006636 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006637 if (!first) pw.print(", ");
6638 first = false;
6639 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006640 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006641 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006642 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006643 if (!first) pw.print(", ");
6644 first = false;
6645 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006646 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006647 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006648 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6649 if (!first) pw.print(", ");
6650 first = false;
6651 pw.print("anyDensity");
6652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006653 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006654 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006655 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6656 pw.print(" signatures="); pw.println(ps.signatures);
6657 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6658 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6659 pw.print(" installStatus="); pw.print(ps.installStatus);
6660 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006661 if (ps.disabledComponents.size() > 0) {
6662 pw.println(" disabledComponents:");
6663 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006664 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006665 }
6666 }
6667 if (ps.enabledComponents.size() > 0) {
6668 pw.println(" enabledComponents:");
6669 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006670 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006671 }
6672 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006673 if (ps.grantedPermissions.size() > 0) {
6674 pw.println(" grantedPermissions:");
6675 for (String s : ps.grantedPermissions) {
6676 pw.print(" "); pw.println(s);
6677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006678 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006679 if (ps.loadedPermissions.size() > 0) {
6680 pw.println(" loadedPermissions:");
6681 for (String s : ps.loadedPermissions) {
6682 pw.print(" "); pw.println(s);
6683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006684 }
6685 }
6686 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006687 if (mSettings.mRenamedPackages.size() > 0) {
6688 pw.println(" ");
6689 pw.println("Renamed packages:");
6690 for (HashMap.Entry<String, String> e
6691 : mSettings.mRenamedPackages.entrySet()) {
6692 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6693 pw.println(e.getValue());
6694 }
6695 }
6696 if (mSettings.mDisabledSysPackages.size() > 0) {
6697 pw.println(" ");
6698 pw.println("Hidden system packages:");
6699 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
6700 pw.print(" Package [");
6701 pw.print(ps.realName != null ? ps.realName : ps.name);
6702 pw.print("] (");
6703 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6704 pw.println("):");
6705 if (ps.realName != null) {
6706 pw.print(" compat name="); pw.println(ps.name);
6707 }
6708 pw.print(" userId="); pw.println(ps.userId);
6709 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6710 pw.print(" codePath="); pw.println(ps.codePathString);
6711 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
6712 }
6713 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006714 pw.println(" ");
6715 pw.println("Shared Users:");
6716 {
6717 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006718 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6719 pw.print(Integer.toHexString(System.identityHashCode(su)));
6720 pw.println("):");
6721 pw.print(" userId="); pw.print(su.userId);
6722 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006723 pw.println(" grantedPermissions:");
6724 for (String s : su.grantedPermissions) {
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 pw.println(" loadedPermissions:");
6728 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006729 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006730 }
6731 }
6732 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006734 pw.println(" ");
6735 pw.println("Settings parse messages:");
6736 pw.println(mSettings.mReadMessages.toString());
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006737
6738 pw.println(" ");
6739 pw.println("Package warning messages:");
6740 File fname = getSettingsProblemFile();
6741 FileInputStream in;
6742 try {
6743 in = new FileInputStream(fname);
6744 int avail = in.available();
6745 byte[] data = new byte[avail];
6746 in.read(data);
6747 pw.println(new String(data));
6748 } catch (FileNotFoundException e) {
6749 } catch (IOException e) {
6750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006751 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006752
6753 synchronized (mProviders) {
6754 pw.println(" ");
6755 pw.println("Registered ContentProviders:");
6756 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006757 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006758 pw.println(p.toString());
6759 }
6760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006761 }
6762
6763 static final class BasePermission {
6764 final static int TYPE_NORMAL = 0;
6765 final static int TYPE_BUILTIN = 1;
6766 final static int TYPE_DYNAMIC = 2;
6767
6768 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006769 String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006770 final int type;
6771 PackageParser.Permission perm;
6772 PermissionInfo pendingInfo;
6773 int uid;
6774 int[] gids;
6775
6776 BasePermission(String _name, String _sourcePackage, int _type) {
6777 name = _name;
6778 sourcePackage = _sourcePackage;
6779 type = _type;
6780 }
6781 }
6782
6783 static class PackageSignatures {
6784 private Signature[] mSignatures;
6785
6786 PackageSignatures(Signature[] sigs) {
6787 assignSignatures(sigs);
6788 }
6789
6790 PackageSignatures() {
6791 }
6792
6793 void writeXml(XmlSerializer serializer, String tagName,
6794 ArrayList<Signature> pastSignatures) throws IOException {
6795 if (mSignatures == null) {
6796 return;
6797 }
6798 serializer.startTag(null, tagName);
6799 serializer.attribute(null, "count",
6800 Integer.toString(mSignatures.length));
6801 for (int i=0; i<mSignatures.length; i++) {
6802 serializer.startTag(null, "cert");
6803 final Signature sig = mSignatures[i];
6804 final int sigHash = sig.hashCode();
6805 final int numPast = pastSignatures.size();
6806 int j;
6807 for (j=0; j<numPast; j++) {
6808 Signature pastSig = pastSignatures.get(j);
6809 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
6810 serializer.attribute(null, "index", Integer.toString(j));
6811 break;
6812 }
6813 }
6814 if (j >= numPast) {
6815 pastSignatures.add(sig);
6816 serializer.attribute(null, "index", Integer.toString(numPast));
6817 serializer.attribute(null, "key", sig.toCharsString());
6818 }
6819 serializer.endTag(null, "cert");
6820 }
6821 serializer.endTag(null, tagName);
6822 }
6823
6824 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
6825 throws IOException, XmlPullParserException {
6826 String countStr = parser.getAttributeValue(null, "count");
6827 if (countStr == null) {
6828 reportSettingsProblem(Log.WARN,
6829 "Error in package manager settings: <signatures> has"
6830 + " no count at " + parser.getPositionDescription());
6831 XmlUtils.skipCurrentTag(parser);
6832 }
6833 final int count = Integer.parseInt(countStr);
6834 mSignatures = new Signature[count];
6835 int pos = 0;
6836
6837 int outerDepth = parser.getDepth();
6838 int type;
6839 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6840 && (type != XmlPullParser.END_TAG
6841 || parser.getDepth() > outerDepth)) {
6842 if (type == XmlPullParser.END_TAG
6843 || type == XmlPullParser.TEXT) {
6844 continue;
6845 }
6846
6847 String tagName = parser.getName();
6848 if (tagName.equals("cert")) {
6849 if (pos < count) {
6850 String index = parser.getAttributeValue(null, "index");
6851 if (index != null) {
6852 try {
6853 int idx = Integer.parseInt(index);
6854 String key = parser.getAttributeValue(null, "key");
6855 if (key == null) {
6856 if (idx >= 0 && idx < pastSignatures.size()) {
6857 Signature sig = pastSignatures.get(idx);
6858 if (sig != null) {
6859 mSignatures[pos] = pastSignatures.get(idx);
6860 pos++;
6861 } else {
6862 reportSettingsProblem(Log.WARN,
6863 "Error in package manager settings: <cert> "
6864 + "index " + index + " is not defined at "
6865 + parser.getPositionDescription());
6866 }
6867 } else {
6868 reportSettingsProblem(Log.WARN,
6869 "Error in package manager settings: <cert> "
6870 + "index " + index + " is out of bounds at "
6871 + parser.getPositionDescription());
6872 }
6873 } else {
6874 while (pastSignatures.size() <= idx) {
6875 pastSignatures.add(null);
6876 }
6877 Signature sig = new Signature(key);
6878 pastSignatures.set(idx, sig);
6879 mSignatures[pos] = sig;
6880 pos++;
6881 }
6882 } catch (NumberFormatException e) {
6883 reportSettingsProblem(Log.WARN,
6884 "Error in package manager settings: <cert> "
6885 + "index " + index + " is not a number at "
6886 + parser.getPositionDescription());
6887 }
6888 } else {
6889 reportSettingsProblem(Log.WARN,
6890 "Error in package manager settings: <cert> has"
6891 + " no index at " + parser.getPositionDescription());
6892 }
6893 } else {
6894 reportSettingsProblem(Log.WARN,
6895 "Error in package manager settings: too "
6896 + "many <cert> tags, expected " + count
6897 + " at " + parser.getPositionDescription());
6898 }
6899 } else {
6900 reportSettingsProblem(Log.WARN,
6901 "Unknown element under <cert>: "
6902 + parser.getName());
6903 }
6904 XmlUtils.skipCurrentTag(parser);
6905 }
6906
6907 if (pos < count) {
6908 // Should never happen -- there is an error in the written
6909 // settings -- but if it does we don't want to generate
6910 // a bad array.
6911 Signature[] newSigs = new Signature[pos];
6912 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6913 mSignatures = newSigs;
6914 }
6915 }
6916
6917 /**
6918 * If any of the given 'sigs' is contained in the existing signatures,
6919 * then completely replace the current signatures with the ones in
6920 * 'sigs'. This is used for updating an existing package to a newly
6921 * installed version.
6922 */
6923 boolean updateSignatures(Signature[] sigs, boolean update) {
6924 if (mSignatures == null) {
6925 if (update) {
6926 assignSignatures(sigs);
6927 }
6928 return true;
6929 }
6930 if (sigs == null) {
6931 return false;
6932 }
6933
6934 for (int i=0; i<sigs.length; i++) {
6935 Signature sig = sigs[i];
6936 for (int j=0; j<mSignatures.length; j++) {
6937 if (mSignatures[j].equals(sig)) {
6938 if (update) {
6939 assignSignatures(sigs);
6940 }
6941 return true;
6942 }
6943 }
6944 }
6945 return false;
6946 }
6947
6948 /**
6949 * If any of the given 'sigs' is contained in the existing signatures,
6950 * then add in any new signatures found in 'sigs'. This is used for
6951 * including a new package into an existing shared user id.
6952 */
6953 boolean mergeSignatures(Signature[] sigs, boolean update) {
6954 if (mSignatures == null) {
6955 if (update) {
6956 assignSignatures(sigs);
6957 }
6958 return true;
6959 }
6960 if (sigs == null) {
6961 return false;
6962 }
6963
6964 Signature[] added = null;
6965 int addedCount = 0;
6966 boolean haveMatch = false;
6967 for (int i=0; i<sigs.length; i++) {
6968 Signature sig = sigs[i];
6969 boolean found = false;
6970 for (int j=0; j<mSignatures.length; j++) {
6971 if (mSignatures[j].equals(sig)) {
6972 found = true;
6973 haveMatch = true;
6974 break;
6975 }
6976 }
6977
6978 if (!found) {
6979 if (added == null) {
6980 added = new Signature[sigs.length];
6981 }
6982 added[i] = sig;
6983 addedCount++;
6984 }
6985 }
6986
6987 if (!haveMatch) {
6988 // Nothing matched -- reject the new signatures.
6989 return false;
6990 }
6991 if (added == null) {
6992 // Completely matched -- nothing else to do.
6993 return true;
6994 }
6995
6996 // Add additional signatures in.
6997 if (update) {
6998 Signature[] total = new Signature[addedCount+mSignatures.length];
6999 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
7000 int j = mSignatures.length;
7001 for (int i=0; i<added.length; i++) {
7002 if (added[i] != null) {
7003 total[j] = added[i];
7004 j++;
7005 }
7006 }
7007 mSignatures = total;
7008 }
7009 return true;
7010 }
7011
7012 private void assignSignatures(Signature[] sigs) {
7013 if (sigs == null) {
7014 mSignatures = null;
7015 return;
7016 }
7017 mSignatures = new Signature[sigs.length];
7018 for (int i=0; i<sigs.length; i++) {
7019 mSignatures[i] = sigs[i];
7020 }
7021 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007023 @Override
7024 public String toString() {
7025 StringBuffer buf = new StringBuffer(128);
7026 buf.append("PackageSignatures{");
7027 buf.append(Integer.toHexString(System.identityHashCode(this)));
7028 buf.append(" [");
7029 if (mSignatures != null) {
7030 for (int i=0; i<mSignatures.length; i++) {
7031 if (i > 0) buf.append(", ");
7032 buf.append(Integer.toHexString(
7033 System.identityHashCode(mSignatures[i])));
7034 }
7035 }
7036 buf.append("]}");
7037 return buf.toString();
7038 }
7039 }
7040
7041 static class PreferredActivity extends IntentFilter {
7042 final int mMatch;
7043 final String[] mSetPackages;
7044 final String[] mSetClasses;
7045 final String[] mSetComponents;
7046 final ComponentName mActivity;
7047 final String mShortActivity;
7048 String mParseError;
7049
7050 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7051 ComponentName activity) {
7052 super(filter);
7053 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7054 mActivity = activity;
7055 mShortActivity = activity.flattenToShortString();
7056 mParseError = null;
7057 if (set != null) {
7058 final int N = set.length;
7059 String[] myPackages = new String[N];
7060 String[] myClasses = new String[N];
7061 String[] myComponents = new String[N];
7062 for (int i=0; i<N; i++) {
7063 ComponentName cn = set[i];
7064 if (cn == null) {
7065 mSetPackages = null;
7066 mSetClasses = null;
7067 mSetComponents = null;
7068 return;
7069 }
7070 myPackages[i] = cn.getPackageName().intern();
7071 myClasses[i] = cn.getClassName().intern();
7072 myComponents[i] = cn.flattenToShortString().intern();
7073 }
7074 mSetPackages = myPackages;
7075 mSetClasses = myClasses;
7076 mSetComponents = myComponents;
7077 } else {
7078 mSetPackages = null;
7079 mSetClasses = null;
7080 mSetComponents = null;
7081 }
7082 }
7083
7084 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7085 IOException {
7086 mShortActivity = parser.getAttributeValue(null, "name");
7087 mActivity = ComponentName.unflattenFromString(mShortActivity);
7088 if (mActivity == null) {
7089 mParseError = "Bad activity name " + mShortActivity;
7090 }
7091 String matchStr = parser.getAttributeValue(null, "match");
7092 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7093 String setCountStr = parser.getAttributeValue(null, "set");
7094 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7095
7096 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7097 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7098 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7099
7100 int setPos = 0;
7101
7102 int outerDepth = parser.getDepth();
7103 int type;
7104 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7105 && (type != XmlPullParser.END_TAG
7106 || parser.getDepth() > outerDepth)) {
7107 if (type == XmlPullParser.END_TAG
7108 || type == XmlPullParser.TEXT) {
7109 continue;
7110 }
7111
7112 String tagName = parser.getName();
7113 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7114 // + parser.getDepth() + " tag=" + tagName);
7115 if (tagName.equals("set")) {
7116 String name = parser.getAttributeValue(null, "name");
7117 if (name == null) {
7118 if (mParseError == null) {
7119 mParseError = "No name in set tag in preferred activity "
7120 + mShortActivity;
7121 }
7122 } else if (setPos >= setCount) {
7123 if (mParseError == null) {
7124 mParseError = "Too many set tags in preferred activity "
7125 + mShortActivity;
7126 }
7127 } else {
7128 ComponentName cn = ComponentName.unflattenFromString(name);
7129 if (cn == null) {
7130 if (mParseError == null) {
7131 mParseError = "Bad set name " + name + " in preferred activity "
7132 + mShortActivity;
7133 }
7134 } else {
7135 myPackages[setPos] = cn.getPackageName();
7136 myClasses[setPos] = cn.getClassName();
7137 myComponents[setPos] = name;
7138 setPos++;
7139 }
7140 }
7141 XmlUtils.skipCurrentTag(parser);
7142 } else if (tagName.equals("filter")) {
7143 //Log.i(TAG, "Starting to parse filter...");
7144 readFromXml(parser);
7145 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7146 // + parser.getDepth() + " tag=" + parser.getName());
7147 } else {
7148 reportSettingsProblem(Log.WARN,
7149 "Unknown element under <preferred-activities>: "
7150 + parser.getName());
7151 XmlUtils.skipCurrentTag(parser);
7152 }
7153 }
7154
7155 if (setPos != setCount) {
7156 if (mParseError == null) {
7157 mParseError = "Not enough set tags (expected " + setCount
7158 + " but found " + setPos + ") in " + mShortActivity;
7159 }
7160 }
7161
7162 mSetPackages = myPackages;
7163 mSetClasses = myClasses;
7164 mSetComponents = myComponents;
7165 }
7166
7167 public void writeToXml(XmlSerializer serializer) throws IOException {
7168 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7169 serializer.attribute(null, "name", mShortActivity);
7170 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7171 serializer.attribute(null, "set", Integer.toString(NS));
7172 for (int s=0; s<NS; s++) {
7173 serializer.startTag(null, "set");
7174 serializer.attribute(null, "name", mSetComponents[s]);
7175 serializer.endTag(null, "set");
7176 }
7177 serializer.startTag(null, "filter");
7178 super.writeToXml(serializer);
7179 serializer.endTag(null, "filter");
7180 }
7181
7182 boolean sameSet(List<ResolveInfo> query, int priority) {
7183 if (mSetPackages == null) return false;
7184 final int NQ = query.size();
7185 final int NS = mSetPackages.length;
7186 int numMatch = 0;
7187 for (int i=0; i<NQ; i++) {
7188 ResolveInfo ri = query.get(i);
7189 if (ri.priority != priority) continue;
7190 ActivityInfo ai = ri.activityInfo;
7191 boolean good = false;
7192 for (int j=0; j<NS; j++) {
7193 if (mSetPackages[j].equals(ai.packageName)
7194 && mSetClasses[j].equals(ai.name)) {
7195 numMatch++;
7196 good = true;
7197 break;
7198 }
7199 }
7200 if (!good) return false;
7201 }
7202 return numMatch == NS;
7203 }
7204 }
7205
7206 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007207 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007209 HashSet<String> grantedPermissions = new HashSet<String>();
7210 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007212 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007214 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007215 setFlags(pkgFlags);
7216 }
7217
7218 void setFlags(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007219 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007220 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08007221 (pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) |
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08007222 (pkgFlags & ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007223 }
7224 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007226 /**
7227 * Settings base class for pending and resolved classes.
7228 */
7229 static class PackageSettingBase extends GrantedPermissions {
7230 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007231 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007232 File codePath;
7233 String codePathString;
7234 File resourcePath;
7235 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007236 private long timeStamp;
7237 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007238 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007239
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007240 boolean uidError;
7241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007242 PackageSignatures signatures = new PackageSignatures();
7243
7244 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007246 /* Explicitly disabled components */
7247 HashSet<String> disabledComponents = new HashSet<String>(0);
7248 /* Explicitly enabled components */
7249 HashSet<String> enabledComponents = new HashSet<String>(0);
7250 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7251 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007252
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007253 PackageSettingBase origPackage;
7254
Jacek Surazski65e13172009-04-28 15:26:38 +02007255 /* package name of the app that installed this package */
7256 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007257
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007258 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007259 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007260 super(pkgFlags);
7261 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007262 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007263 init(codePath, resourcePath, pVersionCode);
7264 }
7265
7266 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007267 this.codePath = codePath;
7268 this.codePathString = codePath.toString();
7269 this.resourcePath = resourcePath;
7270 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007271 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007272 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007273
Jacek Surazski65e13172009-04-28 15:26:38 +02007274 public void setInstallerPackageName(String packageName) {
7275 installerPackageName = packageName;
7276 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007277
Jacek Surazski65e13172009-04-28 15:26:38 +02007278 String getInstallerPackageName() {
7279 return installerPackageName;
7280 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007282 public void setInstallStatus(int newStatus) {
7283 installStatus = newStatus;
7284 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007286 public int getInstallStatus() {
7287 return installStatus;
7288 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007290 public void setTimeStamp(long newStamp) {
7291 if (newStamp != timeStamp) {
7292 timeStamp = newStamp;
7293 timeStampString = Long.toString(newStamp);
7294 }
7295 }
7296
7297 public void setTimeStamp(long newStamp, String newStampStr) {
7298 timeStamp = newStamp;
7299 timeStampString = newStampStr;
7300 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007302 public long getTimeStamp() {
7303 return timeStamp;
7304 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007306 public String getTimeStampStr() {
7307 return timeStampString;
7308 }
7309
7310 public void copyFrom(PackageSettingBase base) {
7311 grantedPermissions = base.grantedPermissions;
7312 gids = base.gids;
7313 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007315 timeStamp = base.timeStamp;
7316 timeStampString = base.timeStampString;
7317 signatures = base.signatures;
7318 permissionsFixed = base.permissionsFixed;
7319 disabledComponents = base.disabledComponents;
7320 enabledComponents = base.enabledComponents;
7321 enabled = base.enabled;
7322 installStatus = base.installStatus;
7323 }
7324
7325 void enableComponentLP(String componentClassName) {
7326 disabledComponents.remove(componentClassName);
7327 enabledComponents.add(componentClassName);
7328 }
7329
7330 void disableComponentLP(String componentClassName) {
7331 enabledComponents.remove(componentClassName);
7332 disabledComponents.add(componentClassName);
7333 }
7334
7335 void restoreComponentLP(String componentClassName) {
7336 enabledComponents.remove(componentClassName);
7337 disabledComponents.remove(componentClassName);
7338 }
7339
7340 int currentEnabledStateLP(String componentName) {
7341 if (enabledComponents.contains(componentName)) {
7342 return COMPONENT_ENABLED_STATE_ENABLED;
7343 } else if (disabledComponents.contains(componentName)) {
7344 return COMPONENT_ENABLED_STATE_DISABLED;
7345 } else {
7346 return COMPONENT_ENABLED_STATE_DEFAULT;
7347 }
7348 }
7349 }
7350
7351 /**
7352 * Settings data for a particular package we know about.
7353 */
7354 static final class PackageSetting extends PackageSettingBase {
7355 int userId;
7356 PackageParser.Package pkg;
7357 SharedUserSetting sharedUser;
7358
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007359 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007360 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007361 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007362 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007364 @Override
7365 public String toString() {
7366 return "PackageSetting{"
7367 + Integer.toHexString(System.identityHashCode(this))
7368 + " " + name + "/" + userId + "}";
7369 }
7370 }
7371
7372 /**
7373 * Settings data for a particular shared user ID we know about.
7374 */
7375 static final class SharedUserSetting extends GrantedPermissions {
7376 final String name;
7377 int userId;
7378 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7379 final PackageSignatures signatures = new PackageSignatures();
7380
7381 SharedUserSetting(String _name, int _pkgFlags) {
7382 super(_pkgFlags);
7383 name = _name;
7384 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007386 @Override
7387 public String toString() {
7388 return "SharedUserSetting{"
7389 + Integer.toHexString(System.identityHashCode(this))
7390 + " " + name + "/" + userId + "}";
7391 }
7392 }
7393
7394 /**
7395 * Holds information about dynamic settings.
7396 */
7397 private static final class Settings {
7398 private final File mSettingsFilename;
7399 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007400 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007401 private final HashMap<String, PackageSetting> mPackages =
7402 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007403 // List of replaced system applications
7404 final HashMap<String, PackageSetting> mDisabledSysPackages =
7405 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007407 // The user's preferred activities associated with particular intent
7408 // filters.
7409 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7410 new IntentResolver<PreferredActivity, PreferredActivity>() {
7411 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007412 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007413 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007414 out.print(prefix); out.print(
7415 Integer.toHexString(System.identityHashCode(filter)));
7416 out.print(' ');
7417 out.print(filter.mActivity.flattenToShortString());
7418 out.print(" match=0x");
7419 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007420 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007421 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007422 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007423 out.print(prefix); out.print(" ");
7424 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007425 }
7426 }
7427 }
7428 };
7429 private final HashMap<String, SharedUserSetting> mSharedUsers =
7430 new HashMap<String, SharedUserSetting>();
7431 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7432 private final SparseArray<Object> mOtherUserIds =
7433 new SparseArray<Object>();
7434
7435 // For reading/writing settings file.
7436 private final ArrayList<Signature> mPastSignatures =
7437 new ArrayList<Signature>();
7438
7439 // Mapping from permission names to info about them.
7440 final HashMap<String, BasePermission> mPermissions =
7441 new HashMap<String, BasePermission>();
7442
7443 // Mapping from permission tree names to info about them.
7444 final HashMap<String, BasePermission> mPermissionTrees =
7445 new HashMap<String, BasePermission>();
7446
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007447 // Packages that have been uninstalled and still need their external
7448 // storage data deleted.
7449 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7450
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007451 // Packages that have been renamed since they were first installed.
7452 // Keys are the new names of the packages, values are the original
7453 // names. The packages appear everwhere else under their original
7454 // names.
7455 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007457 private final StringBuilder mReadMessages = new StringBuilder();
7458
7459 private static final class PendingPackage extends PackageSettingBase {
7460 final int sharedId;
7461
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007462 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007463 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007464 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007465 this.sharedId = sharedId;
7466 }
7467 }
7468 private final ArrayList<PendingPackage> mPendingPackages
7469 = new ArrayList<PendingPackage>();
7470
7471 Settings() {
7472 File dataDir = Environment.getDataDirectory();
7473 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007474 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7475 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007476 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007477 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007478 FileUtils.setPermissions(systemDir.toString(),
7479 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7480 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7481 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007482 FileUtils.setPermissions(systemSecureDir.toString(),
7483 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7484 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7485 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007486 mSettingsFilename = new File(systemDir, "packages.xml");
7487 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007488 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007489 }
7490
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007491 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007492 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007493 int pkgFlags, boolean create, boolean add) {
7494 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007495 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007496 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007497 return p;
7498 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007499
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007500 PackageSetting peekPackageLP(String name) {
7501 return mPackages.get(name);
7502 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007503 PackageSetting p = mPackages.get(name);
7504 if (p != null && p.codePath.getPath().equals(codePath)) {
7505 return p;
7506 }
7507 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007508 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007509 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007511 void setInstallStatus(String pkgName, int status) {
7512 PackageSetting p = mPackages.get(pkgName);
7513 if(p != null) {
7514 if(p.getInstallStatus() != status) {
7515 p.setInstallStatus(status);
7516 }
7517 }
7518 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007519
Jacek Surazski65e13172009-04-28 15:26:38 +02007520 void setInstallerPackageName(String pkgName,
7521 String installerPkgName) {
7522 PackageSetting p = mPackages.get(pkgName);
7523 if(p != null) {
7524 p.setInstallerPackageName(installerPkgName);
7525 }
7526 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007527
Jacek Surazski65e13172009-04-28 15:26:38 +02007528 String getInstallerPackageName(String pkgName) {
7529 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007530 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007531 }
7532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007533 int getInstallStatus(String pkgName) {
7534 PackageSetting p = mPackages.get(pkgName);
7535 if(p != null) {
7536 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007538 return -1;
7539 }
7540
7541 SharedUserSetting getSharedUserLP(String name,
7542 int pkgFlags, boolean create) {
7543 SharedUserSetting s = mSharedUsers.get(name);
7544 if (s == null) {
7545 if (!create) {
7546 return null;
7547 }
7548 s = new SharedUserSetting(name, pkgFlags);
7549 if (MULTIPLE_APPLICATION_UIDS) {
7550 s.userId = newUserIdLP(s);
7551 } else {
7552 s.userId = FIRST_APPLICATION_UID;
7553 }
7554 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7555 // < 0 means we couldn't assign a userid; fall out and return
7556 // s, which is currently null
7557 if (s.userId >= 0) {
7558 mSharedUsers.put(name, s);
7559 }
7560 }
7561
7562 return s;
7563 }
7564
7565 int disableSystemPackageLP(String name) {
7566 PackageSetting p = mPackages.get(name);
7567 if(p == null) {
7568 Log.w(TAG, "Package:"+name+" is not an installed package");
7569 return -1;
7570 }
7571 PackageSetting dp = mDisabledSysPackages.get(name);
7572 // always make sure the system package code and resource paths dont change
7573 if(dp == null) {
7574 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7575 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7576 }
7577 mDisabledSysPackages.put(name, p);
7578 }
7579 return removePackageLP(name);
7580 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007582 PackageSetting enableSystemPackageLP(String name) {
7583 PackageSetting p = mDisabledSysPackages.get(name);
7584 if(p == null) {
7585 Log.w(TAG, "Package:"+name+" is not disabled");
7586 return null;
7587 }
7588 // Reset flag in ApplicationInfo object
7589 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7590 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7591 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007592 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007593 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007594 mDisabledSysPackages.remove(name);
7595 return ret;
7596 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007597
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007598 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007599 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007600 PackageSetting p = mPackages.get(name);
7601 if (p != null) {
7602 if (p.userId == uid) {
7603 return p;
7604 }
7605 reportSettingsProblem(Log.ERROR,
7606 "Adding duplicate package, keeping first: " + name);
7607 return null;
7608 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007609 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007610 p.userId = uid;
7611 if (addUserIdLP(uid, p, name)) {
7612 mPackages.put(name, p);
7613 return p;
7614 }
7615 return null;
7616 }
7617
7618 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7619 SharedUserSetting s = mSharedUsers.get(name);
7620 if (s != null) {
7621 if (s.userId == uid) {
7622 return s;
7623 }
7624 reportSettingsProblem(Log.ERROR,
7625 "Adding duplicate shared user, keeping first: " + name);
7626 return null;
7627 }
7628 s = new SharedUserSetting(name, pkgFlags);
7629 s.userId = uid;
7630 if (addUserIdLP(uid, s, name)) {
7631 mSharedUsers.put(name, s);
7632 return s;
7633 }
7634 return null;
7635 }
7636
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007637 // Transfer ownership of permissions from one package to another.
7638 private void transferPermissions(String origPkg, String newPkg) {
7639 // Transfer ownership of permissions to the new package.
7640 for (int i=0; i<2; i++) {
7641 HashMap<String, BasePermission> permissions =
7642 i == 0 ? mPermissionTrees : mPermissions;
7643 for (BasePermission bp : permissions.values()) {
7644 if (origPkg.equals(bp.sourcePackage)) {
7645 if (DEBUG_UPGRADE) Log.v(TAG,
7646 "Moving permission " + bp.name
7647 + " from pkg " + bp.sourcePackage
7648 + " to " + newPkg);
7649 bp.sourcePackage = newPkg;
7650 bp.perm = null;
7651 if (bp.pendingInfo != null) {
7652 bp.sourcePackage = newPkg;
7653 }
7654 bp.uid = 0;
7655 bp.gids = null;
7656 }
7657 }
7658 }
7659 }
7660
7661 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007662 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007663 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007664 PackageSetting p = mPackages.get(name);
7665 if (p != null) {
7666 if (!p.codePath.equals(codePath)) {
7667 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007668 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007669 // This is an updated system app with versions in both system
7670 // and data partition. Just let the most recent version
7671 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007672 Log.w(TAG, "Trying to update system app code path from " +
7673 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007674 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007675 // Just a change in the code path is not an issue, but
7676 // let's log a message about it.
7677 Log.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007678 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007679 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007680 }
7681 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007682 reportSettingsProblem(Log.WARN,
7683 "Package " + name + " shared user changed from "
7684 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7685 + " to "
7686 + (sharedUser != null ? sharedUser.name : "<nothing>")
7687 + "; replacing with new");
7688 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007689 } else {
7690 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7691 // If what we are scanning is a system package, then
7692 // make it so, regardless of whether it was previously
7693 // installed only in the data partition.
7694 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007696 }
7697 }
7698 if (p == null) {
7699 // Create a new PackageSettings entry. this can end up here because
7700 // of code path mismatch or user id mismatch of an updated system partition
7701 if (!create) {
7702 return null;
7703 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007704 if (origPackage != null) {
7705 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007706 p = new PackageSetting(origPackage.name, name, codePath,
7707 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007708 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
7709 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08007710 // Note that we will retain the new package's signature so
7711 // that we can keep its data.
7712 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007713 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08007714 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007715 p.sharedUser = origPackage.sharedUser;
7716 p.userId = origPackage.userId;
7717 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007718 mRenamedPackages.put(name, origPackage.name);
7719 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007720 // Update new package state.
7721 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007722 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007723 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007724 p.setTimeStamp(codePath.lastModified());
7725 p.sharedUser = sharedUser;
7726 if (sharedUser != null) {
7727 p.userId = sharedUser.userId;
7728 } else if (MULTIPLE_APPLICATION_UIDS) {
7729 // Clone the setting here for disabled system packages
7730 PackageSetting dis = mDisabledSysPackages.get(name);
7731 if (dis != null) {
7732 // For disabled packages a new setting is created
7733 // from the existing user id. This still has to be
7734 // added to list of user id's
7735 // Copy signatures from previous setting
7736 if (dis.signatures.mSignatures != null) {
7737 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
7738 }
7739 p.userId = dis.userId;
7740 // Clone permissions
7741 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
7742 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
7743 // Clone component info
7744 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
7745 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
7746 // Add new setting to list of user ids
7747 addUserIdLP(p.userId, p, name);
7748 } else {
7749 // Assign new user id
7750 p.userId = newUserIdLP(p);
7751 }
7752 } else {
7753 p.userId = FIRST_APPLICATION_UID;
7754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007755 }
7756 if (p.userId < 0) {
7757 reportSettingsProblem(Log.WARN,
7758 "Package " + name + " could not be assigned a valid uid");
7759 return null;
7760 }
7761 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007762 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007763 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007764 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007765 }
7766 }
7767 return p;
7768 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007769
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007770 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007771 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007772 String codePath = pkg.applicationInfo.sourceDir;
7773 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007774 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007775 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007776 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007777 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007778 p.codePath = new File(codePath);
7779 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007780 }
7781 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007782 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007783 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007784 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007785 p.resourcePath = new File(resourcePath);
7786 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007787 }
7788 // Update version code if needed
7789 if (pkg.mVersionCode != p.versionCode) {
7790 p.versionCode = pkg.mVersionCode;
7791 }
7792 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
7793 }
7794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007795 // Utility method that adds a PackageSetting to mPackages and
7796 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007797 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007798 SharedUserSetting sharedUser) {
7799 mPackages.put(name, p);
7800 if (sharedUser != null) {
7801 if (p.sharedUser != null && p.sharedUser != sharedUser) {
7802 reportSettingsProblem(Log.ERROR,
7803 "Package " + p.name + " was user "
7804 + p.sharedUser + " but is now " + sharedUser
7805 + "; I am not changing its files so it will probably fail!");
7806 p.sharedUser.packages.remove(p);
7807 } else if (p.userId != sharedUser.userId) {
7808 reportSettingsProblem(Log.ERROR,
7809 "Package " + p.name + " was user id " + p.userId
7810 + " but is now user " + sharedUser
7811 + " with id " + sharedUser.userId
7812 + "; I am not changing its files so it will probably fail!");
7813 }
7814
7815 sharedUser.packages.add(p);
7816 p.sharedUser = sharedUser;
7817 p.userId = sharedUser.userId;
7818 }
7819 }
7820
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007821 /*
7822 * Update the shared user setting when a package using
7823 * specifying the shared user id is removed. The gids
7824 * associated with each permission of the deleted package
7825 * are removed from the shared user's gid list only if its
7826 * not in use by other permissions of packages in the
7827 * shared user setting.
7828 */
7829 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007830 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
7831 Log.i(TAG, "Trying to update info for null package. Just ignoring");
7832 return;
7833 }
7834 // No sharedUserId
7835 if (deletedPs.sharedUser == null) {
7836 return;
7837 }
7838 SharedUserSetting sus = deletedPs.sharedUser;
7839 // Update permissions
7840 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
7841 boolean used = false;
7842 if (!sus.grantedPermissions.contains (eachPerm)) {
7843 continue;
7844 }
7845 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007846 if (pkg.pkg != null &&
7847 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
7848 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007849 used = true;
7850 break;
7851 }
7852 }
7853 if (!used) {
7854 // can safely delete this permission from list
7855 sus.grantedPermissions.remove(eachPerm);
7856 sus.loadedPermissions.remove(eachPerm);
7857 }
7858 }
7859 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007860 int newGids[] = globalGids;
7861 for (String eachPerm : sus.grantedPermissions) {
7862 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007863 if (bp != null) {
7864 newGids = appendInts(newGids, bp.gids);
7865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007866 }
7867 sus.gids = newGids;
7868 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007870 private int removePackageLP(String name) {
7871 PackageSetting p = mPackages.get(name);
7872 if (p != null) {
7873 mPackages.remove(name);
7874 if (p.sharedUser != null) {
7875 p.sharedUser.packages.remove(p);
7876 if (p.sharedUser.packages.size() == 0) {
7877 mSharedUsers.remove(p.sharedUser.name);
7878 removeUserIdLP(p.sharedUser.userId);
7879 return p.sharedUser.userId;
7880 }
7881 } else {
7882 removeUserIdLP(p.userId);
7883 return p.userId;
7884 }
7885 }
7886 return -1;
7887 }
7888
7889 private boolean addUserIdLP(int uid, Object obj, Object name) {
7890 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
7891 return false;
7892 }
7893
7894 if (uid >= FIRST_APPLICATION_UID) {
7895 int N = mUserIds.size();
7896 final int index = uid - FIRST_APPLICATION_UID;
7897 while (index >= N) {
7898 mUserIds.add(null);
7899 N++;
7900 }
7901 if (mUserIds.get(index) != null) {
7902 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007903 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007904 + " name=" + name);
7905 return false;
7906 }
7907 mUserIds.set(index, obj);
7908 } else {
7909 if (mOtherUserIds.get(uid) != null) {
7910 reportSettingsProblem(Log.ERROR,
7911 "Adding duplicate shared id: " + uid
7912 + " name=" + name);
7913 return false;
7914 }
7915 mOtherUserIds.put(uid, obj);
7916 }
7917 return true;
7918 }
7919
7920 public Object getUserIdLP(int uid) {
7921 if (uid >= FIRST_APPLICATION_UID) {
7922 int N = mUserIds.size();
7923 final int index = uid - FIRST_APPLICATION_UID;
7924 return index < N ? mUserIds.get(index) : null;
7925 } else {
7926 return mOtherUserIds.get(uid);
7927 }
7928 }
7929
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007930 private Set<String> findPackagesWithFlag(int flag) {
7931 Set<String> ret = new HashSet<String>();
7932 for (PackageSetting ps : mPackages.values()) {
7933 // Has to match atleast all the flag bits set on flag
7934 if ((ps.pkgFlags & flag) == flag) {
7935 ret.add(ps.name);
7936 }
7937 }
7938 return ret;
7939 }
7940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007941 private void removeUserIdLP(int uid) {
7942 if (uid >= FIRST_APPLICATION_UID) {
7943 int N = mUserIds.size();
7944 final int index = uid - FIRST_APPLICATION_UID;
7945 if (index < N) mUserIds.set(index, null);
7946 } else {
7947 mOtherUserIds.remove(uid);
7948 }
7949 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007951 void writeLP() {
7952 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
7953
7954 // Keep the old settings around until we know the new ones have
7955 // been successfully written.
7956 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007957 // Presence of backup settings file indicates that we failed
7958 // to persist settings earlier. So preserve the older
7959 // backup for future reference since the current settings
7960 // might have been corrupted.
7961 if (!mBackupSettingsFilename.exists()) {
7962 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
7963 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
7964 return;
7965 }
7966 } else {
7967 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07007968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007969 }
7970
7971 mPastSignatures.clear();
7972
7973 try {
7974 FileOutputStream str = new FileOutputStream(mSettingsFilename);
7975
7976 //XmlSerializer serializer = XmlUtils.serializerInstance();
7977 XmlSerializer serializer = new FastXmlSerializer();
7978 serializer.setOutput(str, "utf-8");
7979 serializer.startDocument(null, true);
7980 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
7981
7982 serializer.startTag(null, "packages");
7983
7984 serializer.startTag(null, "permission-trees");
7985 for (BasePermission bp : mPermissionTrees.values()) {
7986 writePermission(serializer, bp);
7987 }
7988 serializer.endTag(null, "permission-trees");
7989
7990 serializer.startTag(null, "permissions");
7991 for (BasePermission bp : mPermissions.values()) {
7992 writePermission(serializer, bp);
7993 }
7994 serializer.endTag(null, "permissions");
7995
7996 for (PackageSetting pkg : mPackages.values()) {
7997 writePackage(serializer, pkg);
7998 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008000 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8001 writeDisabledSysPackage(serializer, pkg);
8002 }
8003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008004 serializer.startTag(null, "preferred-activities");
8005 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8006 serializer.startTag(null, "item");
8007 pa.writeToXml(serializer);
8008 serializer.endTag(null, "item");
8009 }
8010 serializer.endTag(null, "preferred-activities");
8011
8012 for (SharedUserSetting usr : mSharedUsers.values()) {
8013 serializer.startTag(null, "shared-user");
8014 serializer.attribute(null, "name", usr.name);
8015 serializer.attribute(null, "userId",
8016 Integer.toString(usr.userId));
8017 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8018 serializer.startTag(null, "perms");
8019 for (String name : usr.grantedPermissions) {
8020 serializer.startTag(null, "item");
8021 serializer.attribute(null, "name", name);
8022 serializer.endTag(null, "item");
8023 }
8024 serializer.endTag(null, "perms");
8025 serializer.endTag(null, "shared-user");
8026 }
8027
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008028 if (mPackagesToBeCleaned.size() > 0) {
8029 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8030 serializer.startTag(null, "cleaning-package");
8031 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8032 serializer.endTag(null, "cleaning-package");
8033 }
8034 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008035
8036 if (mRenamedPackages.size() > 0) {
8037 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8038 serializer.startTag(null, "renamed-package");
8039 serializer.attribute(null, "new", e.getKey());
8040 serializer.attribute(null, "old", e.getValue());
8041 serializer.endTag(null, "renamed-package");
8042 }
8043 }
8044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008045 serializer.endTag(null, "packages");
8046
8047 serializer.endDocument();
8048
8049 str.flush();
8050 str.close();
8051
8052 // New settings successfully written, old ones are no longer
8053 // needed.
8054 mBackupSettingsFilename.delete();
8055 FileUtils.setPermissions(mSettingsFilename.toString(),
8056 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8057 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8058 |FileUtils.S_IROTH,
8059 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008060
8061 // Write package list file now, use a JournaledFile.
8062 //
8063 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8064 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8065
8066 str = new FileOutputStream(journal.chooseForWrite());
8067 try {
8068 StringBuilder sb = new StringBuilder();
8069 for (PackageSetting pkg : mPackages.values()) {
8070 ApplicationInfo ai = pkg.pkg.applicationInfo;
8071 String dataPath = ai.dataDir;
8072 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8073
8074 // Avoid any application that has a space in its path
8075 // or that is handled by the system.
8076 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8077 continue;
8078
8079 // we store on each line the following information for now:
8080 //
8081 // pkgName - package name
8082 // userId - application-specific user id
8083 // debugFlag - 0 or 1 if the package is debuggable.
8084 // dataPath - path to package's data path
8085 //
8086 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8087 //
8088 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8089 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8090 // system/core/run-as/run-as.c
8091 //
8092 sb.setLength(0);
8093 sb.append(ai.packageName);
8094 sb.append(" ");
8095 sb.append((int)ai.uid);
8096 sb.append(isDebug ? " 1 " : " 0 ");
8097 sb.append(dataPath);
8098 sb.append("\n");
8099 str.write(sb.toString().getBytes());
8100 }
8101 str.flush();
8102 str.close();
8103 journal.commit();
8104 }
8105 catch (Exception e) {
8106 journal.rollback();
8107 }
8108
8109 FileUtils.setPermissions(mPackageListFilename.toString(),
8110 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8111 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8112 |FileUtils.S_IROTH,
8113 -1, -1);
8114
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008115 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008116
8117 } catch(XmlPullParserException e) {
8118 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 -08008119 } catch(java.io.IOException e) {
8120 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 -08008121 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008122 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008123 if (mSettingsFilename.exists()) {
8124 if (!mSettingsFilename.delete()) {
8125 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8126 }
8127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008128 //Debug.stopMethodTracing();
8129 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008130
8131 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008132 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008133 serializer.startTag(null, "updated-package");
8134 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008135 if (pkg.realName != null) {
8136 serializer.attribute(null, "realName", pkg.realName);
8137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008138 serializer.attribute(null, "codePath", pkg.codePathString);
8139 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008140 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008141 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8142 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8143 }
8144 if (pkg.sharedUser == null) {
8145 serializer.attribute(null, "userId",
8146 Integer.toString(pkg.userId));
8147 } else {
8148 serializer.attribute(null, "sharedUserId",
8149 Integer.toString(pkg.userId));
8150 }
8151 serializer.startTag(null, "perms");
8152 if (pkg.sharedUser == null) {
8153 // If this is a shared user, the permissions will
8154 // be written there. We still need to write an
8155 // empty permissions list so permissionsFixed will
8156 // be set.
8157 for (final String name : pkg.grantedPermissions) {
8158 BasePermission bp = mPermissions.get(name);
8159 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
8160 // We only need to write signature or system permissions but this wont
8161 // match the semantics of grantedPermissions. So write all permissions.
8162 serializer.startTag(null, "item");
8163 serializer.attribute(null, "name", name);
8164 serializer.endTag(null, "item");
8165 }
8166 }
8167 }
8168 serializer.endTag(null, "perms");
8169 serializer.endTag(null, "updated-package");
8170 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008171
8172 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008173 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008174 serializer.startTag(null, "package");
8175 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008176 if (pkg.realName != null) {
8177 serializer.attribute(null, "realName", pkg.realName);
8178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008179 serializer.attribute(null, "codePath", pkg.codePathString);
8180 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8181 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8182 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008183 serializer.attribute(null, "flags",
8184 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008185 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008186 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008187 if (pkg.sharedUser == null) {
8188 serializer.attribute(null, "userId",
8189 Integer.toString(pkg.userId));
8190 } else {
8191 serializer.attribute(null, "sharedUserId",
8192 Integer.toString(pkg.userId));
8193 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008194 if (pkg.uidError) {
8195 serializer.attribute(null, "uidError", "true");
8196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008197 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8198 serializer.attribute(null, "enabled",
8199 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8200 ? "true" : "false");
8201 }
8202 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8203 serializer.attribute(null, "installStatus", "false");
8204 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008205 if (pkg.installerPackageName != null) {
8206 serializer.attribute(null, "installer", pkg.installerPackageName);
8207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008208 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8209 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8210 serializer.startTag(null, "perms");
8211 if (pkg.sharedUser == null) {
8212 // If this is a shared user, the permissions will
8213 // be written there. We still need to write an
8214 // empty permissions list so permissionsFixed will
8215 // be set.
8216 for (final String name : pkg.grantedPermissions) {
8217 serializer.startTag(null, "item");
8218 serializer.attribute(null, "name", name);
8219 serializer.endTag(null, "item");
8220 }
8221 }
8222 serializer.endTag(null, "perms");
8223 }
8224 if (pkg.disabledComponents.size() > 0) {
8225 serializer.startTag(null, "disabled-components");
8226 for (final String name : pkg.disabledComponents) {
8227 serializer.startTag(null, "item");
8228 serializer.attribute(null, "name", name);
8229 serializer.endTag(null, "item");
8230 }
8231 serializer.endTag(null, "disabled-components");
8232 }
8233 if (pkg.enabledComponents.size() > 0) {
8234 serializer.startTag(null, "enabled-components");
8235 for (final String name : pkg.enabledComponents) {
8236 serializer.startTag(null, "item");
8237 serializer.attribute(null, "name", name);
8238 serializer.endTag(null, "item");
8239 }
8240 serializer.endTag(null, "enabled-components");
8241 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008243 serializer.endTag(null, "package");
8244 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008246 void writePermission(XmlSerializer serializer, BasePermission bp)
8247 throws XmlPullParserException, java.io.IOException {
8248 if (bp.type != BasePermission.TYPE_BUILTIN
8249 && bp.sourcePackage != null) {
8250 serializer.startTag(null, "item");
8251 serializer.attribute(null, "name", bp.name);
8252 serializer.attribute(null, "package", bp.sourcePackage);
8253 if (DEBUG_SETTINGS) Log.v(TAG,
8254 "Writing perm: name=" + bp.name + " type=" + bp.type);
8255 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8256 PermissionInfo pi = bp.perm != null ? bp.perm.info
8257 : bp.pendingInfo;
8258 if (pi != null) {
8259 serializer.attribute(null, "type", "dynamic");
8260 if (pi.icon != 0) {
8261 serializer.attribute(null, "icon",
8262 Integer.toString(pi.icon));
8263 }
8264 if (pi.nonLocalizedLabel != null) {
8265 serializer.attribute(null, "label",
8266 pi.nonLocalizedLabel.toString());
8267 }
8268 if (pi.protectionLevel !=
8269 PermissionInfo.PROTECTION_NORMAL) {
8270 serializer.attribute(null, "protection",
8271 Integer.toString(pi.protectionLevel));
8272 }
8273 }
8274 }
8275 serializer.endTag(null, "item");
8276 }
8277 }
8278
8279 String getReadMessagesLP() {
8280 return mReadMessages.toString();
8281 }
8282
Oscar Montemayora8529f62009-11-18 10:14:20 -08008283 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008284 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8285 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008286 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008287 while(its.hasNext()) {
8288 String key = its.next();
8289 PackageSetting ps = mPackages.get(key);
8290 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008291 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008292 }
8293 }
8294 return ret;
8295 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008297 boolean readLP() {
8298 FileInputStream str = null;
8299 if (mBackupSettingsFilename.exists()) {
8300 try {
8301 str = new FileInputStream(mBackupSettingsFilename);
8302 mReadMessages.append("Reading from backup settings file\n");
8303 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008304 if (mSettingsFilename.exists()) {
8305 // If both the backup and settings file exist, we
8306 // ignore the settings since it might have been
8307 // corrupted.
8308 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
8309 mSettingsFilename.delete();
8310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008311 } catch (java.io.IOException e) {
8312 // We'll try for the normal settings file.
8313 }
8314 }
8315
8316 mPastSignatures.clear();
8317
8318 try {
8319 if (str == null) {
8320 if (!mSettingsFilename.exists()) {
8321 mReadMessages.append("No settings file found\n");
8322 Log.i(TAG, "No current settings file!");
8323 return false;
8324 }
8325 str = new FileInputStream(mSettingsFilename);
8326 }
8327 XmlPullParser parser = Xml.newPullParser();
8328 parser.setInput(str, null);
8329
8330 int type;
8331 while ((type=parser.next()) != XmlPullParser.START_TAG
8332 && type != XmlPullParser.END_DOCUMENT) {
8333 ;
8334 }
8335
8336 if (type != XmlPullParser.START_TAG) {
8337 mReadMessages.append("No start tag found in settings file\n");
8338 Log.e(TAG, "No start tag found in package manager settings");
8339 return false;
8340 }
8341
8342 int outerDepth = parser.getDepth();
8343 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8344 && (type != XmlPullParser.END_TAG
8345 || parser.getDepth() > outerDepth)) {
8346 if (type == XmlPullParser.END_TAG
8347 || type == XmlPullParser.TEXT) {
8348 continue;
8349 }
8350
8351 String tagName = parser.getName();
8352 if (tagName.equals("package")) {
8353 readPackageLP(parser);
8354 } else if (tagName.equals("permissions")) {
8355 readPermissionsLP(mPermissions, parser);
8356 } else if (tagName.equals("permission-trees")) {
8357 readPermissionsLP(mPermissionTrees, parser);
8358 } else if (tagName.equals("shared-user")) {
8359 readSharedUserLP(parser);
8360 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008361 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008362 } else if (tagName.equals("preferred-activities")) {
8363 readPreferredActivitiesLP(parser);
8364 } else if(tagName.equals("updated-package")) {
8365 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008366 } else if (tagName.equals("cleaning-package")) {
8367 String name = parser.getAttributeValue(null, "name");
8368 if (name != null) {
8369 mPackagesToBeCleaned.add(name);
8370 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008371 } else if (tagName.equals("renamed-package")) {
8372 String nname = parser.getAttributeValue(null, "new");
8373 String oname = parser.getAttributeValue(null, "old");
8374 if (nname != null && oname != null) {
8375 mRenamedPackages.put(nname, oname);
8376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008377 } else {
8378 Log.w(TAG, "Unknown element under <packages>: "
8379 + parser.getName());
8380 XmlUtils.skipCurrentTag(parser);
8381 }
8382 }
8383
8384 str.close();
8385
8386 } catch(XmlPullParserException e) {
8387 mReadMessages.append("Error reading: " + e.toString());
8388 Log.e(TAG, "Error reading package manager settings", e);
8389
8390 } catch(java.io.IOException e) {
8391 mReadMessages.append("Error reading: " + e.toString());
8392 Log.e(TAG, "Error reading package manager settings", e);
8393
8394 }
8395
8396 int N = mPendingPackages.size();
8397 for (int i=0; i<N; i++) {
8398 final PendingPackage pp = mPendingPackages.get(i);
8399 Object idObj = getUserIdLP(pp.sharedId);
8400 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008401 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008402 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008403 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008404 if (p == null) {
8405 Log.w(TAG, "Unable to create application package for "
8406 + pp.name);
8407 continue;
8408 }
8409 p.copyFrom(pp);
8410 } else if (idObj != null) {
8411 String msg = "Bad package setting: package " + pp.name
8412 + " has shared uid " + pp.sharedId
8413 + " that is not a shared uid\n";
8414 mReadMessages.append(msg);
8415 Log.e(TAG, msg);
8416 } else {
8417 String msg = "Bad package setting: package " + pp.name
8418 + " has shared uid " + pp.sharedId
8419 + " that is not defined\n";
8420 mReadMessages.append(msg);
8421 Log.e(TAG, msg);
8422 }
8423 }
8424 mPendingPackages.clear();
8425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008426 mReadMessages.append("Read completed successfully: "
8427 + mPackages.size() + " packages, "
8428 + mSharedUsers.size() + " shared uids\n");
8429
8430 return true;
8431 }
8432
8433 private int readInt(XmlPullParser parser, String ns, String name,
8434 int defValue) {
8435 String v = parser.getAttributeValue(ns, name);
8436 try {
8437 if (v == null) {
8438 return defValue;
8439 }
8440 return Integer.parseInt(v);
8441 } catch (NumberFormatException e) {
8442 reportSettingsProblem(Log.WARN,
8443 "Error in package manager settings: attribute " +
8444 name + " has bad integer value " + v + " at "
8445 + parser.getPositionDescription());
8446 }
8447 return defValue;
8448 }
8449
8450 private void readPermissionsLP(HashMap<String, BasePermission> out,
8451 XmlPullParser parser)
8452 throws IOException, XmlPullParserException {
8453 int outerDepth = parser.getDepth();
8454 int type;
8455 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8456 && (type != XmlPullParser.END_TAG
8457 || parser.getDepth() > outerDepth)) {
8458 if (type == XmlPullParser.END_TAG
8459 || type == XmlPullParser.TEXT) {
8460 continue;
8461 }
8462
8463 String tagName = parser.getName();
8464 if (tagName.equals("item")) {
8465 String name = parser.getAttributeValue(null, "name");
8466 String sourcePackage = parser.getAttributeValue(null, "package");
8467 String ptype = parser.getAttributeValue(null, "type");
8468 if (name != null && sourcePackage != null) {
8469 boolean dynamic = "dynamic".equals(ptype);
8470 BasePermission bp = new BasePermission(name, sourcePackage,
8471 dynamic
8472 ? BasePermission.TYPE_DYNAMIC
8473 : BasePermission.TYPE_NORMAL);
8474 if (dynamic) {
8475 PermissionInfo pi = new PermissionInfo();
8476 pi.packageName = sourcePackage.intern();
8477 pi.name = name.intern();
8478 pi.icon = readInt(parser, null, "icon", 0);
8479 pi.nonLocalizedLabel = parser.getAttributeValue(
8480 null, "label");
8481 pi.protectionLevel = readInt(parser, null, "protection",
8482 PermissionInfo.PROTECTION_NORMAL);
8483 bp.pendingInfo = pi;
8484 }
8485 out.put(bp.name, bp);
8486 } else {
8487 reportSettingsProblem(Log.WARN,
8488 "Error in package manager settings: permissions has"
8489 + " no name at " + parser.getPositionDescription());
8490 }
8491 } else {
8492 reportSettingsProblem(Log.WARN,
8493 "Unknown element reading permissions: "
8494 + parser.getName() + " at "
8495 + parser.getPositionDescription());
8496 }
8497 XmlUtils.skipCurrentTag(parser);
8498 }
8499 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008501 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008502 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008503 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008504 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008505 String codePathStr = parser.getAttributeValue(null, "codePath");
8506 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008507 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008508 resourcePathStr = codePathStr;
8509 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008510 String version = parser.getAttributeValue(null, "version");
8511 int versionCode = 0;
8512 if (version != null) {
8513 try {
8514 versionCode = Integer.parseInt(version);
8515 } catch (NumberFormatException e) {
8516 }
8517 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008519 int pkgFlags = 0;
8520 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008521 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008522 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008523 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008524 String timeStampStr = parser.getAttributeValue(null, "ts");
8525 if (timeStampStr != null) {
8526 try {
8527 long timeStamp = Long.parseLong(timeStampStr);
8528 ps.setTimeStamp(timeStamp, timeStampStr);
8529 } catch (NumberFormatException e) {
8530 }
8531 }
8532 String idStr = parser.getAttributeValue(null, "userId");
8533 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8534 if(ps.userId <= 0) {
8535 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8536 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8537 }
8538 int outerDepth = parser.getDepth();
8539 int type;
8540 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8541 && (type != XmlPullParser.END_TAG
8542 || parser.getDepth() > outerDepth)) {
8543 if (type == XmlPullParser.END_TAG
8544 || type == XmlPullParser.TEXT) {
8545 continue;
8546 }
8547
8548 String tagName = parser.getName();
8549 if (tagName.equals("perms")) {
8550 readGrantedPermissionsLP(parser,
8551 ps.grantedPermissions);
8552 } else {
8553 reportSettingsProblem(Log.WARN,
8554 "Unknown element under <updated-package>: "
8555 + parser.getName());
8556 XmlUtils.skipCurrentTag(parser);
8557 }
8558 }
8559 mDisabledSysPackages.put(name, ps);
8560 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008562 private void readPackageLP(XmlPullParser parser)
8563 throws XmlPullParserException, IOException {
8564 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008565 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008566 String idStr = null;
8567 String sharedIdStr = null;
8568 String codePathStr = null;
8569 String resourcePathStr = null;
8570 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008571 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008572 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008573 int pkgFlags = 0;
8574 String timeStampStr;
8575 long timeStamp = 0;
8576 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008577 String version = null;
8578 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008579 try {
8580 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008581 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008582 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008583 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008584 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8585 codePathStr = parser.getAttributeValue(null, "codePath");
8586 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008587 version = parser.getAttributeValue(null, "version");
8588 if (version != null) {
8589 try {
8590 versionCode = Integer.parseInt(version);
8591 } catch (NumberFormatException e) {
8592 }
8593 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008594 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008595
8596 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008597 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008598 try {
8599 pkgFlags = Integer.parseInt(systemStr);
8600 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008601 }
8602 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008603 // For backward compatibility
8604 systemStr = parser.getAttributeValue(null, "system");
8605 if (systemStr != null) {
8606 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8607 } else {
8608 // Old settings that don't specify system... just treat
8609 // them as system, good enough.
8610 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008612 }
8613 timeStampStr = parser.getAttributeValue(null, "ts");
8614 if (timeStampStr != null) {
8615 try {
8616 timeStamp = Long.parseLong(timeStampStr);
8617 } catch (NumberFormatException e) {
8618 }
8619 }
8620 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8621 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8622 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8623 if (resourcePathStr == null) {
8624 resourcePathStr = codePathStr;
8625 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008626 if (realName != null) {
8627 realName = realName.intern();
8628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008629 if (name == null) {
8630 reportSettingsProblem(Log.WARN,
8631 "Error in package manager settings: <package> has no name at "
8632 + parser.getPositionDescription());
8633 } else if (codePathStr == null) {
8634 reportSettingsProblem(Log.WARN,
8635 "Error in package manager settings: <package> has no codePath at "
8636 + parser.getPositionDescription());
8637 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008638 packageSetting = addPackageLP(name.intern(), realName,
8639 new File(codePathStr), new File(resourcePathStr),
8640 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008641 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8642 + ": userId=" + userId + " pkg=" + packageSetting);
8643 if (packageSetting == null) {
8644 reportSettingsProblem(Log.ERROR,
8645 "Failure adding uid " + userId
8646 + " while parsing settings at "
8647 + parser.getPositionDescription());
8648 } else {
8649 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8650 }
8651 } else if (sharedIdStr != null) {
8652 userId = sharedIdStr != null
8653 ? Integer.parseInt(sharedIdStr) : 0;
8654 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008655 packageSetting = new PendingPackage(name.intern(), realName,
8656 new File(codePathStr), new File(resourcePathStr),
8657 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008658 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8659 mPendingPackages.add((PendingPackage) packageSetting);
8660 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8661 + ": sharedUserId=" + userId + " pkg="
8662 + packageSetting);
8663 } else {
8664 reportSettingsProblem(Log.WARN,
8665 "Error in package manager settings: package "
8666 + name + " has bad sharedId " + sharedIdStr
8667 + " at " + parser.getPositionDescription());
8668 }
8669 } else {
8670 reportSettingsProblem(Log.WARN,
8671 "Error in package manager settings: package "
8672 + name + " has bad userId " + idStr + " at "
8673 + parser.getPositionDescription());
8674 }
8675 } catch (NumberFormatException e) {
8676 reportSettingsProblem(Log.WARN,
8677 "Error in package manager settings: package "
8678 + name + " has bad userId " + idStr + " at "
8679 + parser.getPositionDescription());
8680 }
8681 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008682 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008683 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008684 final String enabledStr = parser.getAttributeValue(null, "enabled");
8685 if (enabledStr != null) {
8686 if (enabledStr.equalsIgnoreCase("true")) {
8687 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8688 } else if (enabledStr.equalsIgnoreCase("false")) {
8689 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
8690 } else if (enabledStr.equalsIgnoreCase("default")) {
8691 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8692 } else {
8693 reportSettingsProblem(Log.WARN,
8694 "Error in package manager settings: package "
8695 + name + " has bad enabled value: " + idStr
8696 + " at " + parser.getPositionDescription());
8697 }
8698 } else {
8699 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8700 }
8701 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
8702 if (installStatusStr != null) {
8703 if (installStatusStr.equalsIgnoreCase("false")) {
8704 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
8705 } else {
8706 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
8707 }
8708 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008710 int outerDepth = parser.getDepth();
8711 int type;
8712 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8713 && (type != XmlPullParser.END_TAG
8714 || parser.getDepth() > outerDepth)) {
8715 if (type == XmlPullParser.END_TAG
8716 || type == XmlPullParser.TEXT) {
8717 continue;
8718 }
8719
8720 String tagName = parser.getName();
8721 if (tagName.equals("disabled-components")) {
8722 readDisabledComponentsLP(packageSetting, parser);
8723 } else if (tagName.equals("enabled-components")) {
8724 readEnabledComponentsLP(packageSetting, parser);
8725 } else if (tagName.equals("sigs")) {
8726 packageSetting.signatures.readXml(parser, mPastSignatures);
8727 } else if (tagName.equals("perms")) {
8728 readGrantedPermissionsLP(parser,
8729 packageSetting.loadedPermissions);
8730 packageSetting.permissionsFixed = true;
8731 } else {
8732 reportSettingsProblem(Log.WARN,
8733 "Unknown element under <package>: "
8734 + parser.getName());
8735 XmlUtils.skipCurrentTag(parser);
8736 }
8737 }
8738 } else {
8739 XmlUtils.skipCurrentTag(parser);
8740 }
8741 }
8742
8743 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
8744 XmlPullParser parser)
8745 throws IOException, XmlPullParserException {
8746 int outerDepth = parser.getDepth();
8747 int type;
8748 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8749 && (type != XmlPullParser.END_TAG
8750 || parser.getDepth() > outerDepth)) {
8751 if (type == XmlPullParser.END_TAG
8752 || type == XmlPullParser.TEXT) {
8753 continue;
8754 }
8755
8756 String tagName = parser.getName();
8757 if (tagName.equals("item")) {
8758 String name = parser.getAttributeValue(null, "name");
8759 if (name != null) {
8760 packageSetting.disabledComponents.add(name.intern());
8761 } else {
8762 reportSettingsProblem(Log.WARN,
8763 "Error in package manager settings: <disabled-components> has"
8764 + " no name at " + parser.getPositionDescription());
8765 }
8766 } else {
8767 reportSettingsProblem(Log.WARN,
8768 "Unknown element under <disabled-components>: "
8769 + parser.getName());
8770 }
8771 XmlUtils.skipCurrentTag(parser);
8772 }
8773 }
8774
8775 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
8776 XmlPullParser parser)
8777 throws IOException, XmlPullParserException {
8778 int outerDepth = parser.getDepth();
8779 int type;
8780 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8781 && (type != XmlPullParser.END_TAG
8782 || parser.getDepth() > outerDepth)) {
8783 if (type == XmlPullParser.END_TAG
8784 || type == XmlPullParser.TEXT) {
8785 continue;
8786 }
8787
8788 String tagName = parser.getName();
8789 if (tagName.equals("item")) {
8790 String name = parser.getAttributeValue(null, "name");
8791 if (name != null) {
8792 packageSetting.enabledComponents.add(name.intern());
8793 } else {
8794 reportSettingsProblem(Log.WARN,
8795 "Error in package manager settings: <enabled-components> has"
8796 + " no name at " + parser.getPositionDescription());
8797 }
8798 } else {
8799 reportSettingsProblem(Log.WARN,
8800 "Unknown element under <enabled-components>: "
8801 + parser.getName());
8802 }
8803 XmlUtils.skipCurrentTag(parser);
8804 }
8805 }
8806
8807 private void readSharedUserLP(XmlPullParser parser)
8808 throws XmlPullParserException, IOException {
8809 String name = null;
8810 String idStr = null;
8811 int pkgFlags = 0;
8812 SharedUserSetting su = null;
8813 try {
8814 name = parser.getAttributeValue(null, "name");
8815 idStr = parser.getAttributeValue(null, "userId");
8816 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8817 if ("true".equals(parser.getAttributeValue(null, "system"))) {
8818 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8819 }
8820 if (name == null) {
8821 reportSettingsProblem(Log.WARN,
8822 "Error in package manager settings: <shared-user> has no name at "
8823 + parser.getPositionDescription());
8824 } else if (userId == 0) {
8825 reportSettingsProblem(Log.WARN,
8826 "Error in package manager settings: shared-user "
8827 + name + " has bad userId " + idStr + " at "
8828 + parser.getPositionDescription());
8829 } else {
8830 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
8831 reportSettingsProblem(Log.ERROR,
8832 "Occurred while parsing settings at "
8833 + parser.getPositionDescription());
8834 }
8835 }
8836 } catch (NumberFormatException e) {
8837 reportSettingsProblem(Log.WARN,
8838 "Error in package manager settings: package "
8839 + name + " has bad userId " + idStr + " at "
8840 + parser.getPositionDescription());
8841 };
8842
8843 if (su != null) {
8844 int outerDepth = parser.getDepth();
8845 int type;
8846 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8847 && (type != XmlPullParser.END_TAG
8848 || parser.getDepth() > outerDepth)) {
8849 if (type == XmlPullParser.END_TAG
8850 || type == XmlPullParser.TEXT) {
8851 continue;
8852 }
8853
8854 String tagName = parser.getName();
8855 if (tagName.equals("sigs")) {
8856 su.signatures.readXml(parser, mPastSignatures);
8857 } else if (tagName.equals("perms")) {
8858 readGrantedPermissionsLP(parser, su.loadedPermissions);
8859 } else {
8860 reportSettingsProblem(Log.WARN,
8861 "Unknown element under <shared-user>: "
8862 + parser.getName());
8863 XmlUtils.skipCurrentTag(parser);
8864 }
8865 }
8866
8867 } else {
8868 XmlUtils.skipCurrentTag(parser);
8869 }
8870 }
8871
8872 private void readGrantedPermissionsLP(XmlPullParser parser,
8873 HashSet<String> outPerms) throws IOException, XmlPullParserException {
8874 int outerDepth = parser.getDepth();
8875 int type;
8876 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8877 && (type != XmlPullParser.END_TAG
8878 || parser.getDepth() > outerDepth)) {
8879 if (type == XmlPullParser.END_TAG
8880 || type == XmlPullParser.TEXT) {
8881 continue;
8882 }
8883
8884 String tagName = parser.getName();
8885 if (tagName.equals("item")) {
8886 String name = parser.getAttributeValue(null, "name");
8887 if (name != null) {
8888 outPerms.add(name.intern());
8889 } else {
8890 reportSettingsProblem(Log.WARN,
8891 "Error in package manager settings: <perms> has"
8892 + " no name at " + parser.getPositionDescription());
8893 }
8894 } else {
8895 reportSettingsProblem(Log.WARN,
8896 "Unknown element under <perms>: "
8897 + parser.getName());
8898 }
8899 XmlUtils.skipCurrentTag(parser);
8900 }
8901 }
8902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008903 private void readPreferredActivitiesLP(XmlPullParser parser)
8904 throws XmlPullParserException, IOException {
8905 int outerDepth = parser.getDepth();
8906 int type;
8907 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8908 && (type != XmlPullParser.END_TAG
8909 || parser.getDepth() > outerDepth)) {
8910 if (type == XmlPullParser.END_TAG
8911 || type == XmlPullParser.TEXT) {
8912 continue;
8913 }
8914
8915 String tagName = parser.getName();
8916 if (tagName.equals("item")) {
8917 PreferredActivity pa = new PreferredActivity(parser);
8918 if (pa.mParseError == null) {
8919 mPreferredActivities.addFilter(pa);
8920 } else {
8921 reportSettingsProblem(Log.WARN,
8922 "Error in package manager settings: <preferred-activity> "
8923 + pa.mParseError + " at "
8924 + parser.getPositionDescription());
8925 }
8926 } else {
8927 reportSettingsProblem(Log.WARN,
8928 "Unknown element under <preferred-activities>: "
8929 + parser.getName());
8930 XmlUtils.skipCurrentTag(parser);
8931 }
8932 }
8933 }
8934
8935 // Returns -1 if we could not find an available UserId to assign
8936 private int newUserIdLP(Object obj) {
8937 // Let's be stupidly inefficient for now...
8938 final int N = mUserIds.size();
8939 for (int i=0; i<N; i++) {
8940 if (mUserIds.get(i) == null) {
8941 mUserIds.set(i, obj);
8942 return FIRST_APPLICATION_UID + i;
8943 }
8944 }
8945
8946 // None left?
8947 if (N >= MAX_APPLICATION_UIDS) {
8948 return -1;
8949 }
8950
8951 mUserIds.add(obj);
8952 return FIRST_APPLICATION_UID + N;
8953 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008955 public PackageSetting getDisabledSystemPkg(String name) {
8956 synchronized(mPackages) {
8957 PackageSetting ps = mDisabledSysPackages.get(name);
8958 return ps;
8959 }
8960 }
8961
8962 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
8963 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
8964 if (Config.LOGV) {
8965 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
8966 + " componentName = " + componentInfo.name);
8967 Log.v(TAG, "enabledComponents: "
8968 + Arrays.toString(packageSettings.enabledComponents.toArray()));
8969 Log.v(TAG, "disabledComponents: "
8970 + Arrays.toString(packageSettings.disabledComponents.toArray()));
8971 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008972 if (packageSettings == null) {
8973 if (false) {
8974 Log.w(TAG, "WAITING FOR DEBUGGER");
8975 Debug.waitForDebugger();
8976 Log.i(TAG, "We will crash!");
8977 }
8978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008979 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
8980 || ((componentInfo.enabled
8981 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
8982 || (componentInfo.applicationInfo.enabled
8983 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
8984 && !packageSettings.disabledComponents.contains(componentInfo.name))
8985 || packageSettings.enabledComponents.contains(componentInfo.name));
8986 }
8987 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008988
8989 // ------- apps on sdcard specific code -------
8990 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008991 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08008992 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008993 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008994 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008995
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008996 private String getEncryptKey() {
8997 try {
8998 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8999 if (sdEncKey == null) {
9000 sdEncKey = SystemKeyStore.getInstance().
9001 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9002 if (sdEncKey == null) {
9003 Log.e(TAG, "Failed to create encryption keys");
9004 return null;
9005 }
9006 }
9007 return sdEncKey;
9008 } catch (NoSuchAlgorithmException nsae) {
9009 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
9010 return null;
9011 }
9012 }
9013
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009014 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009015 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009016 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009017 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009018 if (list != null) {
9019 int idx = 0;
9020 int idList[] = new int[MAX_CONTAINERS];
9021 boolean neverFound = true;
9022 for (String name : list) {
9023 // Ignore null entries
9024 if (name == null) {
9025 continue;
9026 }
9027 int sidx = name.indexOf(prefix);
9028 if (sidx == -1) {
9029 // Not a temp file. just ignore
9030 continue;
9031 }
9032 String subStr = name.substring(sidx + prefix.length());
9033 idList[idx] = -1;
9034 if (subStr != null) {
9035 try {
9036 int cid = Integer.parseInt(subStr);
9037 idList[idx++] = cid;
9038 neverFound = false;
9039 } catch (NumberFormatException e) {
9040 }
9041 }
9042 }
9043 if (!neverFound) {
9044 // Sort idList
9045 Arrays.sort(idList);
9046 for (int j = 1; j <= idList.length; j++) {
9047 if (idList[j-1] != j) {
9048 tmpIdx = j;
9049 break;
9050 }
9051 }
9052 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009053 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009054 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009055 }
9056
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009057 /*
9058 * Return true if PackageManager does have packages to be updated.
9059 */
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009060 public boolean updateExternalMediaStatus(final boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009061 final boolean ret;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009062 synchronized (mPackages) {
9063 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9064 mediaStatus+", mMediaMounted=" + mMediaMounted);
9065 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009066 return false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009067 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009068 mMediaMounted = mediaStatus;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009069 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_EXTERNAL_STORAGE);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009070 ret = appList != null && appList.size() > 0;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009071 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009072 // Queue up an async operation since the package installation may take a little while.
9073 mHandler.post(new Runnable() {
9074 public void run() {
9075 mHandler.removeCallbacks(this);
9076 updateExternalMediaStatusInner(mediaStatus, ret);
9077 }
9078 });
9079 return ret;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009080 }
9081
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009082 private void updateExternalMediaStatusInner(boolean mediaStatus,
9083 boolean sendUpdateBroadcast) {
9084 // If we are up here that means there are packages to be
9085 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009086 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009087 if (list == null || list.length == 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009088 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009089 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009090
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009091 int uidList[] = new int[list.length];
9092 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009093 HashSet<String> removeCids = new HashSet<String>();
9094 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9095 /*HashMap<String, String> cidPathMap = new HashMap<String, String>();
9096 // Don't hold any locks when getting cache paths
9097 for (String cid : list) {
9098 String cpath = PackageHelper.getSdDir(cid);
9099 if (cpath == null) {
9100 removeCids.add(cid);
9101 } else {
9102 cidPathMap.put(cid, cpath);
9103 }
9104 }*/
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009105 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009106 for (String cid : list) {
9107 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009108 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9109 boolean failed = true;
9110 try {
9111 String pkgName = args.getPackageName();
9112 if (pkgName == null) {
9113 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009114 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009115 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9116 PackageSetting ps = mSettings.mPackages.get(pkgName);
9117 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009118 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009119 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9120 " corresponds to pkg : " + pkgName +
9121 " at code path: " + ps.codePathString);
9122 // We do have a valid package installed on sdcard
9123 processCids.put(args, ps.codePathString);
9124 failed = false;
9125 int uid = ps.userId;
9126 if (uid != -1) {
9127 uidList[num++] = uid;
9128 }
9129 }
9130 } finally {
9131 if (failed) {
9132 // Stale container on sdcard. Just delete
9133 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9134 removeCids.add(cid);
9135 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009136 }
9137 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009138 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009139 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009140 int uidArr[] = null;
9141 if (num > 0) {
9142 // Sort uid list
9143 Arrays.sort(uidList, 0, num);
9144 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009145 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009146 uidArr[0] = uidList[0];
9147 int di = 0;
9148 for (int i = 1; i < num; i++) {
9149 if (uidList[i-1] != uidList[i]) {
9150 uidArr[di++] = uidList[i];
9151 }
9152 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009153 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009154 // Process packages with valid entries.
9155 if (mediaStatus) {
9156 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
9157 loadMediaPackages(processCids, uidArr, sendUpdateBroadcast, removeCids);
9158 startCleaningPackages();
9159 } else {
9160 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
9161 unloadMediaPackages(processCids, uidArr, sendUpdateBroadcast);
9162 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009163 }
9164
9165 private void sendResourcesChangedBroadcast(boolean mediaStatus,
9166 ArrayList<String> pkgList, int uidArr[]) {
9167 int size = pkgList.size();
9168 if (size > 0) {
9169 // Send broadcasts here
9170 Bundle extras = new Bundle();
9171 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9172 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009173 if (uidArr != null) {
9174 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9175 }
9176 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9177 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009178 sendPackageBroadcast(action, null, extras);
9179 }
9180 }
9181
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009182 /*
9183 * Look at potentially valid container ids from processCids
9184 * If package information doesn't match the one on record
9185 * or package scanning fails, the cid is added to list of
9186 * removeCids and cleaned up. Since cleaning up containers
9187 * involves destroying them, we do not want any parse
9188 * references to such stale containers. So force gc's
9189 * to avoid unnecessary crashes.
9190 */
9191 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
9192 int uidArr[], boolean sendUpdateBroadcast,
9193 HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009194 ArrayList<String> pkgList = new ArrayList<String>();
9195 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009196 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009197 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009198 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009199 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9200 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009201 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009202 try {
9203 // Make sure there are no container errors first.
9204 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9205 != PackageManager.INSTALL_SUCCEEDED) {
9206 Log.e(TAG, "Failed to mount cid : " + args.cid +
9207 " when installing from sdcard");
9208 continue;
9209 }
9210 // Check code path here.
9211 if (codePath == null || !codePath.equals(args.getCodePath())) {
9212 Log.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
9213 " does not match one in settings " + codePath);
9214 continue;
9215 }
9216 // Parse package
9217 int parseFlags = PackageParser.PARSE_CHATTY |
9218 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
9219 PackageParser pp = new PackageParser(codePath);
9220 pp.setSeparateProcesses(mSeparateProcesses);
9221 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
9222 codePath, mMetrics, parseFlags);
9223 pp = null;
9224 doGc = true;
9225 // Check for parse errors
9226 if (pkg == null) {
9227 Log.e(TAG, "Parse error when installing install pkg : "
9228 + args.cid + " from " + args.cachePath);
9229 continue;
9230 }
9231 setApplicationInfoPaths(pkg, codePath, codePath);
9232 synchronized (mInstallLock) {
9233 // Scan the package
9234 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
9235 synchronized (mPackages) {
9236 // Grant permissions
9237 grantPermissionsLP(pkg, false);
9238 // Persist settings
9239 mSettings.writeLP();
9240 retCode = PackageManager.INSTALL_SUCCEEDED;
9241 pkgList.add(pkg.packageName);
9242 // Post process args
9243 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9244 }
9245 } else {
9246 Log.i(TAG, "Failed to install pkg: " +
9247 pkg.packageName + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009248 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009249 }
9250
9251 } finally {
9252 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9253 // Don't destroy container here. Wait till gc clears things up.
9254 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009255 }
9256 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009257 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009258 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009259 if (sendUpdateBroadcast) {
9260 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9261 }
9262 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009263 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009264 }
9265 // Delete any stale containers if needed.
9266 if (removeCids != null) {
9267 for (String cid : removeCids) {
9268 Log.i(TAG, "Destroying stale container : " + cid);
9269 PackageHelper.destroySdDir(cid);
9270 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009271 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009272 }
9273
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009274 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
9275 int uidArr[], boolean sendUpdateBroadcast) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009276 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009277 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009278 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009279 Set<SdInstallArgs> keys = processCids.keySet();
9280 for (SdInstallArgs args : keys) {
9281 String cid = args.cid;
9282 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009283 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009284 // Delete package internally
9285 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9286 synchronized (mInstallLock) {
9287 boolean res = deletePackageLI(pkgName, false,
9288 PackageManager.DONT_DELETE_DATA, outInfo);
9289 if (res) {
9290 pkgList.add(pkgName);
9291 } else {
9292 Log.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009293 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009294 }
9295 }
9296 }
9297 // Send broadcasts
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009298 if (sendUpdateBroadcast) {
9299 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009300 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009301 // Force gc
9302 Runtime.getRuntime().gc();
9303 // Just unmount all valid containers.
9304 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009305 synchronized (mInstallLock) {
9306 args.doPostDeleteLI(false);
9307 }
9308 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009309 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009310
9311 public void movePackage(final String packageName,
9312 final IPackageMoveObserver observer, final int flags) {
9313 if (packageName == null) {
9314 return;
9315 }
9316 mContext.enforceCallingOrSelfPermission(
9317 android.Manifest.permission.MOVE_PACKAGE, null);
9318 int returnCode = PackageManager.MOVE_SUCCEEDED;
9319 int currFlags = 0;
9320 int newFlags = 0;
9321 synchronized (mPackages) {
9322 PackageParser.Package pkg = mPackages.get(packageName);
9323 if (pkg == null) {
9324 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9325 }
9326 // Disable moving fwd locked apps and system packages
9327 if (pkg.applicationInfo != null &&
9328 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9329 Log.w(TAG, "Cannot move system application");
9330 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9331 } else if (pkg.applicationInfo != null &&
9332 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9333 Log.w(TAG, "Cannot move forward locked app.");
9334 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9335 } else {
9336 // Find install location first
9337 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9338 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9339 Log.w(TAG, "Ambigous flags specified for move location.");
9340 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9341 } else {
9342 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9343 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009344 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009345 PackageManager.INSTALL_EXTERNAL : 0;
9346 if (newFlags == currFlags) {
9347 Log.w(TAG, "No move required. Trying to move to same location");
9348 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9349 }
9350 }
9351 }
9352 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9353 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9354 } else {
9355 Message msg = mHandler.obtainMessage(INIT_COPY);
9356 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9357 pkg.applicationInfo.publicSourceDir);
9358 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9359 packageName);
9360 msg.obj = mp;
9361 mHandler.sendMessage(msg);
9362 }
9363 }
9364 }
9365
9366 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9367 // Queue up an async operation since the package deletion may take a little while.
9368 mHandler.post(new Runnable() {
9369 public void run() {
9370 mHandler.removeCallbacks(this);
9371 int returnCode = currentStatus;
9372 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9373 if (moveSucceeded) {
9374 int uid = -1;
9375 synchronized (mPackages) {
9376 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9377 }
9378 ArrayList<String> pkgList = new ArrayList<String>();
9379 pkgList.add(mp.packageName);
9380 int uidArr[] = new int[] { uid };
9381 // Send resources unavailable broadcast
9382 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9383
9384 // Update package code and resource paths
9385 synchronized (mPackages) {
9386 PackageParser.Package pkg = mPackages.get(mp.packageName);
9387 if (pkg != null) {
9388 String oldCodePath = pkg.mPath;
9389 String newCodePath = mp.targetArgs.getCodePath();
9390 String newResPath = mp.targetArgs.getResourcePath();
9391 pkg.mPath = newCodePath;
9392 // Move dex files around
9393 if (moveDexFiles(pkg)
9394 != PackageManager.INSTALL_SUCCEEDED) {
9395 // Moving of dex files failed. Set
9396 // error code and abort move.
9397 pkg.mPath = pkg.mScanPath;
9398 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9399 moveSucceeded = false;
9400 } else {
9401 pkg.mScanPath = newCodePath;
9402 pkg.applicationInfo.sourceDir = newCodePath;
9403 pkg.applicationInfo.publicSourceDir = newResPath;
9404 PackageSetting ps = (PackageSetting) pkg.mExtras;
9405 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9406 ps.codePathString = ps.codePath.getPath();
9407 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9408 ps.resourcePathString = ps.resourcePath.getPath();
9409 // Set the application info flag correctly.
9410 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009411 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009412 } else {
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009413 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009414 }
9415 ps.setFlags(pkg.applicationInfo.flags);
9416 mAppDirs.remove(oldCodePath);
9417 mAppDirs.put(newCodePath, pkg);
9418 // Persist settings
9419 mSettings.writeLP();
9420 }
9421 }
9422 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009423 // Send resources available broadcast
9424 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009425 }
9426 if (!moveSucceeded){
9427 // Clean up failed installation
9428 if (mp.targetArgs != null) {
9429 mp.targetArgs.doPostInstall(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009430 returnCode);
9431 }
9432 } else {
9433 // Force a gc to clear things up.
9434 Runtime.getRuntime().gc();
9435 // Delete older code
9436 synchronized (mInstallLock) {
9437 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009438 }
9439 }
9440 IPackageMoveObserver observer = mp.observer;
9441 if (observer != null) {
9442 try {
9443 observer.packageMoved(mp.packageName, returnCode);
9444 } catch (RemoteException e) {
9445 Log.i(TAG, "Observer no longer exists.");
9446 }
9447 }
9448 }
9449 });
9450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009451}