blob: 818e99e6f221aa74803ed035a075f1c3803b09d2 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080021import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080022import com.android.internal.util.FastXmlSerializer;
23import com.android.internal.util.XmlUtils;
David 'Digit' Turneradd13762010-02-03 17:34:58 -080024import com.android.server.JournaledFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025
26import org.xmlpull.v1.XmlPullParser;
27import org.xmlpull.v1.XmlPullParserException;
28import org.xmlpull.v1.XmlSerializer;
29
30import android.app.ActivityManagerNative;
31import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080032import android.app.admin.DevicePolicyManager;
33import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080034import android.app.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.content.Context;
37import android.content.Intent;
38import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070039import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080040import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070041import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.pm.ActivityInfo;
43import android.content.pm.ApplicationInfo;
44import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070045import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.pm.IPackageDataObserver;
47import android.content.pm.IPackageDeleteObserver;
48import android.content.pm.IPackageInstallObserver;
49import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080050import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.content.pm.IPackageStatsObserver;
52import android.content.pm.InstrumentationInfo;
53import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080054import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.content.pm.PackageManager;
56import android.content.pm.PackageStats;
57import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
59import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.content.pm.PackageParser;
61import android.content.pm.PermissionInfo;
62import android.content.pm.PermissionGroupInfo;
63import android.content.pm.ProviderInfo;
64import android.content.pm.ResolveInfo;
65import android.content.pm.ServiceInfo;
66import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.net.Uri;
68import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070069import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080071import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080073import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070074import android.os.Looper;
75import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.os.Parcel;
77import android.os.RemoteException;
78import android.os.Environment;
79import android.os.FileObserver;
80import android.os.FileUtils;
81import android.os.Handler;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080082import android.os.StatFs;
San Mehatb1043402010-02-05 08:26:50 -080083import android.os.storage.StorageResultCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.os.ParcelFileDescriptor;
85import android.os.Process;
86import android.os.ServiceManager;
87import android.os.SystemClock;
88import android.os.SystemProperties;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080089import android.provider.Settings;
Oscar Montemayord02546b2010-01-14 16:38:40 -080090import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.util.*;
92import android.view.Display;
93import android.view.WindowManager;
94
95import java.io.File;
96import java.io.FileDescriptor;
97import java.io.FileInputStream;
98import java.io.FileNotFoundException;
99import java.io.FileOutputStream;
100import java.io.FileReader;
101import java.io.FilenameFilter;
102import java.io.IOException;
103import java.io.InputStream;
104import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800105import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800106import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.ArrayList;
108import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700109import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.Collections;
111import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800112import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import java.util.Enumeration;
114import java.util.HashMap;
115import java.util.HashSet;
116import java.util.Iterator;
117import java.util.List;
118import java.util.Map;
119import java.util.Set;
120import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800121import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import java.util.zip.ZipFile;
123import java.util.zip.ZipOutputStream;
124
125class PackageManagerService extends IPackageManager.Stub {
126 private static final String TAG = "PackageManager";
127 private static final boolean DEBUG_SETTINGS = false;
128 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800129 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800130 private static final boolean DEBUG_INSTALL = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131
132 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
133 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400134 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 private static final int FIRST_APPLICATION_UID =
136 Process.FIRST_APPLICATION_UID;
137 private static final int MAX_APPLICATION_UIDS = 1000;
138
139 private static final boolean SHOW_INFO = false;
140
141 private static final boolean GET_CERTIFICATES = true;
142
Oscar Montemayora8529f62009-11-18 10:14:20 -0800143 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 private static final int REMOVE_EVENTS =
146 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
147 private static final int ADD_EVENTS =
148 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
149
150 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800151 // Suffix used during package installation when copying/moving
152 // package apks to install directory.
153 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800155 /**
156 * Indicates the state of installation. Used by PackageManager to
157 * figure out incomplete installations. Say a package is being installed
158 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
159 * the package installation is successful or unsuccesful lin which case
160 * the PackageManager will no longer maintain state information associated
161 * with the package. If some exception(like device freeze or battery being
162 * pulled out) occurs during installation of a package, the PackageManager
163 * needs this information to clean up the previously failed installation.
164 */
165 private static final int PKG_INSTALL_INCOMPLETE = 0;
166 private static final int PKG_INSTALL_COMPLETE = 1;
167
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 static final int SCAN_MONITOR = 1<<0;
169 static final int SCAN_NO_DEX = 1<<1;
170 static final int SCAN_FORCE_DEX = 1<<2;
171 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800172 static final int SCAN_NEW_INSTALL = 1<<4;
173 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800175 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
176 "com.android.defcontainer",
177 "com.android.defcontainer.DefaultContainerService");
178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
180 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700181 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182
Dianne Hackborn851a5412009-05-08 12:06:44 -0700183 final int mSdkVersion = Build.VERSION.SDK_INT;
184 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
185 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 final Context mContext;
188 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700189 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 final DisplayMetrics mMetrics;
191 final int mDefParseFlags;
192 final String[] mSeparateProcesses;
193
194 // This is where all application persistent data goes.
195 final File mAppDataDir;
196
Oscar Montemayora8529f62009-11-18 10:14:20 -0800197 // If Encrypted File System feature is enabled, all application persistent data
198 // should go here instead.
199 final File mSecureAppDataDir;
200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 // This is the object monitoring the framework dir.
202 final FileObserver mFrameworkInstallObserver;
203
204 // This is the object monitoring the system app dir.
205 final FileObserver mSystemInstallObserver;
206
207 // This is the object monitoring mAppInstallDir.
208 final FileObserver mAppInstallObserver;
209
210 // This is the object monitoring mDrmAppPrivateInstallDir.
211 final FileObserver mDrmAppInstallObserver;
212
213 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
214 // LOCK HELD. Can be called with mInstallLock held.
215 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 final File mFrameworkDir;
218 final File mSystemAppDir;
219 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700220 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221
222 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
223 // apps.
224 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 // Lock for state used when installing and doing other long running
229 // operations. Methods that must be called with this lock held have
230 // the prefix "LI".
231 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 // These are the directories in the 3rd party applications installed dir
234 // that we have currently loaded packages from. Keys are the application's
235 // installed zip file (absolute codePath), and values are Package.
236 final HashMap<String, PackageParser.Package> mAppDirs =
237 new HashMap<String, PackageParser.Package>();
238
239 // Information for the parser to write more useful error messages.
240 File mScanningPath;
241 int mLastScanError;
242
243 final int[] mOutPermissions = new int[3];
244
245 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 // Keys are String (package name), values are Package. This also serves
248 // as the lock for the global state. Methods that must be called with
249 // this lock held have the prefix "LP".
250 final HashMap<String, PackageParser.Package> mPackages =
251 new HashMap<String, PackageParser.Package>();
252
253 final Settings mSettings;
254 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255
256 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
257 int[] mGlobalGids;
258
259 // These are the built-in uid -> permission mappings that were read from the
260 // etc/permissions.xml file.
261 final SparseArray<HashSet<String>> mSystemPermissions =
262 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 // These are the built-in shared libraries that were read from the
265 // etc/permissions.xml file.
266 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800267
Dianne Hackborn49237342009-08-27 20:08:01 -0700268 // Temporary for building the final shared libraries for an .apk.
269 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800270
Dianne Hackborn49237342009-08-27 20:08:01 -0700271 // These are the features this devices supports that were read from the
272 // etc/permissions.xml file.
273 final HashMap<String, FeatureInfo> mAvailableFeatures =
274 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 // All available activities, for your resolving pleasure.
277 final ActivityIntentResolver mActivities =
278 new ActivityIntentResolver();
279
280 // All available receivers, for your resolving pleasure.
281 final ActivityIntentResolver mReceivers =
282 new ActivityIntentResolver();
283
284 // All available services, for your resolving pleasure.
285 final ServiceIntentResolver mServices = new ServiceIntentResolver();
286
287 // Keys are String (provider class name), values are Provider.
288 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
289 new HashMap<ComponentName, PackageParser.Provider>();
290
291 // Mapping from provider base names (first directory in content URI codePath)
292 // to the provider information.
293 final HashMap<String, PackageParser.Provider> mProviders =
294 new HashMap<String, PackageParser.Provider>();
295
296 // Mapping from instrumentation class names to info about them.
297 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
298 new HashMap<ComponentName, PackageParser.Instrumentation>();
299
300 // Mapping from permission names to info about them.
301 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
302 new HashMap<String, PackageParser.PermissionGroup>();
303
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800304 // Packages whose data we have transfered into another package, thus
305 // should no longer exist.
306 final HashSet<String> mTransferedPackages = new HashSet<String>();
307
Dianne Hackborn854060af2009-07-09 18:14:31 -0700308 // Broadcast actions that are only available to the system.
309 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 boolean mSystemReady;
312 boolean mSafeMode;
313 boolean mHasSystemUidErrors;
314
315 ApplicationInfo mAndroidApplication;
316 final ActivityInfo mResolveActivity = new ActivityInfo();
317 final ResolveInfo mResolveInfo = new ResolveInfo();
318 ComponentName mResolveComponentName;
319 PackageParser.Package mPlatformPackage;
320
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700321 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800322 final HashMap<String, ArrayList<String>> mPendingBroadcasts
323 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800324 // Service Connection to remote media container service to copy
325 // package uri's from external media onto secure containers
326 // or internal storage.
327 private IMediaContainerService mContainerService = null;
328
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700329 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800330 static final int MCS_BOUND = 3;
331 static final int END_COPY = 4;
332 static final int INIT_COPY = 5;
333 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800334 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800335 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800336 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800337 static final int MCS_RECONNECT = 10;
338 static final int MCS_GIVE_UP = 11;
339
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700340 // Delay time in millisecs
341 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800342 final private DefaultContainerConnection mDefContainerConn =
343 new DefaultContainerConnection();
344 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800345 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800346 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800347 IMediaContainerService imcs =
348 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800349 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800350 }
351
352 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800353 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800354 }
355 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700356
Christopher Tate1bb69062010-02-19 17:02:12 -0800357 // Recordkeeping of restore-after-install operations that are currently in flight
358 // between the Package Manager and the Backup Manager
359 class PostInstallData {
360 public InstallArgs args;
361 public PackageInstalledInfo res;
362
363 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
364 args = _a;
365 res = _r;
366 }
367 };
368 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
369 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
370
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700371 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800372 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800373 final ArrayList<HandlerParams> mPendingInstalls =
374 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800375
376 private boolean connectToService() {
377 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
378 " DefaultContainerService");
379 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
380 if (mContext.bindService(service, mDefContainerConn,
381 Context.BIND_AUTO_CREATE)) {
382 mBound = true;
383 return true;
384 }
385 return false;
386 }
387
388 private void disconnectService() {
389 mContainerService = null;
390 mBound = false;
391 mContext.unbindService(mDefContainerConn);
392 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800393
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700394 PackageHandler(Looper looper) {
395 super(looper);
396 }
397 public void handleMessage(Message msg) {
398 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800399 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800400 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800401 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800402 int idx = mPendingInstalls.size();
403 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
404 // If a bind was already initiated we dont really
405 // need to do anything. The pending install
406 // will be processed later on.
407 if (!mBound) {
408 // If this is the only one pending we might
409 // have to bind to the service again.
410 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800411 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800412 params.serviceError();
413 return;
414 } else {
415 // Once we bind to the service, the first
416 // pending request will be processed.
417 mPendingInstalls.add(idx, params);
418 }
419 } else {
420 mPendingInstalls.add(idx, params);
421 // Already bound to the service. Just make
422 // sure we trigger off processing the first request.
423 if (idx == 0) {
424 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800425 }
426 }
427 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800428 }
429 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800430 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800431 if (msg.obj != null) {
432 mContainerService = (IMediaContainerService) msg.obj;
433 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800434 if (mContainerService == null) {
435 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800436 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800437 for (HandlerParams params : mPendingInstalls) {
438 mPendingInstalls.remove(0);
439 // Indicate service bind error
440 params.serviceError();
441 }
442 mPendingInstalls.clear();
443 } else if (mPendingInstalls.size() > 0) {
444 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800445 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800446 params.startCopy();
447 }
448 } else {
449 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800450 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800451 }
452 break;
453 }
454 case MCS_RECONNECT : {
455 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
456 if (mPendingInstalls.size() > 0) {
457 if (mBound) {
458 disconnectService();
459 }
460 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800461 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800462 for (HandlerParams params : mPendingInstalls) {
463 mPendingInstalls.remove(0);
464 // Indicate service bind error
465 params.serviceError();
466 }
467 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800468 }
469 }
470 break;
471 }
472 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800473 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
474 // Delete pending install
475 if (mPendingInstalls.size() > 0) {
476 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800477 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800478 if (mPendingInstalls.size() == 0) {
479 if (mBound) {
480 disconnectService();
481 }
482 } else {
483 // There are more pending requests in queue.
484 // Just post MCS_BOUND message to trigger processing
485 // of next pending install.
486 mHandler.sendEmptyMessage(MCS_BOUND);
487 }
488 break;
489 }
490 case MCS_GIVE_UP: {
491 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
492 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800493 break;
494 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700495 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800496 String packages[];
497 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700498 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700499 int uids[];
500 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800501 if (mPendingBroadcasts == null) {
502 return;
503 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700504 size = mPendingBroadcasts.size();
505 if (size <= 0) {
506 // Nothing to be done. Just return
507 return;
508 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800509 packages = new String[size];
510 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700511 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800512 Iterator<HashMap.Entry<String, ArrayList<String>>>
513 it = mPendingBroadcasts.entrySet().iterator();
514 int i = 0;
515 while (it.hasNext() && i < size) {
516 HashMap.Entry<String, ArrayList<String>> ent = it.next();
517 packages[i] = ent.getKey();
518 components[i] = ent.getValue();
519 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700520 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800521 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700522 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800523 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700524 mPendingBroadcasts.clear();
525 }
526 // Send broadcasts
527 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800528 sendPackageChangedBroadcast(packages[i], true,
529 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700530 }
531 break;
532 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800533 case START_CLEANING_PACKAGE: {
534 String packageName = (String)msg.obj;
535 synchronized (mPackages) {
536 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
537 mSettings.mPackagesToBeCleaned.add(packageName);
538 }
539 }
540 startCleaningPackages();
541 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800542 case POST_INSTALL: {
543 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
544 PostInstallData data = mRunningInstalls.get(msg.arg1);
545 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800546 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800547
548 if (data != null) {
549 InstallArgs args = data.args;
550 PackageInstalledInfo res = data.res;
551
552 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
553 res.removedInfo.sendBroadcast(false, true);
554 Bundle extras = new Bundle(1);
555 extras.putInt(Intent.EXTRA_UID, res.uid);
556 final boolean update = res.removedInfo.removedPackage != null;
557 if (update) {
558 extras.putBoolean(Intent.EXTRA_REPLACING, true);
559 }
560 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
561 res.pkg.applicationInfo.packageName,
562 extras);
563 if (update) {
564 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
565 res.pkg.applicationInfo.packageName,
566 extras);
567 }
568 if (res.removedInfo.args != null) {
569 // Remove the replaced package's older resources safely now
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800570 deleteOld = true;
Christopher Tate1bb69062010-02-19 17:02:12 -0800571 }
572 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800573 // Force a gc to clear up things
Christopher Tate1bb69062010-02-19 17:02:12 -0800574 Runtime.getRuntime().gc();
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800575 // We delete after a gc for applications on sdcard.
576 if (deleteOld) {
577 synchronized (mInstallLock) {
578 res.removedInfo.args.doPostDeleteLI(true);
579 }
580 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800581 if (args.observer != null) {
582 try {
583 args.observer.packageInstalled(res.name, res.returnCode);
584 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800585 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800586 }
587 }
588 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800589 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800590 }
591 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700592 }
593 }
594 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800595
596 static boolean installOnSd(int flags) {
597 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800598 ((flags & PackageManager.INSTALL_EXTERNAL) == 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800599 return false;
600 }
601 return true;
602 }
603
604 static boolean isFwdLocked(int flags) {
605 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
606 return true;
607 }
608 return false;
609 }
610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 public static final IPackageManager main(Context context, boolean factoryTest) {
612 PackageManagerService m = new PackageManagerService(context, factoryTest);
613 ServiceManager.addService("package", m);
614 return m;
615 }
616
617 static String[] splitString(String str, char sep) {
618 int count = 1;
619 int i = 0;
620 while ((i=str.indexOf(sep, i)) >= 0) {
621 count++;
622 i++;
623 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 String[] res = new String[count];
626 i=0;
627 count = 0;
628 int lastI=0;
629 while ((i=str.indexOf(sep, i)) >= 0) {
630 res[count] = str.substring(lastI, i);
631 count++;
632 i++;
633 lastI = i;
634 }
635 res[count] = str.substring(lastI, str.length());
636 return res;
637 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800640 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800644 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 mContext = context;
648 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700649 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 mMetrics = new DisplayMetrics();
651 mSettings = new Settings();
652 mSettings.addSharedUserLP("android.uid.system",
653 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
654 mSettings.addSharedUserLP("android.uid.phone",
655 MULTIPLE_APPLICATION_UIDS
656 ? RADIO_UID : FIRST_APPLICATION_UID,
657 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400658 mSettings.addSharedUserLP("android.uid.log",
659 MULTIPLE_APPLICATION_UIDS
660 ? LOG_UID : FIRST_APPLICATION_UID,
661 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662
663 String separateProcesses = SystemProperties.get("debug.separate_processes");
664 if (separateProcesses != null && separateProcesses.length() > 0) {
665 if ("*".equals(separateProcesses)) {
666 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
667 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800668 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 } else {
670 mDefParseFlags = 0;
671 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800672 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 + separateProcesses);
674 }
675 } else {
676 mDefParseFlags = 0;
677 mSeparateProcesses = null;
678 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 Installer installer = new Installer();
681 // Little hacky thing to check if installd is here, to determine
682 // whether we are running on the simulator and thus need to take
683 // care of building the /data file structure ourself.
684 // (apparently the sim now has a working installer)
685 if (installer.ping() && Process.supportsProcesses()) {
686 mInstaller = installer;
687 } else {
688 mInstaller = null;
689 }
690
691 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
692 Display d = wm.getDefaultDisplay();
693 d.getMetrics(mMetrics);
694
695 synchronized (mInstallLock) {
696 synchronized (mPackages) {
697 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700698 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 File dataDir = Environment.getDataDirectory();
701 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800702 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
704
705 if (mInstaller == null) {
706 // Make sure these dirs exist, when we are running in
707 // the simulator.
708 // Make a wide-open directory for random misc stuff.
709 File miscDir = new File(dataDir, "misc");
710 miscDir.mkdirs();
711 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800712 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 mDrmAppPrivateInstallDir.mkdirs();
714 }
715
716 readPermissions();
717
718 mRestoredSettings = mSettings.readLP();
719 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800720
721 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800723
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800724 // Set flag to monitor and not change apk file paths when
725 // scanning install directories.
726 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700727 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800728 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800729 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700730 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700735 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700738 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 /**
741 * Out of paranoia, ensure that everything in the boot class
742 * path has been dexed.
743 */
744 String bootClassPath = System.getProperty("java.boot.class.path");
745 if (bootClassPath != null) {
746 String[] paths = splitString(bootClassPath, ':');
747 for (int i=0; i<paths.length; i++) {
748 try {
749 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
750 libFiles.add(paths[i]);
751 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700752 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 }
754 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800755 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800757 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 }
759 }
760 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800761 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 /**
765 * Also ensure all external libraries have had dexopt run on them.
766 */
767 if (mSharedLibraries.size() > 0) {
768 Iterator<String> libs = mSharedLibraries.values().iterator();
769 while (libs.hasNext()) {
770 String lib = libs.next();
771 try {
772 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
773 libFiles.add(lib);
774 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700775 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 }
777 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800778 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800780 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 }
782 }
783 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 // Gross hack for now: we know this file doesn't contain any
786 // code, so don't dexopt it to avoid the resulting log spew.
787 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 /**
790 * And there are a number of commands implemented in Java, which
791 * we currently need to do the dexopt on so that they can be
792 * run from a non-root shell.
793 */
794 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700795 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 for (int i=0; i<frameworkFiles.length; i++) {
797 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
798 String path = libPath.getPath();
799 // Skip the file if we alrady did it.
800 if (libFiles.contains(path)) {
801 continue;
802 }
803 // Skip the file if it is not a type we want to dexopt.
804 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
805 continue;
806 }
807 try {
808 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
809 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700810 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 }
812 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800813 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800815 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 }
817 }
818 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800819
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700820 if (didDexOpt) {
821 // If we had to do a dexopt of one of the previous
822 // things, then something on the system has changed.
823 // Consider this significant, and wipe away all other
824 // existing dexopt files to ensure we don't leave any
825 // dangling around.
826 String[] files = mDalvikCacheDir.list();
827 if (files != null) {
828 for (int i=0; i<files.length; i++) {
829 String fn = files[i];
830 if (fn.startsWith("data@app@")
831 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800832 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700833 (new File(mDalvikCacheDir, fn)).delete();
834 }
835 }
836 }
837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800839
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800840 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 mFrameworkInstallObserver = new AppDirObserver(
842 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
843 mFrameworkInstallObserver.startWatching();
844 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800845 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800846
847 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
849 mSystemInstallObserver = new AppDirObserver(
850 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
851 mSystemInstallObserver.startWatching();
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800852 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800853
854 if (mInstaller != null) {
855 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
856 mInstaller.moveFiles();
857 }
858
859 // Prune any system packages that no longer exist.
860 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
861 while (psit.hasNext()) {
862 PackageSetting ps = psit.next();
863 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800864 && !mPackages.containsKey(ps.name)
865 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800866 psit.remove();
867 String msg = "System package " + ps.name
868 + " no longer exists; wiping its data";
869 reportSettingsProblem(Log.WARN, msg);
870 if (mInstaller != null) {
871 // XXX how to set useEncryptedFSDir for packages that
872 // are not encrypted?
873 mInstaller.remove(ps.name, true);
874 }
875 }
876 }
877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 mAppInstallDir = new File(dataDir, "app");
879 if (mInstaller == null) {
880 // Make sure these dirs exist, when we are running in
881 // the simulator.
882 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
883 }
884 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800885 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 //clean up list
887 for(int i = 0; i < deletePkgsList.size(); i++) {
888 //clean up here
889 cleanupInstallFailedPackage(deletePkgsList.get(i));
890 }
891 //delete tmp files
892 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800893
894 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 SystemClock.uptimeMillis());
896 mAppInstallObserver = new AppDirObserver(
897 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
898 mAppInstallObserver.startWatching();
899 scanDirLI(mAppInstallDir, 0, scanMode);
900
901 mDrmAppInstallObserver = new AppDirObserver(
902 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
903 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800904 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800906 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800908 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 + ((SystemClock.uptimeMillis()-startTime)/1000f)
910 + " seconds");
911
912 updatePermissionsLP();
913
914 mSettings.writeLP();
915
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800916 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 // Now after opening every single application zip, make sure they
920 // are all flushed. Not really needed, but keeps things nice and
921 // tidy.
922 Runtime.getRuntime().gc();
923 } // synchronized (mPackages)
924 } // synchronized (mInstallLock)
925 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 @Override
928 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
929 throws RemoteException {
930 try {
931 return super.onTransact(code, data, reply, flags);
932 } catch (RuntimeException e) {
933 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800934 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 }
936 throw e;
937 }
938 }
939
Dianne Hackborne6620b22010-01-22 14:46:21 -0800940 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800941 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800943 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
944 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800946 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800947 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 }
949 } else {
950 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800951 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 File dataDir = new File(pkg.applicationInfo.dataDir);
953 dataDir.delete();
954 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800955 if (ps.codePath != null) {
956 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800957 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -0800958 }
959 }
960 if (ps.resourcePath != null) {
961 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800962 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -0800963 }
964 }
965 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 }
967
968 void readPermissions() {
969 // Read permissions from .../etc/permission directory.
970 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
971 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800972 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 return;
974 }
975 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800976 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 return;
978 }
979
980 // Iterate over the files in the directory and scan .xml files
981 for (File f : libraryDir.listFiles()) {
982 // We'll read platform.xml last
983 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
984 continue;
985 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800988 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 continue;
990 }
991 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800992 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 continue;
994 }
995
996 readPermissionsFromXml(f);
997 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1000 final File permFile = new File(Environment.getRootDirectory(),
1001 "etc/permissions/platform.xml");
1002 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001003
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001004 StringBuilder sb = new StringBuilder(128);
1005 sb.append("Libs:");
1006 Iterator<String> it = mSharedLibraries.keySet().iterator();
1007 while (it.hasNext()) {
1008 sb.append(' ');
1009 String name = it.next();
1010 sb.append(name);
1011 sb.append(':');
1012 sb.append(mSharedLibraries.get(name));
1013 }
1014 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001015
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001016 sb.setLength(0);
1017 sb.append("Features:");
1018 it = mAvailableFeatures.keySet().iterator();
1019 while (it.hasNext()) {
1020 sb.append(' ');
1021 sb.append(it.next());
1022 }
1023 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001025
1026 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 FileReader permReader = null;
1028 try {
1029 permReader = new FileReader(permFile);
1030 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001031 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 return;
1033 }
1034
1035 try {
1036 XmlPullParser parser = Xml.newPullParser();
1037 parser.setInput(permReader);
1038
1039 XmlUtils.beginDocument(parser, "permissions");
1040
1041 while (true) {
1042 XmlUtils.nextElement(parser);
1043 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1044 break;
1045 }
1046
1047 String name = parser.getName();
1048 if ("group".equals(name)) {
1049 String gidStr = parser.getAttributeValue(null, "gid");
1050 if (gidStr != null) {
1051 int gid = Integer.parseInt(gidStr);
1052 mGlobalGids = appendInt(mGlobalGids, gid);
1053 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001054 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 + parser.getPositionDescription());
1056 }
1057
1058 XmlUtils.skipCurrentTag(parser);
1059 continue;
1060 } else if ("permission".equals(name)) {
1061 String perm = parser.getAttributeValue(null, "name");
1062 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001063 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 + parser.getPositionDescription());
1065 XmlUtils.skipCurrentTag(parser);
1066 continue;
1067 }
1068 perm = perm.intern();
1069 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 } else if ("assign-permission".equals(name)) {
1072 String perm = parser.getAttributeValue(null, "name");
1073 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001074 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 + parser.getPositionDescription());
1076 XmlUtils.skipCurrentTag(parser);
1077 continue;
1078 }
1079 String uidStr = parser.getAttributeValue(null, "uid");
1080 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001081 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 + parser.getPositionDescription());
1083 XmlUtils.skipCurrentTag(parser);
1084 continue;
1085 }
1086 int uid = Process.getUidForName(uidStr);
1087 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001088 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 + uidStr + "\" at "
1090 + parser.getPositionDescription());
1091 XmlUtils.skipCurrentTag(parser);
1092 continue;
1093 }
1094 perm = perm.intern();
1095 HashSet<String> perms = mSystemPermissions.get(uid);
1096 if (perms == null) {
1097 perms = new HashSet<String>();
1098 mSystemPermissions.put(uid, perms);
1099 }
1100 perms.add(perm);
1101 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 } else if ("library".equals(name)) {
1104 String lname = parser.getAttributeValue(null, "name");
1105 String lfile = parser.getAttributeValue(null, "file");
1106 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001107 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 + parser.getPositionDescription());
1109 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001110 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 + parser.getPositionDescription());
1112 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001113 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001114 mSharedLibraries.put(lname, lfile);
1115 }
1116 XmlUtils.skipCurrentTag(parser);
1117 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001118
Dianne Hackborn49237342009-08-27 20:08:01 -07001119 } else if ("feature".equals(name)) {
1120 String fname = parser.getAttributeValue(null, "name");
1121 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001122 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001123 + parser.getPositionDescription());
1124 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001125 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001126 FeatureInfo fi = new FeatureInfo();
1127 fi.name = fname;
1128 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 }
1130 XmlUtils.skipCurrentTag(parser);
1131 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 } else {
1134 XmlUtils.skipCurrentTag(parser);
1135 continue;
1136 }
1137
1138 }
1139 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001140 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001142 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 }
1144 }
1145
1146 void readPermission(XmlPullParser parser, String name)
1147 throws IOException, XmlPullParserException {
1148
1149 name = name.intern();
1150
1151 BasePermission bp = mSettings.mPermissions.get(name);
1152 if (bp == null) {
1153 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1154 mSettings.mPermissions.put(name, bp);
1155 }
1156 int outerDepth = parser.getDepth();
1157 int type;
1158 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1159 && (type != XmlPullParser.END_TAG
1160 || parser.getDepth() > outerDepth)) {
1161 if (type == XmlPullParser.END_TAG
1162 || type == XmlPullParser.TEXT) {
1163 continue;
1164 }
1165
1166 String tagName = parser.getName();
1167 if ("group".equals(tagName)) {
1168 String gidStr = parser.getAttributeValue(null, "gid");
1169 if (gidStr != null) {
1170 int gid = Process.getGidForName(gidStr);
1171 bp.gids = appendInt(bp.gids, gid);
1172 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001173 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 + parser.getPositionDescription());
1175 }
1176 }
1177 XmlUtils.skipCurrentTag(parser);
1178 }
1179 }
1180
1181 static int[] appendInt(int[] cur, int val) {
1182 if (cur == null) {
1183 return new int[] { val };
1184 }
1185 final int N = cur.length;
1186 for (int i=0; i<N; i++) {
1187 if (cur[i] == val) {
1188 return cur;
1189 }
1190 }
1191 int[] ret = new int[N+1];
1192 System.arraycopy(cur, 0, ret, 0, N);
1193 ret[N] = val;
1194 return ret;
1195 }
1196
1197 static int[] appendInts(int[] cur, int[] add) {
1198 if (add == null) return cur;
1199 if (cur == null) return add;
1200 final int N = add.length;
1201 for (int i=0; i<N; i++) {
1202 cur = appendInt(cur, add[i]);
1203 }
1204 return cur;
1205 }
1206
1207 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001208 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1209 // The package has been uninstalled but has retained data and resources.
1210 return PackageParser.generatePackageInfo(p, null, flags);
1211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 final PackageSetting ps = (PackageSetting)p.mExtras;
1213 if (ps == null) {
1214 return null;
1215 }
1216 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1217 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1218 }
1219
1220 public PackageInfo getPackageInfo(String packageName, int flags) {
1221 synchronized (mPackages) {
1222 PackageParser.Package p = mPackages.get(packageName);
1223 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001224 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 + ": " + p);
1226 if (p != null) {
1227 return generatePackageInfo(p, flags);
1228 }
1229 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1230 return generatePackageInfoFromSettingsLP(packageName, flags);
1231 }
1232 }
1233 return null;
1234 }
1235
Dianne Hackborn47096932010-02-11 15:57:09 -08001236 public String[] currentToCanonicalPackageNames(String[] names) {
1237 String[] out = new String[names.length];
1238 synchronized (mPackages) {
1239 for (int i=names.length-1; i>=0; i--) {
1240 PackageSetting ps = mSettings.mPackages.get(names[i]);
1241 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1242 }
1243 }
1244 return out;
1245 }
1246
1247 public String[] canonicalToCurrentPackageNames(String[] names) {
1248 String[] out = new String[names.length];
1249 synchronized (mPackages) {
1250 for (int i=names.length-1; i>=0; i--) {
1251 String cur = mSettings.mRenamedPackages.get(names[i]);
1252 out[i] = cur != null ? cur : names[i];
1253 }
1254 }
1255 return out;
1256 }
1257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 public int getPackageUid(String packageName) {
1259 synchronized (mPackages) {
1260 PackageParser.Package p = mPackages.get(packageName);
1261 if(p != null) {
1262 return p.applicationInfo.uid;
1263 }
1264 PackageSetting ps = mSettings.mPackages.get(packageName);
1265 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1266 return -1;
1267 }
1268 p = ps.pkg;
1269 return p != null ? p.applicationInfo.uid : -1;
1270 }
1271 }
1272
1273 public int[] getPackageGids(String packageName) {
1274 synchronized (mPackages) {
1275 PackageParser.Package p = mPackages.get(packageName);
1276 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001277 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 + ": " + p);
1279 if (p != null) {
1280 final PackageSetting ps = (PackageSetting)p.mExtras;
1281 final SharedUserSetting suid = ps.sharedUser;
1282 return suid != null ? suid.gids : ps.gids;
1283 }
1284 }
1285 // stupid thing to indicate an error.
1286 return new int[0];
1287 }
1288
1289 public PermissionInfo getPermissionInfo(String name, int flags) {
1290 synchronized (mPackages) {
1291 final BasePermission p = mSettings.mPermissions.get(name);
1292 if (p != null && p.perm != null) {
1293 return PackageParser.generatePermissionInfo(p.perm, flags);
1294 }
1295 return null;
1296 }
1297 }
1298
1299 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1300 synchronized (mPackages) {
1301 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1302 for (BasePermission p : mSettings.mPermissions.values()) {
1303 if (group == null) {
1304 if (p.perm.info.group == null) {
1305 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1306 }
1307 } else {
1308 if (group.equals(p.perm.info.group)) {
1309 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1310 }
1311 }
1312 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 if (out.size() > 0) {
1315 return out;
1316 }
1317 return mPermissionGroups.containsKey(group) ? out : null;
1318 }
1319 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1322 synchronized (mPackages) {
1323 return PackageParser.generatePermissionGroupInfo(
1324 mPermissionGroups.get(name), flags);
1325 }
1326 }
1327
1328 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1329 synchronized (mPackages) {
1330 final int N = mPermissionGroups.size();
1331 ArrayList<PermissionGroupInfo> out
1332 = new ArrayList<PermissionGroupInfo>(N);
1333 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1334 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1335 }
1336 return out;
1337 }
1338 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1341 PackageSetting ps = mSettings.mPackages.get(packageName);
1342 if(ps != null) {
1343 if(ps.pkg == null) {
1344 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1345 if(pInfo != null) {
1346 return pInfo.applicationInfo;
1347 }
1348 return null;
1349 }
1350 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1351 }
1352 return null;
1353 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1356 PackageSetting ps = mSettings.mPackages.get(packageName);
1357 if(ps != null) {
1358 if(ps.pkg == null) {
1359 ps.pkg = new PackageParser.Package(packageName);
1360 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001361 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1362 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1363 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1364 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 }
1366 return generatePackageInfo(ps.pkg, flags);
1367 }
1368 return null;
1369 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1372 synchronized (mPackages) {
1373 PackageParser.Package p = mPackages.get(packageName);
1374 if (Config.LOGV) Log.v(
1375 TAG, "getApplicationInfo " + packageName
1376 + ": " + p);
1377 if (p != null) {
1378 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001379 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 }
1381 if ("android".equals(packageName)||"system".equals(packageName)) {
1382 return mAndroidApplication;
1383 }
1384 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1385 return generateApplicationInfoFromSettingsLP(packageName, flags);
1386 }
1387 }
1388 return null;
1389 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001390
1391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1393 mContext.enforceCallingOrSelfPermission(
1394 android.Manifest.permission.CLEAR_APP_CACHE, null);
1395 // Queue up an async operation since clearing cache may take a little while.
1396 mHandler.post(new Runnable() {
1397 public void run() {
1398 mHandler.removeCallbacks(this);
1399 int retCode = -1;
1400 if (mInstaller != null) {
1401 retCode = mInstaller.freeCache(freeStorageSize);
1402 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001403 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 }
1405 } //end if mInstaller
1406 if (observer != null) {
1407 try {
1408 observer.onRemoveCompleted(null, (retCode >= 0));
1409 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001410 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 }
1412 }
1413 }
1414 });
1415 }
1416
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001417 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001418 mContext.enforceCallingOrSelfPermission(
1419 android.Manifest.permission.CLEAR_APP_CACHE, null);
1420 // Queue up an async operation since clearing cache may take a little while.
1421 mHandler.post(new Runnable() {
1422 public void run() {
1423 mHandler.removeCallbacks(this);
1424 int retCode = -1;
1425 if (mInstaller != null) {
1426 retCode = mInstaller.freeCache(freeStorageSize);
1427 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001428 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001429 }
1430 }
1431 if(pi != null) {
1432 try {
1433 // Callback via pending intent
1434 int code = (retCode >= 0) ? 1 : 0;
1435 pi.sendIntent(null, code, null,
1436 null, null);
1437 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001438 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001439 }
1440 }
1441 }
1442 });
1443 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1446 synchronized (mPackages) {
1447 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001448
1449 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001451 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 }
1453 if (mResolveComponentName.equals(component)) {
1454 return mResolveActivity;
1455 }
1456 }
1457 return null;
1458 }
1459
1460 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1461 synchronized (mPackages) {
1462 PackageParser.Activity a = mReceivers.mActivities.get(component);
1463 if (Config.LOGV) Log.v(
1464 TAG, "getReceiverInfo " + component + ": " + a);
1465 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1466 return PackageParser.generateActivityInfo(a, flags);
1467 }
1468 }
1469 return null;
1470 }
1471
1472 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1473 synchronized (mPackages) {
1474 PackageParser.Service s = mServices.mServices.get(component);
1475 if (Config.LOGV) Log.v(
1476 TAG, "getServiceInfo " + component + ": " + s);
1477 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1478 return PackageParser.generateServiceInfo(s, flags);
1479 }
1480 }
1481 return null;
1482 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 public String[] getSystemSharedLibraryNames() {
1485 Set<String> libSet;
1486 synchronized (mPackages) {
1487 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001488 int size = libSet.size();
1489 if (size > 0) {
1490 String[] libs = new String[size];
1491 libSet.toArray(libs);
1492 return libs;
1493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001495 return null;
1496 }
1497
1498 public FeatureInfo[] getSystemAvailableFeatures() {
1499 Collection<FeatureInfo> featSet;
1500 synchronized (mPackages) {
1501 featSet = mAvailableFeatures.values();
1502 int size = featSet.size();
1503 if (size > 0) {
1504 FeatureInfo[] features = new FeatureInfo[size+1];
1505 featSet.toArray(features);
1506 FeatureInfo fi = new FeatureInfo();
1507 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1508 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1509 features[size] = fi;
1510 return features;
1511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 }
1513 return null;
1514 }
1515
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001516 public boolean hasSystemFeature(String name) {
1517 synchronized (mPackages) {
1518 return mAvailableFeatures.containsKey(name);
1519 }
1520 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 public int checkPermission(String permName, String pkgName) {
1523 synchronized (mPackages) {
1524 PackageParser.Package p = mPackages.get(pkgName);
1525 if (p != null && p.mExtras != null) {
1526 PackageSetting ps = (PackageSetting)p.mExtras;
1527 if (ps.sharedUser != null) {
1528 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1529 return PackageManager.PERMISSION_GRANTED;
1530 }
1531 } else if (ps.grantedPermissions.contains(permName)) {
1532 return PackageManager.PERMISSION_GRANTED;
1533 }
1534 }
1535 }
1536 return PackageManager.PERMISSION_DENIED;
1537 }
1538
1539 public int checkUidPermission(String permName, int uid) {
1540 synchronized (mPackages) {
1541 Object obj = mSettings.getUserIdLP(uid);
1542 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001543 GrantedPermissions gp = (GrantedPermissions)obj;
1544 if (gp.grantedPermissions.contains(permName)) {
1545 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 }
1547 } else {
1548 HashSet<String> perms = mSystemPermissions.get(uid);
1549 if (perms != null && perms.contains(permName)) {
1550 return PackageManager.PERMISSION_GRANTED;
1551 }
1552 }
1553 }
1554 return PackageManager.PERMISSION_DENIED;
1555 }
1556
1557 private BasePermission findPermissionTreeLP(String permName) {
1558 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1559 if (permName.startsWith(bp.name) &&
1560 permName.length() > bp.name.length() &&
1561 permName.charAt(bp.name.length()) == '.') {
1562 return bp;
1563 }
1564 }
1565 return null;
1566 }
1567
1568 private BasePermission checkPermissionTreeLP(String permName) {
1569 if (permName != null) {
1570 BasePermission bp = findPermissionTreeLP(permName);
1571 if (bp != null) {
1572 if (bp.uid == Binder.getCallingUid()) {
1573 return bp;
1574 }
1575 throw new SecurityException("Calling uid "
1576 + Binder.getCallingUid()
1577 + " is not allowed to add to permission tree "
1578 + bp.name + " owned by uid " + bp.uid);
1579 }
1580 }
1581 throw new SecurityException("No permission tree found for " + permName);
1582 }
1583
1584 public boolean addPermission(PermissionInfo info) {
1585 synchronized (mPackages) {
1586 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1587 throw new SecurityException("Label must be specified in permission");
1588 }
1589 BasePermission tree = checkPermissionTreeLP(info.name);
1590 BasePermission bp = mSettings.mPermissions.get(info.name);
1591 boolean added = bp == null;
1592 if (added) {
1593 bp = new BasePermission(info.name, tree.sourcePackage,
1594 BasePermission.TYPE_DYNAMIC);
1595 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1596 throw new SecurityException(
1597 "Not allowed to modify non-dynamic permission "
1598 + info.name);
1599 }
1600 bp.perm = new PackageParser.Permission(tree.perm.owner,
1601 new PermissionInfo(info));
1602 bp.perm.info.packageName = tree.perm.info.packageName;
1603 bp.uid = tree.uid;
1604 if (added) {
1605 mSettings.mPermissions.put(info.name, bp);
1606 }
1607 mSettings.writeLP();
1608 return added;
1609 }
1610 }
1611
1612 public void removePermission(String name) {
1613 synchronized (mPackages) {
1614 checkPermissionTreeLP(name);
1615 BasePermission bp = mSettings.mPermissions.get(name);
1616 if (bp != null) {
1617 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1618 throw new SecurityException(
1619 "Not allowed to modify non-dynamic permission "
1620 + name);
1621 }
1622 mSettings.mPermissions.remove(name);
1623 mSettings.writeLP();
1624 }
1625 }
1626 }
1627
Dianne Hackborn854060af2009-07-09 18:14:31 -07001628 public boolean isProtectedBroadcast(String actionName) {
1629 synchronized (mPackages) {
1630 return mProtectedBroadcasts.contains(actionName);
1631 }
1632 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 public int checkSignatures(String pkg1, String pkg2) {
1635 synchronized (mPackages) {
1636 PackageParser.Package p1 = mPackages.get(pkg1);
1637 PackageParser.Package p2 = mPackages.get(pkg2);
1638 if (p1 == null || p1.mExtras == null
1639 || p2 == null || p2.mExtras == null) {
1640 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1641 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001642 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 }
1644 }
1645
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001646 public int checkUidSignatures(int uid1, int uid2) {
1647 synchronized (mPackages) {
1648 Signature[] s1;
1649 Signature[] s2;
1650 Object obj = mSettings.getUserIdLP(uid1);
1651 if (obj != null) {
1652 if (obj instanceof SharedUserSetting) {
1653 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1654 } else if (obj instanceof PackageSetting) {
1655 s1 = ((PackageSetting)obj).signatures.mSignatures;
1656 } else {
1657 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1658 }
1659 } else {
1660 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1661 }
1662 obj = mSettings.getUserIdLP(uid2);
1663 if (obj != null) {
1664 if (obj instanceof SharedUserSetting) {
1665 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1666 } else if (obj instanceof PackageSetting) {
1667 s2 = ((PackageSetting)obj).signatures.mSignatures;
1668 } else {
1669 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1670 }
1671 } else {
1672 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1673 }
1674 return checkSignaturesLP(s1, s2);
1675 }
1676 }
1677
1678 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1679 if (s1 == null) {
1680 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1682 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1683 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001684 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1686 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001687 final int N1 = s1.length;
1688 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 for (int i=0; i<N1; i++) {
1690 boolean match = false;
1691 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001692 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 match = true;
1694 break;
1695 }
1696 }
1697 if (!match) {
1698 return PackageManager.SIGNATURE_NO_MATCH;
1699 }
1700 }
1701 return PackageManager.SIGNATURE_MATCH;
1702 }
1703
1704 public String[] getPackagesForUid(int uid) {
1705 synchronized (mPackages) {
1706 Object obj = mSettings.getUserIdLP(uid);
1707 if (obj instanceof SharedUserSetting) {
1708 SharedUserSetting sus = (SharedUserSetting)obj;
1709 final int N = sus.packages.size();
1710 String[] res = new String[N];
1711 Iterator<PackageSetting> it = sus.packages.iterator();
1712 int i=0;
1713 while (it.hasNext()) {
1714 res[i++] = it.next().name;
1715 }
1716 return res;
1717 } else if (obj instanceof PackageSetting) {
1718 PackageSetting ps = (PackageSetting)obj;
1719 return new String[] { ps.name };
1720 }
1721 }
1722 return null;
1723 }
1724
1725 public String getNameForUid(int uid) {
1726 synchronized (mPackages) {
1727 Object obj = mSettings.getUserIdLP(uid);
1728 if (obj instanceof SharedUserSetting) {
1729 SharedUserSetting sus = (SharedUserSetting)obj;
1730 return sus.name + ":" + sus.userId;
1731 } else if (obj instanceof PackageSetting) {
1732 PackageSetting ps = (PackageSetting)obj;
1733 return ps.name;
1734 }
1735 }
1736 return null;
1737 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 public int getUidForSharedUser(String sharedUserName) {
1740 if(sharedUserName == null) {
1741 return -1;
1742 }
1743 synchronized (mPackages) {
1744 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1745 if(suid == null) {
1746 return -1;
1747 }
1748 return suid.userId;
1749 }
1750 }
1751
1752 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1753 int flags) {
1754 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001755 return chooseBestActivity(intent, resolvedType, flags, query);
1756 }
1757
Mihai Predaeae850c2009-05-13 10:13:48 +02001758 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1759 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 if (query != null) {
1761 final int N = query.size();
1762 if (N == 1) {
1763 return query.get(0);
1764 } else if (N > 1) {
1765 // If there is more than one activity with the same priority,
1766 // then let the user decide between them.
1767 ResolveInfo r0 = query.get(0);
1768 ResolveInfo r1 = query.get(1);
1769 if (false) {
1770 System.out.println(r0.activityInfo.name +
1771 "=" + r0.priority + " vs " +
1772 r1.activityInfo.name +
1773 "=" + r1.priority);
1774 }
1775 // If the first activity has a higher priority, or a different
1776 // default, then it is always desireable to pick it.
1777 if (r0.priority != r1.priority
1778 || r0.preferredOrder != r1.preferredOrder
1779 || r0.isDefault != r1.isDefault) {
1780 return query.get(0);
1781 }
1782 // If we have saved a preference for a preferred activity for
1783 // this Intent, use that.
1784 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1785 flags, query, r0.priority);
1786 if (ri != null) {
1787 return ri;
1788 }
1789 return mResolveInfo;
1790 }
1791 }
1792 return null;
1793 }
1794
1795 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1796 int flags, List<ResolveInfo> query, int priority) {
1797 synchronized (mPackages) {
1798 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1799 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001800 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1802 if (prefs != null && prefs.size() > 0) {
1803 // First figure out how good the original match set is.
1804 // We will only allow preferred activities that came
1805 // from the same match quality.
1806 int match = 0;
1807 final int N = query.size();
1808 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1809 for (int j=0; j<N; j++) {
1810 ResolveInfo ri = query.get(j);
1811 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1812 + ": 0x" + Integer.toHexString(match));
1813 if (ri.match > match) match = ri.match;
1814 }
1815 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1816 + Integer.toHexString(match));
1817 match &= IntentFilter.MATCH_CATEGORY_MASK;
1818 final int M = prefs.size();
1819 for (int i=0; i<M; i++) {
1820 PreferredActivity pa = prefs.get(i);
1821 if (pa.mMatch != match) {
1822 continue;
1823 }
1824 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1825 if (DEBUG_PREFERRED) {
1826 Log.v(TAG, "Got preferred activity:");
1827 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1828 }
1829 if (ai != null) {
1830 for (int j=0; j<N; j++) {
1831 ResolveInfo ri = query.get(j);
1832 if (!ri.activityInfo.applicationInfo.packageName
1833 .equals(ai.applicationInfo.packageName)) {
1834 continue;
1835 }
1836 if (!ri.activityInfo.name.equals(ai.name)) {
1837 continue;
1838 }
1839
1840 // Okay we found a previously set preferred app.
1841 // If the result set is different from when this
1842 // was created, we need to clear it and re-ask the
1843 // user their preference.
1844 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001845 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 + intent + " type " + resolvedType);
1847 mSettings.mPreferredActivities.removeFilter(pa);
1848 return null;
1849 }
1850
1851 // Yay!
1852 return ri;
1853 }
1854 }
1855 }
1856 }
1857 }
1858 return null;
1859 }
1860
1861 public List<ResolveInfo> queryIntentActivities(Intent intent,
1862 String resolvedType, int flags) {
1863 ComponentName comp = intent.getComponent();
1864 if (comp != null) {
1865 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1866 ActivityInfo ai = getActivityInfo(comp, flags);
1867 if (ai != null) {
1868 ResolveInfo ri = new ResolveInfo();
1869 ri.activityInfo = ai;
1870 list.add(ri);
1871 }
1872 return list;
1873 }
1874
1875 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001876 String pkgName = intent.getPackage();
1877 if (pkgName == null) {
1878 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1879 resolvedType, flags);
1880 }
1881 PackageParser.Package pkg = mPackages.get(pkgName);
1882 if (pkg != null) {
1883 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1884 resolvedType, flags, pkg.activities);
1885 }
1886 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 }
1888 }
1889
1890 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1891 Intent[] specifics, String[] specificTypes, Intent intent,
1892 String resolvedType, int flags) {
1893 final String resultsAction = intent.getAction();
1894
1895 List<ResolveInfo> results = queryIntentActivities(
1896 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1897 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1898
1899 int specificsPos = 0;
1900 int N;
1901
1902 // todo: note that the algorithm used here is O(N^2). This
1903 // isn't a problem in our current environment, but if we start running
1904 // into situations where we have more than 5 or 10 matches then this
1905 // should probably be changed to something smarter...
1906
1907 // First we go through and resolve each of the specific items
1908 // that were supplied, taking care of removing any corresponding
1909 // duplicate items in the generic resolve list.
1910 if (specifics != null) {
1911 for (int i=0; i<specifics.length; i++) {
1912 final Intent sintent = specifics[i];
1913 if (sintent == null) {
1914 continue;
1915 }
1916
1917 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1918 String action = sintent.getAction();
1919 if (resultsAction != null && resultsAction.equals(action)) {
1920 // If this action was explicitly requested, then don't
1921 // remove things that have it.
1922 action = null;
1923 }
1924 ComponentName comp = sintent.getComponent();
1925 ResolveInfo ri = null;
1926 ActivityInfo ai = null;
1927 if (comp == null) {
1928 ri = resolveIntent(
1929 sintent,
1930 specificTypes != null ? specificTypes[i] : null,
1931 flags);
1932 if (ri == null) {
1933 continue;
1934 }
1935 if (ri == mResolveInfo) {
1936 // ACK! Must do something better with this.
1937 }
1938 ai = ri.activityInfo;
1939 comp = new ComponentName(ai.applicationInfo.packageName,
1940 ai.name);
1941 } else {
1942 ai = getActivityInfo(comp, flags);
1943 if (ai == null) {
1944 continue;
1945 }
1946 }
1947
1948 // Look for any generic query activities that are duplicates
1949 // of this specific one, and remove them from the results.
1950 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1951 N = results.size();
1952 int j;
1953 for (j=specificsPos; j<N; j++) {
1954 ResolveInfo sri = results.get(j);
1955 if ((sri.activityInfo.name.equals(comp.getClassName())
1956 && sri.activityInfo.applicationInfo.packageName.equals(
1957 comp.getPackageName()))
1958 || (action != null && sri.filter.matchAction(action))) {
1959 results.remove(j);
1960 if (Config.LOGV) Log.v(
1961 TAG, "Removing duplicate item from " + j
1962 + " due to specific " + specificsPos);
1963 if (ri == null) {
1964 ri = sri;
1965 }
1966 j--;
1967 N--;
1968 }
1969 }
1970
1971 // Add this specific item to its proper place.
1972 if (ri == null) {
1973 ri = new ResolveInfo();
1974 ri.activityInfo = ai;
1975 }
1976 results.add(specificsPos, ri);
1977 ri.specificIndex = i;
1978 specificsPos++;
1979 }
1980 }
1981
1982 // Now we go through the remaining generic results and remove any
1983 // duplicate actions that are found here.
1984 N = results.size();
1985 for (int i=specificsPos; i<N-1; i++) {
1986 final ResolveInfo rii = results.get(i);
1987 if (rii.filter == null) {
1988 continue;
1989 }
1990
1991 // Iterate over all of the actions of this result's intent
1992 // filter... typically this should be just one.
1993 final Iterator<String> it = rii.filter.actionsIterator();
1994 if (it == null) {
1995 continue;
1996 }
1997 while (it.hasNext()) {
1998 final String action = it.next();
1999 if (resultsAction != null && resultsAction.equals(action)) {
2000 // If this action was explicitly requested, then don't
2001 // remove things that have it.
2002 continue;
2003 }
2004 for (int j=i+1; j<N; j++) {
2005 final ResolveInfo rij = results.get(j);
2006 if (rij.filter != null && rij.filter.hasAction(action)) {
2007 results.remove(j);
2008 if (Config.LOGV) Log.v(
2009 TAG, "Removing duplicate item from " + j
2010 + " due to action " + action + " at " + i);
2011 j--;
2012 N--;
2013 }
2014 }
2015 }
2016
2017 // If the caller didn't request filter information, drop it now
2018 // so we don't have to marshall/unmarshall it.
2019 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2020 rii.filter = null;
2021 }
2022 }
2023
2024 // Filter out the caller activity if so requested.
2025 if (caller != null) {
2026 N = results.size();
2027 for (int i=0; i<N; i++) {
2028 ActivityInfo ainfo = results.get(i).activityInfo;
2029 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2030 && caller.getClassName().equals(ainfo.name)) {
2031 results.remove(i);
2032 break;
2033 }
2034 }
2035 }
2036
2037 // If the caller didn't request filter information,
2038 // drop them now so we don't have to
2039 // marshall/unmarshall it.
2040 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2041 N = results.size();
2042 for (int i=0; i<N; i++) {
2043 results.get(i).filter = null;
2044 }
2045 }
2046
2047 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2048 return results;
2049 }
2050
2051 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2052 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002053 ComponentName comp = intent.getComponent();
2054 if (comp != null) {
2055 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2056 ActivityInfo ai = getReceiverInfo(comp, flags);
2057 if (ai != null) {
2058 ResolveInfo ri = new ResolveInfo();
2059 ri.activityInfo = ai;
2060 list.add(ri);
2061 }
2062 return list;
2063 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002066 String pkgName = intent.getPackage();
2067 if (pkgName == null) {
2068 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2069 resolvedType, flags);
2070 }
2071 PackageParser.Package pkg = mPackages.get(pkgName);
2072 if (pkg != null) {
2073 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2074 resolvedType, flags, pkg.receivers);
2075 }
2076 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 }
2078 }
2079
2080 public ResolveInfo resolveService(Intent intent, String resolvedType,
2081 int flags) {
2082 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2083 flags);
2084 if (query != null) {
2085 if (query.size() >= 1) {
2086 // If there is more than one service with the same priority,
2087 // just arbitrarily pick the first one.
2088 return query.get(0);
2089 }
2090 }
2091 return null;
2092 }
2093
2094 public List<ResolveInfo> queryIntentServices(Intent intent,
2095 String resolvedType, int flags) {
2096 ComponentName comp = intent.getComponent();
2097 if (comp != null) {
2098 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2099 ServiceInfo si = getServiceInfo(comp, flags);
2100 if (si != null) {
2101 ResolveInfo ri = new ResolveInfo();
2102 ri.serviceInfo = si;
2103 list.add(ri);
2104 }
2105 return list;
2106 }
2107
2108 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002109 String pkgName = intent.getPackage();
2110 if (pkgName == null) {
2111 return (List<ResolveInfo>)mServices.queryIntent(intent,
2112 resolvedType, flags);
2113 }
2114 PackageParser.Package pkg = mPackages.get(pkgName);
2115 if (pkg != null) {
2116 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2117 resolvedType, flags, pkg.services);
2118 }
2119 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 }
2121 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 public List<PackageInfo> getInstalledPackages(int flags) {
2124 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2125
2126 synchronized (mPackages) {
2127 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2128 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2129 while (i.hasNext()) {
2130 final PackageSetting ps = i.next();
2131 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2132 if(psPkg != null) {
2133 finalList.add(psPkg);
2134 }
2135 }
2136 }
2137 else {
2138 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2139 while (i.hasNext()) {
2140 final PackageParser.Package p = i.next();
2141 if (p.applicationInfo != null) {
2142 PackageInfo pi = generatePackageInfo(p, flags);
2143 if(pi != null) {
2144 finalList.add(pi);
2145 }
2146 }
2147 }
2148 }
2149 }
2150 return finalList;
2151 }
2152
2153 public List<ApplicationInfo> getInstalledApplications(int flags) {
2154 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2155 synchronized(mPackages) {
2156 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2157 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2158 while (i.hasNext()) {
2159 final PackageSetting ps = i.next();
2160 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2161 if(ai != null) {
2162 finalList.add(ai);
2163 }
2164 }
2165 }
2166 else {
2167 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2168 while (i.hasNext()) {
2169 final PackageParser.Package p = i.next();
2170 if (p.applicationInfo != null) {
2171 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2172 if(ai != null) {
2173 finalList.add(ai);
2174 }
2175 }
2176 }
2177 }
2178 }
2179 return finalList;
2180 }
2181
2182 public List<ApplicationInfo> getPersistentApplications(int flags) {
2183 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2184
2185 synchronized (mPackages) {
2186 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2187 while (i.hasNext()) {
2188 PackageParser.Package p = i.next();
2189 if (p.applicationInfo != null
2190 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2191 && (!mSafeMode || (p.applicationInfo.flags
2192 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2193 finalList.add(p.applicationInfo);
2194 }
2195 }
2196 }
2197
2198 return finalList;
2199 }
2200
2201 public ProviderInfo resolveContentProvider(String name, int flags) {
2202 synchronized (mPackages) {
2203 final PackageParser.Provider provider = mProviders.get(name);
2204 return provider != null
2205 && mSettings.isEnabledLP(provider.info, flags)
2206 && (!mSafeMode || (provider.info.applicationInfo.flags
2207 &ApplicationInfo.FLAG_SYSTEM) != 0)
2208 ? PackageParser.generateProviderInfo(provider, flags)
2209 : null;
2210 }
2211 }
2212
Fred Quintana718d8a22009-04-29 17:53:20 -07002213 /**
2214 * @deprecated
2215 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 public void querySyncProviders(List outNames, List outInfo) {
2217 synchronized (mPackages) {
2218 Iterator<Map.Entry<String, PackageParser.Provider>> i
2219 = mProviders.entrySet().iterator();
2220
2221 while (i.hasNext()) {
2222 Map.Entry<String, PackageParser.Provider> entry = i.next();
2223 PackageParser.Provider p = entry.getValue();
2224
2225 if (p.syncable
2226 && (!mSafeMode || (p.info.applicationInfo.flags
2227 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2228 outNames.add(entry.getKey());
2229 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2230 }
2231 }
2232 }
2233 }
2234
2235 public List<ProviderInfo> queryContentProviders(String processName,
2236 int uid, int flags) {
2237 ArrayList<ProviderInfo> finalList = null;
2238
2239 synchronized (mPackages) {
2240 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2241 while (i.hasNext()) {
2242 PackageParser.Provider p = i.next();
2243 if (p.info.authority != null
2244 && (processName == null ||
2245 (p.info.processName.equals(processName)
2246 && p.info.applicationInfo.uid == uid))
2247 && mSettings.isEnabledLP(p.info, flags)
2248 && (!mSafeMode || (p.info.applicationInfo.flags
2249 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2250 if (finalList == null) {
2251 finalList = new ArrayList<ProviderInfo>(3);
2252 }
2253 finalList.add(PackageParser.generateProviderInfo(p,
2254 flags));
2255 }
2256 }
2257 }
2258
2259 if (finalList != null) {
2260 Collections.sort(finalList, mProviderInitOrderSorter);
2261 }
2262
2263 return finalList;
2264 }
2265
2266 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2267 int flags) {
2268 synchronized (mPackages) {
2269 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2270 return PackageParser.generateInstrumentationInfo(i, flags);
2271 }
2272 }
2273
2274 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2275 int flags) {
2276 ArrayList<InstrumentationInfo> finalList =
2277 new ArrayList<InstrumentationInfo>();
2278
2279 synchronized (mPackages) {
2280 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2281 while (i.hasNext()) {
2282 PackageParser.Instrumentation p = i.next();
2283 if (targetPackage == null
2284 || targetPackage.equals(p.info.targetPackage)) {
2285 finalList.add(PackageParser.generateInstrumentationInfo(p,
2286 flags));
2287 }
2288 }
2289 }
2290
2291 return finalList;
2292 }
2293
2294 private void scanDirLI(File dir, int flags, int scanMode) {
2295 Log.d(TAG, "Scanning app dir " + dir);
2296
2297 String[] files = dir.list();
2298
2299 int i;
2300 for (i=0; i<files.length; i++) {
2301 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002302 if (!isPackageFilename(files[i])) {
2303 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002304 continue;
2305 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002306 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002307 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002308 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002309 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2310 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002311 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002312 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002313 file.delete();
2314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 }
2316 }
2317
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002318 private static File getSettingsProblemFile() {
2319 File dataDir = Environment.getDataDirectory();
2320 File systemDir = new File(dataDir, "system");
2321 File fname = new File(systemDir, "uiderrors.txt");
2322 return fname;
2323 }
2324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 private static void reportSettingsProblem(int priority, String msg) {
2326 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002327 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328 FileOutputStream out = new FileOutputStream(fname, true);
2329 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002330 SimpleDateFormat formatter = new SimpleDateFormat();
2331 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2332 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333 pw.close();
2334 FileUtils.setPermissions(
2335 fname.toString(),
2336 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2337 -1, -1);
2338 } catch (java.io.IOException e) {
2339 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002340 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002341 }
2342
2343 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2344 PackageParser.Package pkg, File srcFile, int parseFlags) {
2345 if (GET_CERTIFICATES) {
2346 if (ps == null || !ps.codePath.equals(srcFile)
2347 || ps.getTimeStamp() != srcFile.lastModified()) {
2348 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2349 if (!pp.collectCertificates(pkg, parseFlags)) {
2350 mLastScanError = pp.getParseError();
2351 return false;
2352 }
2353 }
2354 }
2355 return true;
2356 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002358 /*
2359 * Scan a package and return the newly parsed package.
2360 * Returns null in case of errors and the error code is stored in mLastScanError
2361 */
2362 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002363 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002365 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002367 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002370 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 if (pkg == null) {
2372 mLastScanError = pp.getParseError();
2373 return null;
2374 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002375 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 PackageSetting updatedPkg;
2377 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002378 // Look to see if we already know about this package.
2379 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002380 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002381 // This package has been renamed to its original name. Let's
2382 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002383 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002384 }
2385 // If there was no original package, see one for the real package name.
2386 if (ps == null) {
2387 ps = mSettings.peekPackageLP(pkg.packageName);
2388 }
2389 // Check to see if this package could be hiding/updating a system
2390 // package. Must look for it either under the original or real
2391 // package name depending on our state.
2392 updatedPkg = mSettings.mDisabledSysPackages.get(
2393 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002395 // First check if this is a system package that may involve an update
2396 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2397 if (!ps.codePath.equals(scanFile)) {
2398 // The path has changed from what was last scanned... check the
2399 // version of the new path against what we have stored to determine
2400 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002401 if (pkg.mVersionCode < ps.versionCode) {
2402 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002403 // Ignore entry. Skip it.
2404 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2405 + "ignored: updated version " + ps.versionCode
2406 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002407 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2408 return null;
2409 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002410 // The current app on the system partion is better than
2411 // what we have updated to on the data partition; switch
2412 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002413 // At this point, its safely assumed that package installation for
2414 // apps in system partition will go through. If not there won't be a working
2415 // version of the app
2416 synchronized (mPackages) {
2417 // Just remove the loaded entries from package lists.
2418 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002419 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002420 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002421 + "reverting from " + ps.codePathString
2422 + ": new version " + pkg.mVersionCode
2423 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002424 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2425 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002426 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 }
2429 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002430 if (updatedPkg != null) {
2431 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2432 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2433 }
2434 // Verify certificates against what was last scanned
2435 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002436 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002437 return null;
2438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 // The apk is forward locked (not public) if its code and resources
2440 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002441 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002443 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002444 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002445
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002446 String codePath = null;
2447 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002448 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2449 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002450 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002451 } else {
2452 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002453 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002454 }
2455 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002456 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002457 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002458 codePath = pkg.mScanPath;
2459 // Set application objects path explicitly.
2460 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002462 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002463 }
2464
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002465 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2466 String destCodePath, String destResPath) {
2467 pkg.mPath = pkg.mScanPath = destCodePath;
2468 pkg.applicationInfo.sourceDir = destCodePath;
2469 pkg.applicationInfo.publicSourceDir = destResPath;
2470 }
2471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472 private static String fixProcessName(String defProcessName,
2473 String processName, int uid) {
2474 if (processName == null) {
2475 return defProcessName;
2476 }
2477 return processName;
2478 }
2479
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002480 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2482 if (pkg.mSignatures != null) {
2483 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2484 updateSignature)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002485 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 + " signatures do not match the previously installed version; ignoring!");
2487 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2488 return false;
2489 }
2490
2491 if (pkgSetting.sharedUser != null) {
2492 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2493 pkg.mSignatures, updateSignature)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002494 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 + " has no signatures that match those in shared user "
2496 + pkgSetting.sharedUser.name + "; ignoring!");
2497 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2498 return false;
2499 }
2500 }
2501 } else {
2502 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2503 }
2504 return true;
2505 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002506
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002507 public boolean performDexOpt(String packageName) {
2508 if (!mNoDexOpt) {
2509 return false;
2510 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002511
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002512 PackageParser.Package p;
2513 synchronized (mPackages) {
2514 p = mPackages.get(packageName);
2515 if (p == null || p.mDidDexOpt) {
2516 return false;
2517 }
2518 }
2519 synchronized (mInstallLock) {
2520 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2521 }
2522 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002523
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002524 static final int DEX_OPT_SKIPPED = 0;
2525 static final int DEX_OPT_PERFORMED = 1;
2526 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002527
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002528 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2529 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002530 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002531 String path = pkg.mScanPath;
2532 int ret = 0;
2533 try {
2534 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002535 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002536 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002537 pkg.mDidDexOpt = true;
2538 performed = true;
2539 }
2540 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002541 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002542 ret = -1;
2543 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002544 Slog.w(TAG, "Exception reading apk: " + path, e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002545 ret = -1;
2546 }
2547 if (ret < 0) {
2548 //error from installer
2549 return DEX_OPT_FAILED;
2550 }
2551 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002552
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002553 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2554 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002555
2556 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2557 return Environment.isEncryptedFilesystemEnabled() &&
2558 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2559 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002560
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002561 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2562 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002563 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002564 + " to " + newPkg.packageName
2565 + ": old package not in system partition");
2566 return false;
2567 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002568 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002569 + " to " + newPkg.packageName
2570 + ": old package still exists");
2571 return false;
2572 }
2573 return true;
2574 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002575
2576 private File getDataPathForPackage(PackageParser.Package pkg) {
2577 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2578 File dataPath;
2579 if (useEncryptedFSDir) {
2580 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2581 } else {
2582 dataPath = new File(mAppDataDir, pkg.packageName);
2583 }
2584 return dataPath;
2585 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002586
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002587 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2588 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002589 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002590 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2591 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002592 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002593 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002594 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2595 return null;
2596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597 mScanningPath = scanFile;
2598 if (pkg == null) {
2599 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2600 return null;
2601 }
2602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2604 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2605 }
2606
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002607 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 synchronized (mPackages) {
2609 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002610 Slog.w(TAG, "*************************************************");
2611 Slog.w(TAG, "Core android package being redefined. Skipping.");
2612 Slog.w(TAG, " file=" + mScanningPath);
2613 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2615 return null;
2616 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002618 // Set up information for our fall-back user intent resolution
2619 // activity.
2620 mPlatformPackage = pkg;
2621 pkg.mVersionCode = mSdkVersion;
2622 mAndroidApplication = pkg.applicationInfo;
2623 mResolveActivity.applicationInfo = mAndroidApplication;
2624 mResolveActivity.name = ResolverActivity.class.getName();
2625 mResolveActivity.packageName = mAndroidApplication.packageName;
2626 mResolveActivity.processName = mAndroidApplication.processName;
2627 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2628 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2629 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2630 mResolveActivity.exported = true;
2631 mResolveActivity.enabled = true;
2632 mResolveInfo.activityInfo = mResolveActivity;
2633 mResolveInfo.priority = 0;
2634 mResolveInfo.preferredOrder = 0;
2635 mResolveInfo.match = 0;
2636 mResolveComponentName = new ComponentName(
2637 mAndroidApplication.packageName, mResolveActivity.name);
2638 }
2639 }
2640
2641 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002642 TAG, "Scanning package " + pkg.packageName);
2643 if (mPackages.containsKey(pkg.packageName)
2644 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002645 Slog.w(TAG, "*************************************************");
2646 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002648 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2650 return null;
2651 }
2652
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002653 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002654 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2655 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002657 SharedUserSetting suid = null;
2658 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002661
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002662 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2663 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002664 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002665 pkg.mRealPackage = null;
2666 pkg.mAdoptPermissions = null;
2667 }
2668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 synchronized (mPackages) {
2670 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002671 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2672 if (mTmpSharedLibraries == null ||
2673 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2674 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2675 }
2676 int num = 0;
2677 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2678 for (int i=0; i<N; i++) {
2679 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002681 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002683 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2685 return null;
2686 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002687 mTmpSharedLibraries[num] = file;
2688 num++;
2689 }
2690 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2691 for (int i=0; i<N; i++) {
2692 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2693 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002694 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002695 + " desires unavailable shared library "
2696 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2697 } else {
2698 mTmpSharedLibraries[num] = file;
2699 num++;
2700 }
2701 }
2702 if (num > 0) {
2703 pkg.usesLibraryFiles = new String[num];
2704 System.arraycopy(mTmpSharedLibraries, 0,
2705 pkg.usesLibraryFiles, 0, num);
2706 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002707
Dianne Hackborn49237342009-08-27 20:08:01 -07002708 if (pkg.reqFeatures != null) {
2709 N = pkg.reqFeatures.size();
2710 for (int i=0; i<N; i++) {
2711 FeatureInfo fi = pkg.reqFeatures.get(i);
2712 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2713 // Don't care.
2714 continue;
2715 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002716
Dianne Hackborn49237342009-08-27 20:08:01 -07002717 if (fi.name != null) {
2718 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002719 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002720 + " requires unavailable feature "
2721 + fi.name + "; failing!");
2722 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2723 return null;
2724 }
2725 }
2726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002727 }
2728 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730 if (pkg.mSharedUserId != null) {
2731 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2732 pkg.applicationInfo.flags, true);
2733 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002734 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 + " for shared user failed");
2736 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2737 return null;
2738 }
2739 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2740 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2741 + suid.userId + "): packages=" + suid.packages);
2742 }
2743 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002744
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002745 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002746 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002747 Log.w(TAG, "WAITING FOR DEBUGGER");
2748 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002749 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2750 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002751 }
2752 }
2753
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002754 // Check if we are renaming from an original package name.
2755 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002756 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002757 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002758 // This package may need to be renamed to a previously
2759 // installed name. Let's check on that...
2760 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002761 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002762 // This package had originally been installed as the
2763 // original name, and we have already taken care of
2764 // transitioning to the new one. Just update the new
2765 // one to continue using the old name.
2766 realName = pkg.mRealPackage;
2767 if (!pkg.packageName.equals(renamed)) {
2768 // Callers into this function may have already taken
2769 // care of renaming the package; only do it here if
2770 // it is not already done.
2771 pkg.setPackageName(renamed);
2772 }
2773
Dianne Hackbornc1552392010-03-03 16:19:01 -08002774 } else {
2775 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2776 if ((origPackage=mSettings.peekPackageLP(
2777 pkg.mOriginalPackages.get(i))) != null) {
2778 // We do have the package already installed under its
2779 // original name... should we use it?
2780 if (!verifyPackageUpdate(origPackage, pkg)) {
2781 // New package is not compatible with original.
2782 origPackage = null;
2783 continue;
2784 } else if (origPackage.sharedUser != null) {
2785 // Make sure uid is compatible between packages.
2786 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002787 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002788 + " to " + pkg.packageName + ": old uid "
2789 + origPackage.sharedUser.name
2790 + " differs from " + pkg.mSharedUserId);
2791 origPackage = null;
2792 continue;
2793 }
2794 } else {
2795 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2796 + pkg.packageName + " to old name " + origPackage.name);
2797 }
2798 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002799 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002800 }
2801 }
2802 }
2803
2804 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002805 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002806 + " was transferred to another, but its .apk remains");
2807 }
2808
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002809 // Just create the setting, don't add it yet. For already existing packages
2810 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002811 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 destResourceFile, pkg.applicationInfo.flags, true, false);
2813 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002814 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2816 return null;
2817 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002818
2819 if (pkgSetting.origPackage != null) {
2820 // If we are first transitioning from an original package,
2821 // fix up the new package's name now. We need to do this after
2822 // looking up the package under its new name, so getPackageLP
2823 // can take care of fiddling things correctly.
2824 pkg.setPackageName(origPackage.name);
2825
2826 // File a report about this.
2827 String msg = "New package " + pkgSetting.realName
2828 + " renamed to replace old package " + pkgSetting.name;
2829 reportSettingsProblem(Log.WARN, msg);
2830
2831 // Make a note of it.
2832 mTransferedPackages.add(origPackage.name);
2833
2834 // No longer need to retain this.
2835 pkgSetting.origPackage = null;
2836 }
2837
2838 if (realName != null) {
2839 // Make a note of it.
2840 mTransferedPackages.add(pkg.packageName);
2841 }
2842
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002843 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2845 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002847 pkg.applicationInfo.uid = pkgSetting.userId;
2848 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002849
2850 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2852 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2853 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2854 return null;
2855 }
2856 // The signature has changed, but this package is in the system
2857 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002858 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 // However... if this package is part of a shared user, but it
2860 // doesn't match the signature of the shared user, let's fail.
2861 // What this means is that you can't change the signatures
2862 // associated with an overall shared user, which doesn't seem all
2863 // that unreasonable.
2864 if (pkgSetting.sharedUser != null) {
2865 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2866 pkg.mSignatures, false)) {
2867 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2868 return null;
2869 }
2870 }
2871 removeExisting = true;
2872 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002873
The Android Open Source Project10592532009-03-18 17:39:46 -07002874 // Verify that this new package doesn't have any content providers
2875 // that conflict with existing packages. Only do this if the
2876 // package isn't already installed, since we don't want to break
2877 // things that are installed.
2878 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2879 int N = pkg.providers.size();
2880 int i;
2881 for (i=0; i<N; i++) {
2882 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08002883 if (p.info.authority != null) {
2884 String names[] = p.info.authority.split(";");
2885 for (int j = 0; j < names.length; j++) {
2886 if (mProviders.containsKey(names[j])) {
2887 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002888 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08002889 " (in package " + pkg.applicationInfo.packageName +
2890 ") is already used by "
2891 + ((other != null && other.getComponentName() != null)
2892 ? other.getComponentName().getPackageName() : "?"));
2893 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2894 return null;
2895 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002896 }
2897 }
2898 }
2899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 }
2901
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002902 final String pkgName = pkg.packageName;
2903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002905 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002907 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908 if (ret != 0) {
2909 String msg = "System package " + pkg.packageName
2910 + " could not have data directory erased after signature change.";
2911 reportSettingsProblem(Log.WARN, msg);
2912 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2913 return null;
2914 }
2915 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002916 Slog.w(TAG, "System package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 + " signature changed: existing data removed.");
2918 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2919 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002920
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002921 if (pkg.mAdoptPermissions != null) {
2922 // This package wants to adopt ownership of permissions from
2923 // another package.
2924 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2925 String origName = pkg.mAdoptPermissions.get(i);
2926 PackageSetting orig = mSettings.peekPackageLP(origName);
2927 if (orig != null) {
2928 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002929 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002930 + origName + " to " + pkg.packageName);
2931 mSettings.transferPermissions(origName, pkg.packageName);
2932 }
2933 }
2934 }
2935 }
2936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 long scanFileTime = scanFile.lastModified();
2938 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2939 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2940 pkg.applicationInfo.processName = fixProcessName(
2941 pkg.applicationInfo.packageName,
2942 pkg.applicationInfo.processName,
2943 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944
2945 File dataPath;
2946 if (mPlatformPackage == pkg) {
2947 // The system package is special.
2948 dataPath = new File (Environment.getDataDirectory(), "system");
2949 pkg.applicationInfo.dataDir = dataPath.getPath();
2950 } else {
2951 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002952 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002953 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002954
2955 boolean uidError = false;
2956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 if (dataPath.exists()) {
2958 mOutPermissions[1] = 0;
2959 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2960 if (mOutPermissions[1] == pkg.applicationInfo.uid
2961 || !Process.supportsProcesses()) {
2962 pkg.applicationInfo.dataDir = dataPath.getPath();
2963 } else {
2964 boolean recovered = false;
2965 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2966 // If this is a system app, we can at least delete its
2967 // current data so the application will still work.
2968 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002969 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002970 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 // Old data gone!
2972 String msg = "System package " + pkg.packageName
2973 + " has changed from uid: "
2974 + mOutPermissions[1] + " to "
2975 + pkg.applicationInfo.uid + "; old data erased";
2976 reportSettingsProblem(Log.WARN, msg);
2977 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002980 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002981 pkg.applicationInfo.uid);
2982 if (ret == -1) {
2983 // Ack should not happen!
2984 msg = "System package " + pkg.packageName
2985 + " could not have data directory re-created after delete.";
2986 reportSettingsProblem(Log.WARN, msg);
2987 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2988 return null;
2989 }
2990 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 if (!recovered) {
2993 mHasSystemUidErrors = true;
2994 }
2995 }
2996 if (!recovered) {
2997 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2998 + pkg.applicationInfo.uid + "/fs_"
2999 + mOutPermissions[1];
3000 String msg = "Package " + pkg.packageName
3001 + " has mismatched uid: "
3002 + mOutPermissions[1] + " on disk, "
3003 + pkg.applicationInfo.uid + " in settings";
3004 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003005 mSettings.mReadMessages.append(msg);
3006 mSettings.mReadMessages.append('\n');
3007 uidError = true;
3008 if (!pkgSetting.uidError) {
3009 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003011 }
3012 }
3013 }
3014 pkg.applicationInfo.dataDir = dataPath.getPath();
3015 } else {
3016 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3017 Log.v(TAG, "Want this data dir: " + dataPath);
3018 //invoke installer to do the actual installation
3019 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003020 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 pkg.applicationInfo.uid);
3022 if(ret < 0) {
3023 // Error from installer
3024 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3025 return null;
3026 }
3027 } else {
3028 dataPath.mkdirs();
3029 if (dataPath.exists()) {
3030 FileUtils.setPermissions(
3031 dataPath.toString(),
3032 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3033 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3034 }
3035 }
3036 if (dataPath.exists()) {
3037 pkg.applicationInfo.dataDir = dataPath.getPath();
3038 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003039 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 pkg.applicationInfo.dataDir = null;
3041 }
3042 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003043
3044 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003045 }
3046
3047 // Perform shared library installation and dex validation and
3048 // optimization, if this is not a system app.
3049 if (mInstaller != null) {
3050 String path = scanFile.getPath();
3051 if (scanFileNewer) {
3052 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003053 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3054 if (err != PackageManager.INSTALL_SUCCEEDED) {
3055 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056 return null;
3057 }
3058 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003059 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003060
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003061 if ((scanMode&SCAN_NO_DEX) == 0) {
3062 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003063 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3064 return null;
3065 }
3066 }
3067 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003069 if (mFactoryTest && pkg.requestedPermissions.contains(
3070 android.Manifest.permission.FACTORY_TEST)) {
3071 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3072 }
3073
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003074 // Request the ActivityManager to kill the process(only for existing packages)
3075 // so that we do not end up in a confused state while the user is still using the older
3076 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003077 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003078 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003079 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003080 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003082 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003083 // We don't expect installation to fail beyond this point,
3084 if ((scanMode&SCAN_MONITOR) != 0) {
3085 mAppDirs.put(pkg.mPath, pkg);
3086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003088 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003089 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003090 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003091 // Make sure we don't accidentally delete its data.
3092 mSettings.mPackagesToBeCleaned.remove(pkgName);
3093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003094 int N = pkg.providers.size();
3095 StringBuilder r = null;
3096 int i;
3097 for (i=0; i<N; i++) {
3098 PackageParser.Provider p = pkg.providers.get(i);
3099 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3100 p.info.processName, pkg.applicationInfo.uid);
3101 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3102 p.info.name), p);
3103 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003104 if (p.info.authority != null) {
3105 String names[] = p.info.authority.split(";");
3106 p.info.authority = null;
3107 for (int j = 0; j < names.length; j++) {
3108 if (j == 1 && p.syncable) {
3109 // We only want the first authority for a provider to possibly be
3110 // syncable, so if we already added this provider using a different
3111 // authority clear the syncable flag. We copy the provider before
3112 // changing it because the mProviders object contains a reference
3113 // to a provider that we don't want to change.
3114 // Only do this for the second authority since the resulting provider
3115 // object can be the same for all future authorities for this provider.
3116 p = new PackageParser.Provider(p);
3117 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003118 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003119 if (!mProviders.containsKey(names[j])) {
3120 mProviders.put(names[j], p);
3121 if (p.info.authority == null) {
3122 p.info.authority = names[j];
3123 } else {
3124 p.info.authority = p.info.authority + ";" + names[j];
3125 }
3126 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3127 Log.d(TAG, "Registered content provider: " + names[j] +
3128 ", className = " + p.info.name +
3129 ", isSyncable = " + p.info.isSyncable);
3130 } else {
3131 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003132 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003133 " (in package " + pkg.applicationInfo.packageName +
3134 "): name already used by "
3135 + ((other != null && other.getComponentName() != null)
3136 ? other.getComponentName().getPackageName() : "?"));
3137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003138 }
3139 }
3140 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3141 if (r == null) {
3142 r = new StringBuilder(256);
3143 } else {
3144 r.append(' ');
3145 }
3146 r.append(p.info.name);
3147 }
3148 }
3149 if (r != null) {
3150 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3151 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003153 N = pkg.services.size();
3154 r = null;
3155 for (i=0; i<N; i++) {
3156 PackageParser.Service s = pkg.services.get(i);
3157 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3158 s.info.processName, pkg.applicationInfo.uid);
3159 mServices.addService(s);
3160 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3161 if (r == null) {
3162 r = new StringBuilder(256);
3163 } else {
3164 r.append(' ');
3165 }
3166 r.append(s.info.name);
3167 }
3168 }
3169 if (r != null) {
3170 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3171 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003173 N = pkg.receivers.size();
3174 r = null;
3175 for (i=0; i<N; i++) {
3176 PackageParser.Activity a = pkg.receivers.get(i);
3177 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3178 a.info.processName, pkg.applicationInfo.uid);
3179 mReceivers.addActivity(a, "receiver");
3180 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3181 if (r == null) {
3182 r = new StringBuilder(256);
3183 } else {
3184 r.append(' ');
3185 }
3186 r.append(a.info.name);
3187 }
3188 }
3189 if (r != null) {
3190 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3191 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193 N = pkg.activities.size();
3194 r = null;
3195 for (i=0; i<N; i++) {
3196 PackageParser.Activity a = pkg.activities.get(i);
3197 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3198 a.info.processName, pkg.applicationInfo.uid);
3199 mActivities.addActivity(a, "activity");
3200 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3201 if (r == null) {
3202 r = new StringBuilder(256);
3203 } else {
3204 r.append(' ');
3205 }
3206 r.append(a.info.name);
3207 }
3208 }
3209 if (r != null) {
3210 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3211 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213 N = pkg.permissionGroups.size();
3214 r = null;
3215 for (i=0; i<N; i++) {
3216 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3217 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3218 if (cur == null) {
3219 mPermissionGroups.put(pg.info.name, pg);
3220 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3221 if (r == null) {
3222 r = new StringBuilder(256);
3223 } else {
3224 r.append(' ');
3225 }
3226 r.append(pg.info.name);
3227 }
3228 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003229 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 + pg.info.packageName + " ignored: original from "
3231 + cur.info.packageName);
3232 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3233 if (r == null) {
3234 r = new StringBuilder(256);
3235 } else {
3236 r.append(' ');
3237 }
3238 r.append("DUP:");
3239 r.append(pg.info.name);
3240 }
3241 }
3242 }
3243 if (r != null) {
3244 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3245 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247 N = pkg.permissions.size();
3248 r = null;
3249 for (i=0; i<N; i++) {
3250 PackageParser.Permission p = pkg.permissions.get(i);
3251 HashMap<String, BasePermission> permissionMap =
3252 p.tree ? mSettings.mPermissionTrees
3253 : mSettings.mPermissions;
3254 p.group = mPermissionGroups.get(p.info.group);
3255 if (p.info.group == null || p.group != null) {
3256 BasePermission bp = permissionMap.get(p.info.name);
3257 if (bp == null) {
3258 bp = new BasePermission(p.info.name, p.info.packageName,
3259 BasePermission.TYPE_NORMAL);
3260 permissionMap.put(p.info.name, bp);
3261 }
3262 if (bp.perm == null) {
3263 if (bp.sourcePackage == null
3264 || bp.sourcePackage.equals(p.info.packageName)) {
3265 BasePermission tree = findPermissionTreeLP(p.info.name);
3266 if (tree == null
3267 || tree.sourcePackage.equals(p.info.packageName)) {
3268 bp.perm = p;
3269 bp.uid = pkg.applicationInfo.uid;
3270 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3271 if (r == null) {
3272 r = new StringBuilder(256);
3273 } else {
3274 r.append(' ');
3275 }
3276 r.append(p.info.name);
3277 }
3278 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003279 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003280 + p.info.packageName + " ignored: base tree "
3281 + tree.name + " is from package "
3282 + tree.sourcePackage);
3283 }
3284 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003285 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003286 + p.info.packageName + " ignored: original from "
3287 + bp.sourcePackage);
3288 }
3289 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3290 if (r == null) {
3291 r = new StringBuilder(256);
3292 } else {
3293 r.append(' ');
3294 }
3295 r.append("DUP:");
3296 r.append(p.info.name);
3297 }
3298 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003299 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 + p.info.packageName + " ignored: no group "
3301 + p.group);
3302 }
3303 }
3304 if (r != null) {
3305 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3306 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 N = pkg.instrumentation.size();
3309 r = null;
3310 for (i=0; i<N; i++) {
3311 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3312 a.info.packageName = pkg.applicationInfo.packageName;
3313 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3314 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3315 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003316 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3318 if (r == null) {
3319 r = new StringBuilder(256);
3320 } else {
3321 r.append(' ');
3322 }
3323 r.append(a.info.name);
3324 }
3325 }
3326 if (r != null) {
3327 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3328 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003329
Dianne Hackborn854060af2009-07-09 18:14:31 -07003330 if (pkg.protectedBroadcasts != null) {
3331 N = pkg.protectedBroadcasts.size();
3332 for (i=0; i<N; i++) {
3333 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3334 }
3335 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337 pkgSetting.setTimeStamp(scanFileTime);
3338 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003340 return pkg;
3341 }
3342
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003343 private void killApplication(String pkgName, int uid) {
3344 // Request the ActivityManager to kill the process(only for existing packages)
3345 // so that we do not end up in a confused state while the user is still using the older
3346 // version of the application while the new one gets installed.
3347 IActivityManager am = ActivityManagerNative.getDefault();
3348 if (am != null) {
3349 try {
3350 am.killApplicationWithUid(pkgName, uid);
3351 } catch (RemoteException e) {
3352 }
3353 }
3354 }
3355
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003356 // The following constants are returned by cachePackageSharedLibsForAbiLI
3357 // to indicate if native shared libraries were found in the package.
3358 // Values are:
3359 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3360 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3361 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3362 // in package (and not installed)
3363 //
3364 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3365 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3366 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003367
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003368 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3369 // and automatically copy them to /data/data/<appname>/lib if present.
3370 //
3371 // NOTE: this method may throw an IOException if the library cannot
3372 // be copied to its final destination, e.g. if there isn't enough
3373 // room left on the data partition, or a ZipException if the package
3374 // file is malformed.
3375 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003376 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3377 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003378 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3379 final String apkLib = "lib/";
3380 final int apkLibLen = apkLib.length();
3381 final int cpuAbiLen = cpuAbi.length();
3382 final String libPrefix = "lib";
3383 final int libPrefixLen = libPrefix.length();
3384 final String libSuffix = ".so";
3385 final int libSuffixLen = libSuffix.length();
3386 boolean hasNativeLibraries = false;
3387 boolean installedNativeLibraries = false;
3388
3389 // the minimum length of a valid native shared library of the form
3390 // lib/<something>/lib<name>.so.
3391 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3392
3393 ZipFile zipFile = new ZipFile(scanFile);
3394 Enumeration<ZipEntry> entries =
3395 (Enumeration<ZipEntry>) zipFile.entries();
3396
3397 while (entries.hasMoreElements()) {
3398 ZipEntry entry = entries.nextElement();
3399 // skip directories
3400 if (entry.isDirectory()) {
3401 continue;
3402 }
3403 String entryName = entry.getName();
3404
3405 // check that the entry looks like lib/<something>/lib<name>.so
3406 // here, but don't check the ABI just yet.
3407 //
3408 // - must be sufficiently long
3409 // - must end with libSuffix, i.e. ".so"
3410 // - must start with apkLib, i.e. "lib/"
3411 if (entryName.length() < minEntryLen ||
3412 !entryName.endsWith(libSuffix) ||
3413 !entryName.startsWith(apkLib) ) {
3414 continue;
3415 }
3416
3417 // file name must start with libPrefix, i.e. "lib"
3418 int lastSlash = entryName.lastIndexOf('/');
3419
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003420 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003421 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3422 continue;
3423 }
3424
3425 hasNativeLibraries = true;
3426
3427 // check the cpuAbi now, between lib/ and /lib<name>.so
3428 //
3429 if (lastSlash != apkLibLen + cpuAbiLen ||
3430 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3431 continue;
3432
3433 // extract the library file name, ensure it doesn't contain
3434 // weird characters. we're guaranteed here that it doesn't contain
3435 // a directory separator though.
3436 String libFileName = entryName.substring(lastSlash+1);
3437 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3438 continue;
3439 }
3440
3441 installedNativeLibraries = true;
3442
3443 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3444 File.separator + libFileName;
3445 File sharedLibraryFile = new File(sharedLibraryFilePath);
3446 if (! sharedLibraryFile.exists() ||
3447 sharedLibraryFile.length() != entry.getSize() ||
3448 sharedLibraryFile.lastModified() != entry.getTime()) {
3449 if (Config.LOGD) {
3450 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003451 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003452 if (mInstaller == null) {
3453 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003454 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003455 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003456 sharedLibraryFile);
3457 }
3458 }
3459 if (!hasNativeLibraries)
3460 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3461
3462 if (!installedNativeLibraries)
3463 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3464
3465 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3466 }
3467
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003468 // Find the gdbserver executable program in a package at
3469 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3470 //
3471 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3472 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3473 //
3474 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3475 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3476 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3477 final String GDBSERVER = "gdbserver";
3478 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3479
3480 ZipFile zipFile = new ZipFile(scanFile);
3481 Enumeration<ZipEntry> entries =
3482 (Enumeration<ZipEntry>) zipFile.entries();
3483
3484 while (entries.hasMoreElements()) {
3485 ZipEntry entry = entries.nextElement();
3486 // skip directories
3487 if (entry.isDirectory()) {
3488 continue;
3489 }
3490 String entryName = entry.getName();
3491
3492 if (!entryName.equals(apkGdbServerPath)) {
3493 continue;
3494 }
3495
3496 String installGdbServerPath = installGdbServerDir.getPath() +
3497 "/" + GDBSERVER;
3498 File installGdbServerFile = new File(installGdbServerPath);
3499 if (! installGdbServerFile.exists() ||
3500 installGdbServerFile.length() != entry.getSize() ||
3501 installGdbServerFile.lastModified() != entry.getTime()) {
3502 if (Config.LOGD) {
3503 Log.d(TAG, "Caching gdbserver " + entry.getName());
3504 }
3505 if (mInstaller == null) {
3506 installGdbServerDir.mkdir();
3507 }
3508 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3509 installGdbServerFile);
3510 }
3511 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3512 }
3513 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3514 }
3515
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003516 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3517 // and copy them to /data/data/<appname>/lib.
3518 //
3519 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3520 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3521 // one if ro.product.cpu.abi2 is defined.
3522 //
3523 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3524 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003525 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003526 try {
3527 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3528
3529 // some architectures are capable of supporting several CPU ABIs
3530 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3531 // this is indicated by the definition of the ro.product.cpu.abi2
3532 // system property.
3533 //
3534 // only scan the package twice in case of ABI mismatch
3535 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003536 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003537 if (cpuAbi2 != null) {
3538 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003540
3541 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003542 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003543 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003544 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003545
3546 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3547 cpuAbi = cpuAbi2;
3548 }
3549 }
3550
3551 // for debuggable packages, also extract gdbserver from lib/<abi>
3552 // into /data/data/<appname>/lib too.
3553 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3554 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3555 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3556 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3557 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003559 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003560 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003561 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003562 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003564 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003565 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003567 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 }
3569
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003570 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003572 File binaryDir,
3573 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574 InputStream inputStream = zipFile.getInputStream(entry);
3575 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003576 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003578 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003579 // now need to be left as world readable and owned by the system.
3580 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3581 ! tempFile.setLastModified(entry.getTime()) ||
3582 FileUtils.setPermissions(tempFilePath,
3583 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003584 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003585 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003586 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003587 // Failed to properly write file.
3588 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003589 throw new IOException("Couldn't create cached binary "
3590 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003591 }
3592 } finally {
3593 inputStream.close();
3594 }
3595 }
3596
3597 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3598 if (chatty && Config.LOGD) Log.d(
3599 TAG, "Removing package " + pkg.applicationInfo.packageName );
3600
3601 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003604 mPackages.remove(pkg.applicationInfo.packageName);
3605 if (pkg.mPath != null) {
3606 mAppDirs.remove(pkg.mPath);
3607 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003609 PackageSetting ps = (PackageSetting)pkg.mExtras;
3610 if (ps != null && ps.sharedUser != null) {
3611 // XXX don't do this until the data is removed.
3612 if (false) {
3613 ps.sharedUser.packages.remove(ps);
3614 if (ps.sharedUser.packages.size() == 0) {
3615 // Remove.
3616 }
3617 }
3618 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 int N = pkg.providers.size();
3621 StringBuilder r = null;
3622 int i;
3623 for (i=0; i<N; i++) {
3624 PackageParser.Provider p = pkg.providers.get(i);
3625 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3626 p.info.name));
3627 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003629 /* The is another ContentProvider with this authority when
3630 * this app was installed so this authority is null,
3631 * Ignore it as we don't have to unregister the provider.
3632 */
3633 continue;
3634 }
3635 String names[] = p.info.authority.split(";");
3636 for (int j = 0; j < names.length; j++) {
3637 if (mProviders.get(names[j]) == p) {
3638 mProviders.remove(names[j]);
3639 if (chatty && Config.LOGD) Log.d(
3640 TAG, "Unregistered content provider: " + names[j] +
3641 ", className = " + p.info.name +
3642 ", isSyncable = " + p.info.isSyncable);
3643 }
3644 }
3645 if (chatty) {
3646 if (r == null) {
3647 r = new StringBuilder(256);
3648 } else {
3649 r.append(' ');
3650 }
3651 r.append(p.info.name);
3652 }
3653 }
3654 if (r != null) {
3655 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3656 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 N = pkg.services.size();
3659 r = null;
3660 for (i=0; i<N; i++) {
3661 PackageParser.Service s = pkg.services.get(i);
3662 mServices.removeService(s);
3663 if (chatty) {
3664 if (r == null) {
3665 r = new StringBuilder(256);
3666 } else {
3667 r.append(' ');
3668 }
3669 r.append(s.info.name);
3670 }
3671 }
3672 if (r != null) {
3673 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3674 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 N = pkg.receivers.size();
3677 r = null;
3678 for (i=0; i<N; i++) {
3679 PackageParser.Activity a = pkg.receivers.get(i);
3680 mReceivers.removeActivity(a, "receiver");
3681 if (chatty) {
3682 if (r == null) {
3683 r = new StringBuilder(256);
3684 } else {
3685 r.append(' ');
3686 }
3687 r.append(a.info.name);
3688 }
3689 }
3690 if (r != null) {
3691 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3692 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 N = pkg.activities.size();
3695 r = null;
3696 for (i=0; i<N; i++) {
3697 PackageParser.Activity a = pkg.activities.get(i);
3698 mActivities.removeActivity(a, "activity");
3699 if (chatty) {
3700 if (r == null) {
3701 r = new StringBuilder(256);
3702 } else {
3703 r.append(' ');
3704 }
3705 r.append(a.info.name);
3706 }
3707 }
3708 if (r != null) {
3709 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3710 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003712 N = pkg.permissions.size();
3713 r = null;
3714 for (i=0; i<N; i++) {
3715 PackageParser.Permission p = pkg.permissions.get(i);
3716 boolean tree = false;
3717 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3718 if (bp == null) {
3719 tree = true;
3720 bp = mSettings.mPermissionTrees.get(p.info.name);
3721 }
3722 if (bp != null && bp.perm == p) {
3723 if (bp.type != BasePermission.TYPE_BUILTIN) {
3724 if (tree) {
3725 mSettings.mPermissionTrees.remove(p.info.name);
3726 } else {
3727 mSettings.mPermissions.remove(p.info.name);
3728 }
3729 } else {
3730 bp.perm = null;
3731 }
3732 if (chatty) {
3733 if (r == null) {
3734 r = new StringBuilder(256);
3735 } else {
3736 r.append(' ');
3737 }
3738 r.append(p.info.name);
3739 }
3740 }
3741 }
3742 if (r != null) {
3743 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3744 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 N = pkg.instrumentation.size();
3747 r = null;
3748 for (i=0; i<N; i++) {
3749 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003750 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 if (chatty) {
3752 if (r == null) {
3753 r = new StringBuilder(256);
3754 } else {
3755 r.append(' ');
3756 }
3757 r.append(a.info.name);
3758 }
3759 }
3760 if (r != null) {
3761 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3762 }
3763 }
3764 }
3765
3766 private static final boolean isPackageFilename(String name) {
3767 return name != null && name.endsWith(".apk");
3768 }
3769
3770 private void updatePermissionsLP() {
3771 // Make sure there are no dangling permission trees.
3772 Iterator<BasePermission> it = mSettings.mPermissionTrees
3773 .values().iterator();
3774 while (it.hasNext()) {
3775 BasePermission bp = it.next();
3776 if (bp.perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003777 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 + " from package " + bp.sourcePackage);
3779 it.remove();
3780 }
3781 }
3782
3783 // Make sure all dynamic permissions have been assigned to a package,
3784 // and make sure there are no dangling permissions.
3785 it = mSettings.mPermissions.values().iterator();
3786 while (it.hasNext()) {
3787 BasePermission bp = it.next();
3788 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3789 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3790 + bp.name + " pkg=" + bp.sourcePackage
3791 + " info=" + bp.pendingInfo);
3792 if (bp.perm == null && bp.pendingInfo != null) {
3793 BasePermission tree = findPermissionTreeLP(bp.name);
3794 if (tree != null) {
3795 bp.perm = new PackageParser.Permission(tree.perm.owner,
3796 new PermissionInfo(bp.pendingInfo));
3797 bp.perm.info.packageName = tree.perm.info.packageName;
3798 bp.perm.info.name = bp.name;
3799 bp.uid = tree.uid;
3800 }
3801 }
3802 }
3803 if (bp.perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003804 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 + " from package " + bp.sourcePackage);
3806 it.remove();
3807 }
3808 }
3809
3810 // Now update the permissions for all packages, in particular
3811 // replace the granted permissions of the system packages.
3812 for (PackageParser.Package pkg : mPackages.values()) {
3813 grantPermissionsLP(pkg, false);
3814 }
3815 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003817 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3818 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3819 if (ps == null) {
3820 return;
3821 }
3822 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3823 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 if (replace) {
3826 ps.permissionsFixed = false;
3827 if (gp == ps) {
3828 gp.grantedPermissions.clear();
3829 gp.gids = mGlobalGids;
3830 }
3831 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833 if (gp.gids == null) {
3834 gp.gids = mGlobalGids;
3835 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 final int N = pkg.requestedPermissions.size();
3838 for (int i=0; i<N; i++) {
3839 String name = pkg.requestedPermissions.get(i);
3840 BasePermission bp = mSettings.mPermissions.get(name);
3841 PackageParser.Permission p = bp != null ? bp.perm : null;
3842 if (false) {
3843 if (gp != ps) {
3844 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3845 + ": " + p);
3846 }
3847 }
3848 if (p != null) {
3849 final String perm = p.info.name;
3850 boolean allowed;
3851 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3852 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3853 allowed = true;
3854 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3855 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003856 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003858 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 == PackageManager.SIGNATURE_MATCH);
3860 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3861 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3862 // For updated system applications, the signatureOrSystem permission
3863 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003864 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3866 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3867 if(sysPs.grantedPermissions.contains(perm)) {
3868 allowed = true;
3869 } else {
3870 allowed = false;
3871 }
3872 } else {
3873 allowed = true;
3874 }
3875 }
3876 }
3877 } else {
3878 allowed = false;
3879 }
3880 if (false) {
3881 if (gp != ps) {
3882 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3883 }
3884 }
3885 if (allowed) {
3886 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3887 && ps.permissionsFixed) {
3888 // If this is an existing, non-system package, then
3889 // we can't add any new permissions to it.
3890 if (!gp.loadedPermissions.contains(perm)) {
3891 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003892 // Except... if this is a permission that was added
3893 // to the platform (note: need to only do this when
3894 // updating the platform).
3895 final int NP = PackageParser.NEW_PERMISSIONS.length;
3896 for (int ip=0; ip<NP; ip++) {
3897 final PackageParser.NewPermissionInfo npi
3898 = PackageParser.NEW_PERMISSIONS[ip];
3899 if (npi.name.equals(perm)
3900 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3901 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003902 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003903 + pkg.packageName);
3904 break;
3905 }
3906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907 }
3908 }
3909 if (allowed) {
3910 if (!gp.grantedPermissions.contains(perm)) {
3911 addedPermission = true;
3912 gp.grantedPermissions.add(perm);
3913 gp.gids = appendInts(gp.gids, bp.gids);
3914 }
3915 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003916 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917 + " to package " + pkg.packageName
3918 + " because it was previously installed without");
3919 }
3920 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003921 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 + " to package " + pkg.packageName
3923 + " (protectionLevel=" + p.info.protectionLevel
3924 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3925 + ")");
3926 }
3927 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003928 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003929 + " in package " + pkg.packageName);
3930 }
3931 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003934 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3935 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 // This is the first that we have heard about this package, so the
3937 // permissions we have now selected are fixed until explicitly
3938 // changed.
3939 ps.permissionsFixed = true;
3940 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3941 }
3942 }
3943
3944 private final class ActivityIntentResolver
3945 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003946 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003947 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003948 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 }
3950
Mihai Preda074edef2009-05-18 17:13:31 +02003951 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003953 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3955 }
3956
Mihai Predaeae850c2009-05-13 10:13:48 +02003957 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3958 ArrayList<PackageParser.Activity> packageActivities) {
3959 if (packageActivities == null) {
3960 return null;
3961 }
3962 mFlags = flags;
3963 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3964 int N = packageActivities.size();
3965 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3966 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003967
3968 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003969 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003970 intentFilters = packageActivities.get(i).intents;
3971 if (intentFilters != null && intentFilters.size() > 0) {
3972 listCut.add(intentFilters);
3973 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003974 }
3975 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3976 }
3977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003979 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 if (SHOW_INFO || Config.LOGV) Log.v(
3981 TAG, " " + type + " " +
3982 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3983 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3984 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003985 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3987 if (SHOW_INFO || Config.LOGV) {
3988 Log.v(TAG, " IntentFilter:");
3989 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3990 }
3991 if (!intent.debugCheck()) {
3992 Log.w(TAG, "==> For Activity " + a.info.name);
3993 }
3994 addFilter(intent);
3995 }
3996 }
3997
3998 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003999 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 if (SHOW_INFO || Config.LOGV) Log.v(
4001 TAG, " " + type + " " +
4002 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4003 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4004 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004005 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4007 if (SHOW_INFO || Config.LOGV) {
4008 Log.v(TAG, " IntentFilter:");
4009 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4010 }
4011 removeFilter(intent);
4012 }
4013 }
4014
4015 @Override
4016 protected boolean allowFilterResult(
4017 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4018 ActivityInfo filterAi = filter.activity.info;
4019 for (int i=dest.size()-1; i>=0; i--) {
4020 ActivityInfo destAi = dest.get(i).activityInfo;
4021 if (destAi.name == filterAi.name
4022 && destAi.packageName == filterAi.packageName) {
4023 return false;
4024 }
4025 }
4026 return true;
4027 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 @Override
4030 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4031 int match) {
4032 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4033 return null;
4034 }
4035 final PackageParser.Activity activity = info.activity;
4036 if (mSafeMode && (activity.info.applicationInfo.flags
4037 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4038 return null;
4039 }
4040 final ResolveInfo res = new ResolveInfo();
4041 res.activityInfo = PackageParser.generateActivityInfo(activity,
4042 mFlags);
4043 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4044 res.filter = info;
4045 }
4046 res.priority = info.getPriority();
4047 res.preferredOrder = activity.owner.mPreferredOrder;
4048 //System.out.println("Result: " + res.activityInfo.className +
4049 // " = " + res.priority);
4050 res.match = match;
4051 res.isDefault = info.hasDefault;
4052 res.labelRes = info.labelRes;
4053 res.nonLocalizedLabel = info.nonLocalizedLabel;
4054 res.icon = info.icon;
4055 return res;
4056 }
4057
4058 @Override
4059 protected void sortResults(List<ResolveInfo> results) {
4060 Collections.sort(results, mResolvePrioritySorter);
4061 }
4062
4063 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004064 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004066 out.print(prefix); out.print(
4067 Integer.toHexString(System.identityHashCode(filter.activity)));
4068 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004069 out.println(filter.activity.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004070 }
4071
4072// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4073// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4074// final List<ResolveInfo> retList = Lists.newArrayList();
4075// while (i.hasNext()) {
4076// final ResolveInfo resolveInfo = i.next();
4077// if (isEnabledLP(resolveInfo.activityInfo)) {
4078// retList.add(resolveInfo);
4079// }
4080// }
4081// return retList;
4082// }
4083
4084 // Keys are String (activity class name), values are Activity.
4085 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4086 = new HashMap<ComponentName, PackageParser.Activity>();
4087 private int mFlags;
4088 }
4089
4090 private final class ServiceIntentResolver
4091 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004092 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004093 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004094 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 }
4096
Mihai Preda074edef2009-05-18 17:13:31 +02004097 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004099 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004100 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4101 }
4102
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004103 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4104 ArrayList<PackageParser.Service> packageServices) {
4105 if (packageServices == null) {
4106 return null;
4107 }
4108 mFlags = flags;
4109 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4110 int N = packageServices.size();
4111 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4112 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4113
4114 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4115 for (int i = 0; i < N; ++i) {
4116 intentFilters = packageServices.get(i).intents;
4117 if (intentFilters != null && intentFilters.size() > 0) {
4118 listCut.add(intentFilters);
4119 }
4120 }
4121 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4122 }
4123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004124 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004125 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 if (SHOW_INFO || Config.LOGV) Log.v(
4127 TAG, " " + (s.info.nonLocalizedLabel != null
4128 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4129 if (SHOW_INFO || Config.LOGV) Log.v(
4130 TAG, " Class=" + s.info.name);
4131 int NI = s.intents.size();
4132 int j;
4133 for (j=0; j<NI; j++) {
4134 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4135 if (SHOW_INFO || Config.LOGV) {
4136 Log.v(TAG, " IntentFilter:");
4137 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4138 }
4139 if (!intent.debugCheck()) {
4140 Log.w(TAG, "==> For Service " + s.info.name);
4141 }
4142 addFilter(intent);
4143 }
4144 }
4145
4146 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004147 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 if (SHOW_INFO || Config.LOGV) Log.v(
4149 TAG, " " + (s.info.nonLocalizedLabel != null
4150 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4151 if (SHOW_INFO || Config.LOGV) Log.v(
4152 TAG, " Class=" + s.info.name);
4153 int NI = s.intents.size();
4154 int j;
4155 for (j=0; j<NI; j++) {
4156 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4157 if (SHOW_INFO || Config.LOGV) {
4158 Log.v(TAG, " IntentFilter:");
4159 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4160 }
4161 removeFilter(intent);
4162 }
4163 }
4164
4165 @Override
4166 protected boolean allowFilterResult(
4167 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4168 ServiceInfo filterSi = filter.service.info;
4169 for (int i=dest.size()-1; i>=0; i--) {
4170 ServiceInfo destAi = dest.get(i).serviceInfo;
4171 if (destAi.name == filterSi.name
4172 && destAi.packageName == filterSi.packageName) {
4173 return false;
4174 }
4175 }
4176 return true;
4177 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004179 @Override
4180 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4181 int match) {
4182 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4183 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4184 return null;
4185 }
4186 final PackageParser.Service service = info.service;
4187 if (mSafeMode && (service.info.applicationInfo.flags
4188 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4189 return null;
4190 }
4191 final ResolveInfo res = new ResolveInfo();
4192 res.serviceInfo = PackageParser.generateServiceInfo(service,
4193 mFlags);
4194 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4195 res.filter = filter;
4196 }
4197 res.priority = info.getPriority();
4198 res.preferredOrder = service.owner.mPreferredOrder;
4199 //System.out.println("Result: " + res.activityInfo.className +
4200 // " = " + res.priority);
4201 res.match = match;
4202 res.isDefault = info.hasDefault;
4203 res.labelRes = info.labelRes;
4204 res.nonLocalizedLabel = info.nonLocalizedLabel;
4205 res.icon = info.icon;
4206 return res;
4207 }
4208
4209 @Override
4210 protected void sortResults(List<ResolveInfo> results) {
4211 Collections.sort(results, mResolvePrioritySorter);
4212 }
4213
4214 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004215 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004217 out.print(prefix); out.print(
4218 Integer.toHexString(System.identityHashCode(filter.service)));
4219 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004220 out.println(filter.service.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 }
4222
4223// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4224// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4225// final List<ResolveInfo> retList = Lists.newArrayList();
4226// while (i.hasNext()) {
4227// final ResolveInfo resolveInfo = (ResolveInfo) i;
4228// if (isEnabledLP(resolveInfo.serviceInfo)) {
4229// retList.add(resolveInfo);
4230// }
4231// }
4232// return retList;
4233// }
4234
4235 // Keys are String (activity class name), values are Activity.
4236 private final HashMap<ComponentName, PackageParser.Service> mServices
4237 = new HashMap<ComponentName, PackageParser.Service>();
4238 private int mFlags;
4239 };
4240
4241 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4242 new Comparator<ResolveInfo>() {
4243 public int compare(ResolveInfo r1, ResolveInfo r2) {
4244 int v1 = r1.priority;
4245 int v2 = r2.priority;
4246 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4247 if (v1 != v2) {
4248 return (v1 > v2) ? -1 : 1;
4249 }
4250 v1 = r1.preferredOrder;
4251 v2 = r2.preferredOrder;
4252 if (v1 != v2) {
4253 return (v1 > v2) ? -1 : 1;
4254 }
4255 if (r1.isDefault != r2.isDefault) {
4256 return r1.isDefault ? -1 : 1;
4257 }
4258 v1 = r1.match;
4259 v2 = r2.match;
4260 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4261 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4262 }
4263 };
4264
4265 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4266 new Comparator<ProviderInfo>() {
4267 public int compare(ProviderInfo p1, ProviderInfo p2) {
4268 final int v1 = p1.initOrder;
4269 final int v2 = p2.initOrder;
4270 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4271 }
4272 };
4273
4274 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4275 IActivityManager am = ActivityManagerNative.getDefault();
4276 if (am != null) {
4277 try {
4278 final Intent intent = new Intent(action,
4279 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4280 if (extras != null) {
4281 intent.putExtras(extras);
4282 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004283 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004284 am.broadcastIntent(
4285 null, intent,
4286 null, null, 0, null, null, null, false, false);
4287 } catch (RemoteException ex) {
4288 }
4289 }
4290 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004291
4292 public String nextPackageToClean(String lastPackage) {
4293 synchronized (mPackages) {
4294 if (!mMediaMounted) {
4295 // If the external storage is no longer mounted at this point,
4296 // the caller may not have been able to delete all of this
4297 // packages files and can not delete any more. Bail.
4298 return null;
4299 }
4300 if (lastPackage != null) {
4301 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4302 }
4303 return mSettings.mPackagesToBeCleaned.size() > 0
4304 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4305 }
4306 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004308 void schedulePackageCleaning(String packageName) {
4309 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4310 }
4311
4312 void startCleaningPackages() {
4313 synchronized (mPackages) {
4314 if (!mMediaMounted) {
4315 return;
4316 }
4317 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4318 return;
4319 }
4320 }
4321 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4322 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4323 IActivityManager am = ActivityManagerNative.getDefault();
4324 if (am != null) {
4325 try {
4326 am.startService(null, intent, null);
4327 } catch (RemoteException e) {
4328 }
4329 }
4330 }
4331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004332 private final class AppDirObserver extends FileObserver {
4333 public AppDirObserver(String path, int mask, boolean isrom) {
4334 super(path, mask);
4335 mRootDir = path;
4336 mIsRom = isrom;
4337 }
4338
4339 public void onEvent(int event, String path) {
4340 String removedPackage = null;
4341 int removedUid = -1;
4342 String addedPackage = null;
4343 int addedUid = -1;
4344
4345 synchronized (mInstallLock) {
4346 String fullPathStr = null;
4347 File fullPath = null;
4348 if (path != null) {
4349 fullPath = new File(mRootDir, path);
4350 fullPathStr = fullPath.getPath();
4351 }
4352
4353 if (Config.LOGV) Log.v(
4354 TAG, "File " + fullPathStr + " changed: "
4355 + Integer.toHexString(event));
4356
4357 if (!isPackageFilename(path)) {
4358 if (Config.LOGV) Log.v(
4359 TAG, "Ignoring change of non-package file: " + fullPathStr);
4360 return;
4361 }
4362
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004363 // Ignore packages that are being installed or
4364 // have just been installed.
4365 if (ignoreCodePath(fullPathStr)) {
4366 return;
4367 }
4368 PackageParser.Package p = null;
4369 synchronized (mPackages) {
4370 p = mAppDirs.get(fullPathStr);
4371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004372 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004373 if (p != null) {
4374 removePackageLI(p, true);
4375 removedPackage = p.applicationInfo.packageName;
4376 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004377 }
4378 }
4379
4380 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004381 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004382 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004383 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
4384 PackageParser.PARSE_CHATTY |
4385 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004386 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004387 if (p != null) {
4388 synchronized (mPackages) {
4389 grantPermissionsLP(p, false);
4390 }
4391 addedPackage = p.applicationInfo.packageName;
4392 addedUid = p.applicationInfo.uid;
4393 }
4394 }
4395 }
4396
4397 synchronized (mPackages) {
4398 mSettings.writeLP();
4399 }
4400 }
4401
4402 if (removedPackage != null) {
4403 Bundle extras = new Bundle(1);
4404 extras.putInt(Intent.EXTRA_UID, removedUid);
4405 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4406 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4407 }
4408 if (addedPackage != null) {
4409 Bundle extras = new Bundle(1);
4410 extras.putInt(Intent.EXTRA_UID, addedUid);
4411 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4412 }
4413 }
4414
4415 private final String mRootDir;
4416 private final boolean mIsRom;
4417 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004419 /* Called when a downloaded package installation has been confirmed by the user */
4420 public void installPackage(
4421 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004422 installPackage(packageURI, observer, flags, null);
4423 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004424
Jacek Surazski65e13172009-04-28 15:26:38 +02004425 /* Called when a downloaded package installation has been confirmed by the user */
4426 public void installPackage(
4427 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4428 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004429 mContext.enforceCallingOrSelfPermission(
4430 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004431
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004432 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004433 msg.obj = new InstallParams(packageURI, observer, flags,
4434 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004435 mHandler.sendMessage(msg);
4436 }
4437
Christopher Tate1bb69062010-02-19 17:02:12 -08004438 public void finishPackageInstall(int token) {
4439 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4440 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4441 mHandler.sendMessage(msg);
4442 }
4443
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004444 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004445 // Queue up an async operation since the package installation may take a little while.
4446 mHandler.post(new Runnable() {
4447 public void run() {
4448 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004449 // Result object to be returned
4450 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004451 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004452 res.uid = -1;
4453 res.pkg = null;
4454 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004455 args.doPreInstall(res.returnCode);
4456 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004457 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004458 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004459 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004460 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004461 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004462
4463 // A restore should be performed at this point if (a) the install
4464 // succeeded, (b) the operation is not an update, and (c) the new
4465 // package has a backupAgent defined.
4466 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004467 boolean doRestore = (!update
4468 && res.pkg != null
4469 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004470
4471 // Set up the post-install work request bookkeeping. This will be used
4472 // and cleaned up by the post-install event handling regardless of whether
4473 // there's a restore pass performed. Token values are >= 1.
4474 int token;
4475 if (mNextInstallToken < 0) mNextInstallToken = 1;
4476 token = mNextInstallToken++;
4477
4478 PostInstallData data = new PostInstallData(args, res);
4479 mRunningInstalls.put(token, data);
4480 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4481
4482 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4483 // Pass responsibility to the Backup Manager. It will perform a
4484 // restore if appropriate, then pass responsibility back to the
4485 // Package Manager to run the post-install observer callbacks
4486 // and broadcasts.
4487 IBackupManager bm = IBackupManager.Stub.asInterface(
4488 ServiceManager.getService(Context.BACKUP_SERVICE));
4489 if (bm != null) {
4490 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4491 + " to BM for possible restore");
4492 try {
4493 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4494 } catch (RemoteException e) {
4495 // can't happen; the backup manager is local
4496 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004497 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004498 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004499 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004500 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004501 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004502 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004504 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004505
4506 if (!doRestore) {
4507 // No restore possible, or the Backup Manager was mysteriously not
4508 // available -- just fire the post-install work request directly.
4509 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4510 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4511 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004513 }
4514 });
4515 }
4516
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004517 abstract class HandlerParams {
4518 final static int MAX_RETRIES = 4;
4519 int retry = 0;
4520 final void startCopy() {
4521 try {
4522 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4523 retry++;
4524 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004525 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004526 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4527 handleServiceError();
4528 return;
4529 } else {
4530 handleStartCopy();
4531 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4532 mHandler.sendEmptyMessage(MCS_UNBIND);
4533 }
4534 } catch (RemoteException e) {
4535 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4536 mHandler.sendEmptyMessage(MCS_RECONNECT);
4537 }
4538 handleReturnCode();
4539 }
4540
4541 final void serviceError() {
4542 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4543 handleServiceError();
4544 handleReturnCode();
4545 }
4546 abstract void handleStartCopy() throws RemoteException;
4547 abstract void handleServiceError();
4548 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004549 }
4550
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004551 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004552 final IPackageInstallObserver observer;
4553 int flags;
4554 final Uri packageURI;
4555 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004556 private InstallArgs mArgs;
4557 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004558 InstallParams(Uri packageURI,
4559 IPackageInstallObserver observer, int flags,
4560 String installerPackageName) {
4561 this.packageURI = packageURI;
4562 this.flags = flags;
4563 this.observer = observer;
4564 this.installerPackageName = installerPackageName;
4565 }
4566
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004567 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4568 String packageName = pkgLite.packageName;
4569 int installLocation = pkgLite.installLocation;
4570 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4571 synchronized (mPackages) {
4572 PackageParser.Package pkg = mPackages.get(packageName);
4573 if (pkg != null) {
4574 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4575 // Check for updated system application.
4576 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4577 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004578 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004579 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4580 }
4581 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4582 } else {
4583 // When replacing apps make sure we honour
4584 // the existing app location if not overwritten by other options
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08004585 boolean prevOnSd = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004586 if (onSd) {
4587 // Install flag overrides everything.
4588 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4589 }
4590 // If current upgrade does not specify install location.
4591 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4592 // Application explicitly specified internal.
4593 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4594 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4595 // App explictly prefers external. Let policy decide
4596 } else if (installLocation == PackageInfo.INSTALL_LOCATION_AUTO) {
4597 // Prefer previous location
4598 return prevOnSd ? PackageHelper.RECOMMEND_INSTALL_EXTERNAL:
4599 PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4600 }
4601 }
4602 } else {
4603 // Invalid install. Return error code
4604 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4605 }
4606 }
4607 }
4608 // All the special cases have been taken care of.
4609 // Return result based on recommended install location.
4610 if (onSd) {
4611 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4612 }
4613 return pkgLite.recommendedInstallLocation;
4614 }
4615
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004616 /*
4617 * Invoke remote method to get package information and install
4618 * location values. Override install location based on default
4619 * policy if needed and then create install arguments based
4620 * on the install location.
4621 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004622 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004623 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004624 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4625 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004626 // Dont need to invoke getInstallLocation for forward locked apps.
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004627 if (fwdLocked && onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004628 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004629 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004630 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004631 // Remote call to find out default install location
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004632 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004633 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004634 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4635 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4636 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4637 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4638 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004639 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4640 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4641 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004642 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4643 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004644 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004645 // Override with defaults if needed.
4646 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004647 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004648 if ((flags & PackageManager.INSTALL_EXTERNAL) == 0){
4649 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4650 // Set the flag to install on external media.
4651 flags |= PackageManager.INSTALL_EXTERNAL;
4652 } else {
4653 // Make sure the flag for installing on external
4654 // media is unset
4655 flags &= ~PackageManager.INSTALL_EXTERNAL;
4656 }
4657 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004658 }
4659 }
4660 // Create the file args now.
4661 mArgs = createInstallArgs(this);
4662 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4663 // Create copy only if we are not in an erroneous state.
4664 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004665 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004666 }
4667 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004668 }
4669
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004670 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004671 void handleReturnCode() {
4672 processPendingInstall(mArgs, mRet);
4673 }
4674
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004675 @Override
4676 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004677 mArgs = createInstallArgs(this);
4678 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004679 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004680 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004681
4682 /*
4683 * Utility class used in movePackage api.
4684 * srcArgs and targetArgs are not set for invalid flags and make
4685 * sure to do null checks when invoking methods on them.
4686 * We probably want to return ErrorPrams for both failed installs
4687 * and moves.
4688 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004689 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004690 final IPackageMoveObserver observer;
4691 final int flags;
4692 final String packageName;
4693 final InstallArgs srcArgs;
4694 final InstallArgs targetArgs;
4695 int mRet;
4696 MoveParams(InstallArgs srcArgs,
4697 IPackageMoveObserver observer,
4698 int flags, String packageName) {
4699 this.srcArgs = srcArgs;
4700 this.observer = observer;
4701 this.flags = flags;
4702 this.packageName = packageName;
4703 if (srcArgs != null) {
4704 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4705 targetArgs = createInstallArgs(packageUri, flags, packageName);
4706 } else {
4707 targetArgs = null;
4708 }
4709 }
4710
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004711 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004712 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4713 // Check for storage space on target medium
4714 if (!targetArgs.checkFreeStorage(mContainerService)) {
4715 Log.w(TAG, "Insufficient storage to install");
4716 return;
4717 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004718 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004719 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004720 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004721 if (DEBUG_SD_INSTALL) {
4722 StringBuilder builder = new StringBuilder();
4723 if (srcArgs != null) {
4724 builder.append("src: ");
4725 builder.append(srcArgs.getCodePath());
4726 }
4727 if (targetArgs != null) {
4728 builder.append(" target : ");
4729 builder.append(targetArgs.getCodePath());
4730 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004731 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004732 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004733 }
4734
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004735 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004736 void handleReturnCode() {
4737 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004738 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4739 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4740 currentStatus = PackageManager.MOVE_SUCCEEDED;
4741 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4742 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4743 }
4744 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004745 }
4746
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004747 @Override
4748 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004749 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004750 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004751 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004752
4753 private InstallArgs createInstallArgs(InstallParams params) {
4754 if (installOnSd(params.flags)) {
4755 return new SdInstallArgs(params);
4756 } else {
4757 return new FileInstallArgs(params);
4758 }
4759 }
4760
4761 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4762 if (installOnSd(flags)) {
4763 return new SdInstallArgs(fullCodePath, fullResourcePath);
4764 } else {
4765 return new FileInstallArgs(fullCodePath, fullResourcePath);
4766 }
4767 }
4768
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004769 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4770 if (installOnSd(flags)) {
4771 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4772 return new SdInstallArgs(packageURI, cid);
4773 } else {
4774 return new FileInstallArgs(packageURI, pkgName);
4775 }
4776 }
4777
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004778 static abstract class InstallArgs {
4779 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004780 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004781 final int flags;
4782 final Uri packageURI;
4783 final String installerPackageName;
4784
4785 InstallArgs(Uri packageURI,
4786 IPackageInstallObserver observer, int flags,
4787 String installerPackageName) {
4788 this.packageURI = packageURI;
4789 this.flags = flags;
4790 this.observer = observer;
4791 this.installerPackageName = installerPackageName;
4792 }
4793
4794 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004795 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004796 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004797 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004798 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004799 abstract String getCodePath();
4800 abstract String getResourcePath();
4801 // Need installer lock especially for dex file removal.
4802 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004803 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004804 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004805 }
4806
4807 class FileInstallArgs extends InstallArgs {
4808 File installDir;
4809 String codeFileName;
4810 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004811 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004812
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004813 FileInstallArgs(InstallParams params) {
4814 super(params.packageURI, params.observer,
4815 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004816 }
4817
4818 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4819 super(null, null, 0, null);
4820 File codeFile = new File(fullCodePath);
4821 installDir = codeFile.getParentFile();
4822 codeFileName = fullCodePath;
4823 resourceFileName = fullResourcePath;
4824 }
4825
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004826 FileInstallArgs(Uri packageURI, String pkgName) {
4827 super(packageURI, null, 0, null);
4828 boolean fwdLocked = isFwdLocked(flags);
4829 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4830 String apkName = getNextCodePath(null, pkgName, ".apk");
4831 codeFileName = new File(installDir, apkName + ".apk").getPath();
4832 resourceFileName = getResourcePathFromCodePath();
4833 }
4834
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004835 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4836 return imcs.checkFreeStorage(false, packageURI);
4837 }
4838
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004839 String getCodePath() {
4840 return codeFileName;
4841 }
4842
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004843 void createCopyFile() {
4844 boolean fwdLocked = isFwdLocked(flags);
4845 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4846 codeFileName = createTempPackageFile(installDir).getPath();
4847 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004848 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004849 }
4850
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004851 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004852 if (temp) {
4853 // Generate temp file name
4854 createCopyFile();
4855 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004856 // Get a ParcelFileDescriptor to write to the output file
4857 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004858 if (!created) {
4859 try {
4860 codeFile.createNewFile();
4861 // Set permissions
4862 if (!setPermissions()) {
4863 // Failed setting permissions.
4864 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4865 }
4866 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004867 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004868 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4869 }
4870 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004871 ParcelFileDescriptor out = null;
4872 try {
4873 out = ParcelFileDescriptor.open(codeFile,
4874 ParcelFileDescriptor.MODE_READ_WRITE);
4875 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004876 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004877 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4878 }
4879 // Copy the resource now
4880 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4881 try {
4882 if (imcs.copyResource(packageURI, out)) {
4883 ret = PackageManager.INSTALL_SUCCEEDED;
4884 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004885 } finally {
4886 try { if (out != null) out.close(); } catch (IOException e) {}
4887 }
4888 return ret;
4889 }
4890
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004891 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004892 if (status != PackageManager.INSTALL_SUCCEEDED) {
4893 cleanUp();
4894 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004895 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004896 }
4897
4898 boolean doRename(int status, final String pkgName, String oldCodePath) {
4899 if (status != PackageManager.INSTALL_SUCCEEDED) {
4900 cleanUp();
4901 return false;
4902 } else {
4903 // Rename based on packageName
4904 File codeFile = new File(getCodePath());
4905 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
4906 File desFile = new File(installDir, apkName + ".apk");
4907 if (!codeFile.renameTo(desFile)) {
4908 return false;
4909 }
4910 // Reset paths since the file has been renamed.
4911 codeFileName = desFile.getPath();
4912 resourceFileName = getResourcePathFromCodePath();
4913 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004914 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004915 // Failed setting permissions.
4916 return false;
4917 }
4918 return true;
4919 }
4920 }
4921
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004922 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004923 if (status != PackageManager.INSTALL_SUCCEEDED) {
4924 cleanUp();
4925 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004926 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004927 }
4928
4929 String getResourcePath() {
4930 return resourceFileName;
4931 }
4932
4933 String getResourcePathFromCodePath() {
4934 String codePath = getCodePath();
4935 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4936 String apkNameOnly = getApkName(codePath);
4937 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
4938 } else {
4939 return codePath;
4940 }
4941 }
4942
4943 private boolean cleanUp() {
4944 boolean ret = true;
4945 String sourceDir = getCodePath();
4946 String publicSourceDir = getResourcePath();
4947 if (sourceDir != null) {
4948 File sourceFile = new File(sourceDir);
4949 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004950 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004951 ret = false;
4952 }
4953 // Delete application's code and resources
4954 sourceFile.delete();
4955 }
4956 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4957 final File publicSourceFile = new File(publicSourceDir);
4958 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004959 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004960 }
4961 if (publicSourceFile.exists()) {
4962 publicSourceFile.delete();
4963 }
4964 }
4965 return ret;
4966 }
4967
4968 void cleanUpResourcesLI() {
4969 String sourceDir = getCodePath();
4970 if (cleanUp() && mInstaller != null) {
4971 int retCode = mInstaller.rmdex(sourceDir);
4972 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004973 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004974 + " at location "
4975 + sourceDir + ", retcode=" + retCode);
4976 // we don't consider this to be a failure of the core package deletion
4977 }
4978 }
4979 }
4980
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004981 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004982 // TODO Do this in a more elegant way later on. for now just a hack
4983 if (!isFwdLocked(flags)) {
4984 final int filePermissions =
4985 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4986 |FileUtils.S_IROTH;
4987 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
4988 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004989 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004990 getCodePath()
4991 + ". The return code was: " + retCode);
4992 // TODO Define new internal error
4993 return false;
4994 }
4995 return true;
4996 }
4997 return true;
4998 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004999
5000 boolean doPostDeleteLI(boolean delete) {
5001 cleanUpResourcesLI();
5002 return true;
5003 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005004 }
5005
5006 class SdInstallArgs extends InstallArgs {
5007 String cid;
5008 String cachePath;
5009 static final String RES_FILE_NAME = "pkg.apk";
5010
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005011 SdInstallArgs(InstallParams params) {
5012 super(params.packageURI, params.observer,
5013 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005014 }
5015
5016 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005017 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005018 // Extract cid from fullCodePath
5019 int eidx = fullCodePath.lastIndexOf("/");
5020 String subStr1 = fullCodePath.substring(0, eidx);
5021 int sidx = subStr1.lastIndexOf("/");
5022 cid = subStr1.substring(sidx+1, eidx);
5023 cachePath = subStr1;
5024 }
5025
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005026 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005027 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5028 this.cid = cid;
5029 }
5030
5031 SdInstallArgs(Uri packageURI, String cid) {
5032 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005033 this.cid = cid;
5034 }
5035
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005036 void createCopyFile() {
5037 cid = getTempContainerId();
5038 }
5039
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005040 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5041 return imcs.checkFreeStorage(true, packageURI);
5042 }
5043
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005044 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005045 if (temp) {
5046 createCopyFile();
5047 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005048 cachePath = imcs.copyResourceToContainer(
5049 packageURI, cid,
5050 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005051 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5052 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005053 }
5054
5055 @Override
5056 String getCodePath() {
5057 return cachePath + "/" + RES_FILE_NAME;
5058 }
5059
5060 @Override
5061 String getResourcePath() {
5062 return cachePath + "/" + RES_FILE_NAME;
5063 }
5064
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005065 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005066 if (status != PackageManager.INSTALL_SUCCEEDED) {
5067 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005068 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005069 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005070 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005071 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005072 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005073 if (cachePath == null) {
5074 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5075 }
5076 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005077 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005078 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005079 }
5080
5081 boolean doRename(int status, final String pkgName,
5082 String oldCodePath) {
5083 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005084 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005085 if (PackageHelper.isContainerMounted(cid)) {
5086 // Unmount the container
5087 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005088 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005089 return false;
5090 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005091 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005092 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005093 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005094 return false;
5095 }
5096 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005097 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005098 newCachePath = PackageHelper.mountSdDir(newCacheId,
5099 getEncryptKey(), Process.SYSTEM_UID);
5100 } else {
5101 newCachePath = PackageHelper.getSdDir(newCacheId);
5102 }
5103 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005104 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005105 return false;
5106 }
5107 Log.i(TAG, "Succesfully renamed " + cid +
5108 " at path: " + cachePath + " to " + newCacheId +
5109 " at new path: " + newCachePath);
5110 cid = newCacheId;
5111 cachePath = newCachePath;
5112 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005113 }
5114
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005115 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005116 if (status != PackageManager.INSTALL_SUCCEEDED) {
5117 cleanUp();
5118 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005119 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005120 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005121 PackageHelper.mountSdDir(cid,
5122 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005123 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005124 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005125 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005126 }
5127
5128 private void cleanUp() {
5129 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005130 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005131 }
5132
5133 void cleanUpResourcesLI() {
5134 String sourceFile = getCodePath();
5135 // Remove dex file
5136 if (mInstaller != null) {
5137 int retCode = mInstaller.rmdex(sourceFile.toString());
5138 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005139 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005140 + " at location "
5141 + sourceFile.toString() + ", retcode=" + retCode);
5142 // we don't consider this to be a failure of the core package deletion
5143 }
5144 }
5145 cleanUp();
5146 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005147
5148 boolean matchContainer(String app) {
5149 if (cid.startsWith(app)) {
5150 return true;
5151 }
5152 return false;
5153 }
5154
5155 String getPackageName() {
5156 int idx = cid.lastIndexOf("-");
5157 if (idx == -1) {
5158 return cid;
5159 }
5160 return cid.substring(0, idx);
5161 }
5162
5163 boolean doPostDeleteLI(boolean delete) {
5164 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005165 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005166 if (mounted) {
5167 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005168 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005169 }
5170 if (ret && delete) {
5171 cleanUpResourcesLI();
5172 }
5173 return ret;
5174 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005175 };
5176
5177 // Utility method used to create code paths based on package name and available index.
5178 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5179 String idxStr = "";
5180 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005181 // Fall back to default value of idx=1 if prefix is not
5182 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005183 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005184 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005185 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005186 if (subStr.endsWith(suffix)) {
5187 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005188 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005189 // If oldCodePath already contains prefix find out the
5190 // ending index to either increment or decrement.
5191 int sidx = subStr.lastIndexOf(prefix);
5192 if (sidx != -1) {
5193 subStr = subStr.substring(sidx + prefix.length());
5194 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005195 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5196 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005197 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005198 try {
5199 idx = Integer.parseInt(subStr);
5200 if (idx <= 1) {
5201 idx++;
5202 } else {
5203 idx--;
5204 }
5205 } catch(NumberFormatException e) {
5206 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005207 }
5208 }
5209 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005210 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005211 return prefix + idxStr;
5212 }
5213
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005214 // Utility method used to ignore ADD/REMOVE events
5215 // by directory observer.
5216 private static boolean ignoreCodePath(String fullPathStr) {
5217 String apkName = getApkName(fullPathStr);
5218 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5219 if (idx != -1 && ((idx+1) < apkName.length())) {
5220 // Make sure the package ends with a numeral
5221 String version = apkName.substring(idx+1);
5222 try {
5223 Integer.parseInt(version);
5224 return true;
5225 } catch (NumberFormatException e) {}
5226 }
5227 return false;
5228 }
5229
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005230 // Utility method that returns the relative package path with respect
5231 // to the installation directory. Like say for /data/data/com.test-1.apk
5232 // string com.test-1 is returned.
5233 static String getApkName(String codePath) {
5234 if (codePath == null) {
5235 return null;
5236 }
5237 int sidx = codePath.lastIndexOf("/");
5238 int eidx = codePath.lastIndexOf(".");
5239 if (eidx == -1) {
5240 eidx = codePath.length();
5241 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005242 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005243 return null;
5244 }
5245 return codePath.substring(sidx+1, eidx);
5246 }
5247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005248 class PackageInstalledInfo {
5249 String name;
5250 int uid;
5251 PackageParser.Package pkg;
5252 int returnCode;
5253 PackageRemovedInfo removedInfo;
5254 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005256 /*
5257 * Install a non-existing package.
5258 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005259 private void installNewPackageLI(PackageParser.Package pkg,
5260 int parseFlags,
5261 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005262 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005263 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005264 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005265
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005266 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005267 res.name = pkgName;
5268 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005269 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005270 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005271 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005272 + " without first uninstalling.");
5273 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5274 return;
5275 }
5276 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005277 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005278 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005279 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005280 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005281 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5282 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5283 }
5284 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005285 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005286 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005287 res);
5288 // delete the partially installed application. the data directory will have to be
5289 // restored if it was already existing
5290 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5291 // remove package from internal structures. Note that we want deletePackageX to
5292 // delete the package data and cache directories that it created in
5293 // scanPackageLocked, unless those directories existed before we even tried to
5294 // install.
5295 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005296 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005297 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5298 res.removedInfo);
5299 }
5300 }
5301 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005302
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005303 private void replacePackageLI(PackageParser.Package pkg,
5304 int parseFlags,
5305 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005306 String installerPackageName, PackageInstalledInfo res) {
5307
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005308 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005309 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005310 // First find the old package info and check signatures
5311 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005312 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005313 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005314 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005315 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5316 return;
5317 }
5318 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005319 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005320 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005321 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005322 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005323 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005324 }
5325 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005327 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005328 PackageParser.Package pkg,
5329 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005330 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005331 PackageParser.Package newPackage = null;
5332 String pkgName = deletedPackage.packageName;
5333 boolean deletedPkg = true;
5334 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005335
Jacek Surazski65e13172009-04-28 15:26:38 +02005336 String oldInstallerPackageName = null;
5337 synchronized (mPackages) {
5338 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5339 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005340
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005341 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005342 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005343 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005344 res.removedInfo)) {
5345 // If the existing package was'nt successfully deleted
5346 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5347 deletedPkg = false;
5348 } else {
5349 // Successfully deleted the old package. Now proceed with re-installation
5350 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005351 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005352 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005353 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005354 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5355 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005356 }
5357 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005358 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005359 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005360 res);
5361 updatedSettings = true;
5362 }
5363 }
5364
5365 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5366 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005367 // were keeping around in case we needed them (see below) can now be deleted.
5368 // This info will be set on the res.removedInfo to clean up later on as post
5369 // install action.
5370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005371 //update signature on the new package setting
5372 //this should always succeed, since we checked the
5373 //signature earlier.
5374 synchronized(mPackages) {
5375 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
5376 parseFlags, true);
5377 }
5378 } else {
5379 // remove package from internal structures. Note that we want deletePackageX to
5380 // delete the package data and cache directories that it created in
5381 // scanPackageLocked, unless those directories existed before we even tried to
5382 // install.
5383 if(updatedSettings) {
5384 deletePackageLI(
5385 pkgName, true,
5386 PackageManager.DONT_DELETE_DATA,
5387 res.removedInfo);
5388 }
5389 // Since we failed to install the new package we need to restore the old
5390 // package that we deleted.
5391 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005392 File restoreFile = new File(deletedPackage.mPath);
5393 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005394 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005395 return;
5396 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005397 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5398 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005399 // Parse old package
5400 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5401 scanPackageLI(restoreFile, parseFlags, scanMode);
5402 synchronized (mPackages) {
5403 grantPermissionsLP(deletedPackage, false);
5404 mSettings.writeLP();
5405 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005406 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005407 Slog.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005409 }
5410 }
5411 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005413 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005414 PackageParser.Package pkg,
5415 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005416 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005417 PackageParser.Package newPackage = null;
5418 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005419 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005420 PackageParser.PARSE_IS_SYSTEM;
5421 String packageName = deletedPackage.packageName;
5422 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5423 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005424 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005425 return;
5426 }
5427 PackageParser.Package oldPkg;
5428 PackageSetting oldPkgSetting;
5429 synchronized (mPackages) {
5430 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005431 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005432 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5433 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005434 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005435 return;
5436 }
5437 }
5438 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5439 res.removedInfo.removedPackage = packageName;
5440 // Remove existing system package
5441 removePackageLI(oldPkg, true);
5442 synchronized (mPackages) {
5443 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5444 }
5445
5446 // Successfully disabled the old package. Now proceed with re-installation
5447 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5448 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005449 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005450 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005451 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005452 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5453 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5454 }
5455 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005456 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005457 updatedSettings = true;
5458 }
5459
5460 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5461 //update signature on the new package setting
5462 //this should always succeed, since we checked the
5463 //signature earlier.
5464 synchronized(mPackages) {
5465 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5466 parseFlags, true);
5467 }
5468 } else {
5469 // Re installation failed. Restore old information
5470 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005471 if (newPackage != null) {
5472 removePackageLI(newPackage, true);
5473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005474 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005475 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005476 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005477 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005478 // Restore the old system information in Settings
5479 synchronized(mPackages) {
5480 if(updatedSettings) {
5481 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005482 mSettings.setInstallerPackageName(packageName,
5483 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005484 }
5485 mSettings.writeLP();
5486 }
5487 }
5488 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005489
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005490 // Utility method used to move dex files during install.
5491 private int moveDexFiles(PackageParser.Package newPackage) {
5492 int retCode;
5493 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5494 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5495 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005496 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005497 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5498 }
5499 }
5500 return PackageManager.INSTALL_SUCCEEDED;
5501 }
5502
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005503 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005504 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005505 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005506 synchronized (mPackages) {
5507 //write settings. the installStatus will be incomplete at this stage.
5508 //note that the new package setting would have already been
5509 //added to mPackages. It hasn't been persisted yet.
5510 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5511 mSettings.writeLP();
5512 }
5513
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005514 if ((res.returnCode = moveDexFiles(newPackage))
5515 != PackageManager.INSTALL_SUCCEEDED) {
5516 // Discontinue if moving dex files failed.
5517 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005518 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005519 if((res.returnCode = setPermissionsLI(newPackage))
5520 != PackageManager.INSTALL_SUCCEEDED) {
5521 if (mInstaller != null) {
5522 mInstaller.rmdex(newPackage.mScanPath);
5523 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005524 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005525 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005526 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005528 synchronized (mPackages) {
5529 grantPermissionsLP(newPackage, true);
5530 res.name = pkgName;
5531 res.uid = newPackage.applicationInfo.uid;
5532 res.pkg = newPackage;
5533 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005534 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005535 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5536 //to update install status
5537 mSettings.writeLP();
5538 }
5539 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005540
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005541 private void installPackageLI(InstallArgs args,
5542 boolean newInstall, PackageInstalledInfo res) {
5543 int pFlags = args.flags;
5544 String installerPackageName = args.installerPackageName;
5545 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005546 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005547 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005548 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005549 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5550 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005551 // Result object to be returned
5552 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5553
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005554 // Retrieve PackageSettings and parse package
5555 int parseFlags = PackageParser.PARSE_CHATTY |
5556 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5557 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5558 parseFlags |= mDefParseFlags;
5559 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5560 pp.setSeparateProcesses(mSeparateProcesses);
5561 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5562 null, mMetrics, parseFlags);
5563 if (pkg == null) {
5564 res.returnCode = pp.getParseError();
5565 return;
5566 }
5567 String pkgName = res.name = pkg.packageName;
5568 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5569 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5570 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5571 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005572 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005573 }
5574 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5575 res.returnCode = pp.getParseError();
5576 return;
5577 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005578 // Get rid of all references to package scan path via parser.
5579 pp = null;
5580 String oldCodePath = null;
5581 boolean systemApp = false;
5582 synchronized (mPackages) {
5583 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005584 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5585 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005586 if (pkg.mOriginalPackages != null
5587 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005588 && mPackages.containsKey(oldName)) {
5589 // This package is derived from an original package,
5590 // and this device has been updating from that original
5591 // name. We must continue using the original name, so
5592 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005593 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005594 pkgName = pkg.packageName;
5595 replace = true;
5596 } else if (mPackages.containsKey(pkgName)) {
5597 // This package, under its official name, already exists
5598 // on the device; we should replace it.
5599 replace = true;
5600 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005601 }
5602 PackageSetting ps = mSettings.mPackages.get(pkgName);
5603 if (ps != null) {
5604 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5605 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5606 systemApp = (ps.pkg.applicationInfo.flags &
5607 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005608 }
5609 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005610 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005611
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005612 if (systemApp && onSd) {
5613 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005614 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005615 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5616 return;
5617 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005618
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005619 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5620 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5621 return;
5622 }
5623 // Set application objects path explicitly after the rename
5624 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005625 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005626 replacePackageLI(pkg, parseFlags, scanMode,
5627 installerPackageName, res);
5628 } else {
5629 installNewPackageLI(pkg, parseFlags, scanMode,
5630 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005631 }
5632 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005633
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005634 private int setPermissionsLI(PackageParser.Package newPackage) {
5635 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005636 int retCode = 0;
5637 // TODO Gross hack but fix later. Ideally move this to be a post installation
5638 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005639 if ((newPackage.applicationInfo.flags
5640 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5641 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 try {
5643 extractPublicFiles(newPackage, destResourceFile);
5644 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005645 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005646 " forward-locked app.");
5647 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5648 } finally {
5649 //TODO clean up the extracted public files
5650 }
5651 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005652 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005653 newPackage.applicationInfo.uid);
5654 } else {
5655 final int filePermissions =
5656 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005657 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005658 newPackage.applicationInfo.uid);
5659 }
5660 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005661 // The permissions on the resource file was set when it was copied for
5662 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005663 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005665 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005666 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005667 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005668 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005669 // TODO Define new internal error
5670 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005671 }
5672 return PackageManager.INSTALL_SUCCEEDED;
5673 }
5674
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005675 private boolean isForwardLocked(PackageParser.Package pkg) {
5676 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005677 }
5678
5679 private void extractPublicFiles(PackageParser.Package newPackage,
5680 File publicZipFile) throws IOException {
5681 final ZipOutputStream publicZipOutStream =
5682 new ZipOutputStream(new FileOutputStream(publicZipFile));
5683 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5684
5685 // Copy manifest, resources.arsc and res directory to public zip
5686
5687 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5688 while (privateZipEntries.hasMoreElements()) {
5689 final ZipEntry zipEntry = privateZipEntries.nextElement();
5690 final String zipEntryName = zipEntry.getName();
5691 if ("AndroidManifest.xml".equals(zipEntryName)
5692 || "resources.arsc".equals(zipEntryName)
5693 || zipEntryName.startsWith("res/")) {
5694 try {
5695 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5696 } catch (IOException e) {
5697 try {
5698 publicZipOutStream.close();
5699 throw e;
5700 } finally {
5701 publicZipFile.delete();
5702 }
5703 }
5704 }
5705 }
5706
5707 publicZipOutStream.close();
5708 FileUtils.setPermissions(
5709 publicZipFile.getAbsolutePath(),
5710 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5711 -1, -1);
5712 }
5713
5714 private static void copyZipEntry(ZipEntry zipEntry,
5715 ZipFile inZipFile,
5716 ZipOutputStream outZipStream) throws IOException {
5717 byte[] buffer = new byte[4096];
5718 int num;
5719
5720 ZipEntry newEntry;
5721 if (zipEntry.getMethod() == ZipEntry.STORED) {
5722 // Preserve the STORED method of the input entry.
5723 newEntry = new ZipEntry(zipEntry);
5724 } else {
5725 // Create a new entry so that the compressed len is recomputed.
5726 newEntry = new ZipEntry(zipEntry.getName());
5727 }
5728 outZipStream.putNextEntry(newEntry);
5729
5730 InputStream data = inZipFile.getInputStream(zipEntry);
5731 while ((num = data.read(buffer)) > 0) {
5732 outZipStream.write(buffer, 0, num);
5733 }
5734 outZipStream.flush();
5735 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005737 private void deleteTempPackageFiles() {
5738 FilenameFilter filter = new FilenameFilter() {
5739 public boolean accept(File dir, String name) {
5740 return name.startsWith("vmdl") && name.endsWith(".tmp");
5741 }
5742 };
5743 String tmpFilesList[] = mAppInstallDir.list(filter);
5744 if(tmpFilesList == null) {
5745 return;
5746 }
5747 for(int i = 0; i < tmpFilesList.length; i++) {
5748 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5749 tmpFile.delete();
5750 }
5751 }
5752
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005753 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 File tmpPackageFile;
5755 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005756 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005757 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005758 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005759 return null;
5760 }
5761 try {
5762 FileUtils.setPermissions(
5763 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5764 -1, -1);
5765 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005766 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005767 return null;
5768 }
5769 return tmpPackageFile;
5770 }
5771
5772 public void deletePackage(final String packageName,
5773 final IPackageDeleteObserver observer,
5774 final int flags) {
5775 mContext.enforceCallingOrSelfPermission(
5776 android.Manifest.permission.DELETE_PACKAGES, null);
5777 // Queue up an async operation since the package deletion may take a little while.
5778 mHandler.post(new Runnable() {
5779 public void run() {
5780 mHandler.removeCallbacks(this);
5781 final boolean succeded = deletePackageX(packageName, true, true, flags);
5782 if (observer != null) {
5783 try {
5784 observer.packageDeleted(succeded);
5785 } catch (RemoteException e) {
5786 Log.i(TAG, "Observer no longer exists.");
5787 } //end catch
5788 } //end if
5789 } //end run
5790 });
5791 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005793 /**
5794 * This method is an internal method that could be get invoked either
5795 * to delete an installed package or to clean up a failed installation.
5796 * After deleting an installed package, a broadcast is sent to notify any
5797 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005798 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005799 * installation wouldn't have sent the initial broadcast either
5800 * The key steps in deleting a package are
5801 * deleting the package information in internal structures like mPackages,
5802 * deleting the packages base directories through installd
5803 * updating mSettings to reflect current status
5804 * persisting settings for later use
5805 * sending a broadcast if necessary
5806 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005807 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5808 boolean deleteCodeAndResources, int flags) {
5809 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005810 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005811
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005812 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
5813 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
5814 try {
5815 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005816 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005817 return false;
5818 }
5819 } catch (RemoteException e) {
5820 }
5821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005822 synchronized (mInstallLock) {
5823 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5824 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005826 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005827 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5828 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5829
5830 // If the removed package was a system update, the old system packaged
5831 // was re-enabled; we need to broadcast this information
5832 if (systemUpdate) {
5833 Bundle extras = new Bundle(1);
5834 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5835 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5836
5837 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5838 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005840 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005841 // Force a gc here.
5842 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005843 // Delete the resources here after sending the broadcast to let
5844 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005845 if (info.args != null) {
5846 synchronized (mInstallLock) {
5847 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005848 }
5849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005850 return res;
5851 }
5852
5853 static class PackageRemovedInfo {
5854 String removedPackage;
5855 int uid = -1;
5856 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005857 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005858 // Clean up resources deleted packages.
5859 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005861 void sendBroadcast(boolean fullRemove, boolean replacing) {
5862 Bundle extras = new Bundle(1);
5863 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5864 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5865 if (replacing) {
5866 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5867 }
5868 if (removedPackage != null) {
5869 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5870 }
5871 if (removedUid >= 0) {
5872 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5873 }
5874 }
5875 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005877 /*
5878 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5879 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005880 * 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 -08005881 * delete a partially installed application.
5882 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005883 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005884 int flags) {
5885 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005886 if (outInfo != null) {
5887 outInfo.removedPackage = packageName;
5888 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005889 removePackageLI(p, true);
5890 // Retrieve object to delete permissions for shared user later on
5891 PackageSetting deletedPs;
5892 synchronized (mPackages) {
5893 deletedPs = mSettings.mPackages.get(packageName);
5894 }
5895 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005896 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005897 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005898 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005899 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005900 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005901 + packageName + ", retcode=" + retCode);
5902 // we don't consider this to be a failure of the core package deletion
5903 }
5904 } else {
5905 //for emulator
5906 PackageParser.Package pkg = mPackages.get(packageName);
5907 File dataDir = new File(pkg.applicationInfo.dataDir);
5908 dataDir.delete();
5909 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005910 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005911 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005912 if (outInfo != null) {
5913 outInfo.removedUid = mSettings.removePackageLP(packageName);
5914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005915 }
5916 }
5917 synchronized (mPackages) {
5918 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5919 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005920 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005921 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005922 if (deletedPs != null) {
5923 // remove from preferred activities.
5924 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
5925 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
5926 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
5927 removed.add(pa);
5928 }
5929 }
5930 for (PreferredActivity pa : removed) {
5931 mSettings.mPreferredActivities.removeFilter(pa);
5932 }
5933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005934 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005935 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005936 }
5937 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005939 /*
5940 * Tries to delete system package.
5941 */
5942 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005943 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005944 ApplicationInfo applicationInfo = p.applicationInfo;
5945 //applicable for non-partially installed applications only
5946 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005947 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005948 return false;
5949 }
5950 PackageSetting ps = null;
5951 // Confirm if the system package has been updated
5952 // An updated system app can be deleted. This will also have to restore
5953 // the system pkg from system partition
5954 synchronized (mPackages) {
5955 ps = mSettings.getDisabledSystemPkg(p.packageName);
5956 }
5957 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005958 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 return false;
5960 } else {
5961 Log.i(TAG, "Deleting system pkg from data partition");
5962 }
5963 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005964 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005965 boolean deleteCodeAndResources = false;
5966 if (ps.versionCode < p.mVersionCode) {
5967 // Delete code and resources for downgrades
5968 deleteCodeAndResources = true;
5969 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5970 flags &= ~PackageManager.DONT_DELETE_DATA;
5971 }
5972 } else {
5973 // Preserve data by setting flag
5974 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5975 flags |= PackageManager.DONT_DELETE_DATA;
5976 }
5977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005978 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5979 if (!ret) {
5980 return false;
5981 }
5982 synchronized (mPackages) {
5983 // Reinstate the old system package
5984 mSettings.enableSystemPackageLP(p.packageName);
5985 }
5986 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005987 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005988 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005989 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005991 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005992 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005993 return false;
5994 }
5995 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07005996 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005997 mSettings.writeLP();
5998 }
5999 return true;
6000 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006002 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6003 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6004 ApplicationInfo applicationInfo = p.applicationInfo;
6005 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006006 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 return false;
6008 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006009 if (outInfo != null) {
6010 outInfo.uid = applicationInfo.uid;
6011 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006012
6013 // Delete package data from internal structures and also remove data if flag is set
6014 removePackageDataLI(p, outInfo, flags);
6015
6016 // Delete application code and resources
6017 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006018 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006019 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006020 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006021 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6022 PackageManager.INSTALL_FORWARD_LOCK : 0;
6023 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006024 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006025 }
6026 return true;
6027 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006029 /*
6030 * This method handles package deletion in general
6031 */
6032 private boolean deletePackageLI(String packageName,
6033 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6034 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006035 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006036 return false;
6037 }
6038 PackageParser.Package p;
6039 boolean dataOnly = false;
6040 synchronized (mPackages) {
6041 p = mPackages.get(packageName);
6042 if (p == null) {
6043 //this retrieves partially installed apps
6044 dataOnly = true;
6045 PackageSetting ps = mSettings.mPackages.get(packageName);
6046 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006047 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006048 return false;
6049 }
6050 p = ps.pkg;
6051 }
6052 }
6053 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006054 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006055 return false;
6056 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006058 if (dataOnly) {
6059 // Delete application data first
6060 removePackageDataLI(p, outInfo, flags);
6061 return true;
6062 }
6063 // At this point the package should have ApplicationInfo associated with it
6064 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006065 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 return false;
6067 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006068 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006069 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6070 Log.i(TAG, "Removing system package:"+p.packageName);
6071 // When an updated system application is deleted we delete the existing resources as well and
6072 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006073 ret = deleteSystemPackageLI(p, flags, outInfo);
6074 } else {
6075 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006076 // Kill application pre-emptively especially for apps on sd.
6077 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006078 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006079 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006080 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006083 public void clearApplicationUserData(final String packageName,
6084 final IPackageDataObserver observer) {
6085 mContext.enforceCallingOrSelfPermission(
6086 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6087 // Queue up an async operation since the package deletion may take a little while.
6088 mHandler.post(new Runnable() {
6089 public void run() {
6090 mHandler.removeCallbacks(this);
6091 final boolean succeeded;
6092 synchronized (mInstallLock) {
6093 succeeded = clearApplicationUserDataLI(packageName);
6094 }
6095 if (succeeded) {
6096 // invoke DeviceStorageMonitor's update method to clear any notifications
6097 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6098 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6099 if (dsm != null) {
6100 dsm.updateMemory();
6101 }
6102 }
6103 if(observer != null) {
6104 try {
6105 observer.onRemoveCompleted(packageName, succeeded);
6106 } catch (RemoteException e) {
6107 Log.i(TAG, "Observer no longer exists.");
6108 }
6109 } //end if observer
6110 } //end run
6111 });
6112 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006114 private boolean clearApplicationUserDataLI(String packageName) {
6115 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006116 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006117 return false;
6118 }
6119 PackageParser.Package p;
6120 boolean dataOnly = false;
6121 synchronized (mPackages) {
6122 p = mPackages.get(packageName);
6123 if(p == null) {
6124 dataOnly = true;
6125 PackageSetting ps = mSettings.mPackages.get(packageName);
6126 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006127 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006128 return false;
6129 }
6130 p = ps.pkg;
6131 }
6132 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006133 boolean useEncryptedFSDir = false;
6134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006135 if(!dataOnly) {
6136 //need to check this only for fully installed applications
6137 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006138 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006139 return false;
6140 }
6141 final ApplicationInfo applicationInfo = p.applicationInfo;
6142 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006143 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006144 return false;
6145 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006146 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006147 }
6148 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006149 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006150 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006151 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006152 + packageName);
6153 return false;
6154 }
6155 }
6156 return true;
6157 }
6158
6159 public void deleteApplicationCacheFiles(final String packageName,
6160 final IPackageDataObserver observer) {
6161 mContext.enforceCallingOrSelfPermission(
6162 android.Manifest.permission.DELETE_CACHE_FILES, null);
6163 // Queue up an async operation since the package deletion may take a little while.
6164 mHandler.post(new Runnable() {
6165 public void run() {
6166 mHandler.removeCallbacks(this);
6167 final boolean succeded;
6168 synchronized (mInstallLock) {
6169 succeded = deleteApplicationCacheFilesLI(packageName);
6170 }
6171 if(observer != null) {
6172 try {
6173 observer.onRemoveCompleted(packageName, succeded);
6174 } catch (RemoteException e) {
6175 Log.i(TAG, "Observer no longer exists.");
6176 }
6177 } //end if observer
6178 } //end run
6179 });
6180 }
6181
6182 private boolean deleteApplicationCacheFilesLI(String packageName) {
6183 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006184 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 return false;
6186 }
6187 PackageParser.Package p;
6188 synchronized (mPackages) {
6189 p = mPackages.get(packageName);
6190 }
6191 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006192 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193 return false;
6194 }
6195 final ApplicationInfo applicationInfo = p.applicationInfo;
6196 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006197 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006198 return false;
6199 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006200 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006201 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006202 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006204 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006205 + packageName);
6206 return false;
6207 }
6208 }
6209 return true;
6210 }
6211
6212 public void getPackageSizeInfo(final String packageName,
6213 final IPackageStatsObserver observer) {
6214 mContext.enforceCallingOrSelfPermission(
6215 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6216 // Queue up an async operation since the package deletion may take a little while.
6217 mHandler.post(new Runnable() {
6218 public void run() {
6219 mHandler.removeCallbacks(this);
6220 PackageStats lStats = new PackageStats(packageName);
6221 final boolean succeded;
6222 synchronized (mInstallLock) {
6223 succeded = getPackageSizeInfoLI(packageName, lStats);
6224 }
6225 if(observer != null) {
6226 try {
6227 observer.onGetStatsCompleted(lStats, succeded);
6228 } catch (RemoteException e) {
6229 Log.i(TAG, "Observer no longer exists.");
6230 }
6231 } //end if observer
6232 } //end run
6233 });
6234 }
6235
6236 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6237 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006238 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006239 return false;
6240 }
6241 PackageParser.Package p;
6242 boolean dataOnly = false;
6243 synchronized (mPackages) {
6244 p = mPackages.get(packageName);
6245 if(p == null) {
6246 dataOnly = true;
6247 PackageSetting ps = mSettings.mPackages.get(packageName);
6248 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006249 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250 return false;
6251 }
6252 p = ps.pkg;
6253 }
6254 }
6255 String publicSrcDir = null;
6256 if(!dataOnly) {
6257 final ApplicationInfo applicationInfo = p.applicationInfo;
6258 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006259 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006260 return false;
6261 }
6262 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6263 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006264 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006265 if (mInstaller != null) {
6266 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006267 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268 if (res < 0) {
6269 return false;
6270 } else {
6271 return true;
6272 }
6273 }
6274 return true;
6275 }
6276
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006278 public void addPackageToPreferred(String packageName) {
6279 mContext.enforceCallingOrSelfPermission(
6280 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006281 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 }
6283
6284 public void removePackageFromPreferred(String packageName) {
6285 mContext.enforceCallingOrSelfPermission(
6286 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006287 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 }
6289
6290 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006291 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 }
6293
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006294 int getUidTargetSdkVersionLockedLP(int uid) {
6295 Object obj = mSettings.getUserIdLP(uid);
6296 if (obj instanceof SharedUserSetting) {
6297 SharedUserSetting sus = (SharedUserSetting)obj;
6298 final int N = sus.packages.size();
6299 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6300 Iterator<PackageSetting> it = sus.packages.iterator();
6301 int i=0;
6302 while (it.hasNext()) {
6303 PackageSetting ps = it.next();
6304 if (ps.pkg != null) {
6305 int v = ps.pkg.applicationInfo.targetSdkVersion;
6306 if (v < vers) vers = v;
6307 }
6308 }
6309 return vers;
6310 } else if (obj instanceof PackageSetting) {
6311 PackageSetting ps = (PackageSetting)obj;
6312 if (ps.pkg != null) {
6313 return ps.pkg.applicationInfo.targetSdkVersion;
6314 }
6315 }
6316 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6317 }
6318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006319 public void addPreferredActivity(IntentFilter filter, int match,
6320 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006321 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006322 if (mContext.checkCallingOrSelfPermission(
6323 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6324 != PackageManager.PERMISSION_GRANTED) {
6325 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6326 < Build.VERSION_CODES.FROYO) {
6327 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6328 + Binder.getCallingUid());
6329 return;
6330 }
6331 mContext.enforceCallingOrSelfPermission(
6332 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6333 }
6334
6335 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6337 mSettings.mPreferredActivities.addFilter(
6338 new PreferredActivity(filter, match, set, activity));
6339 mSettings.writeLP();
6340 }
6341 }
6342
Satish Sampath8dbe6122009-06-02 23:35:54 +01006343 public void replacePreferredActivity(IntentFilter filter, int match,
6344 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006345 if (filter.countActions() != 1) {
6346 throw new IllegalArgumentException(
6347 "replacePreferredActivity expects filter to have only 1 action.");
6348 }
6349 if (filter.countCategories() != 1) {
6350 throw new IllegalArgumentException(
6351 "replacePreferredActivity expects filter to have only 1 category.");
6352 }
6353 if (filter.countDataAuthorities() != 0
6354 || filter.countDataPaths() != 0
6355 || filter.countDataSchemes() != 0
6356 || filter.countDataTypes() != 0) {
6357 throw new IllegalArgumentException(
6358 "replacePreferredActivity expects filter to have no data authorities, " +
6359 "paths, schemes or types.");
6360 }
6361 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006362 if (mContext.checkCallingOrSelfPermission(
6363 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6364 != PackageManager.PERMISSION_GRANTED) {
6365 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6366 < Build.VERSION_CODES.FROYO) {
6367 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6368 + Binder.getCallingUid());
6369 return;
6370 }
6371 mContext.enforceCallingOrSelfPermission(
6372 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6373 }
6374
Satish Sampath8dbe6122009-06-02 23:35:54 +01006375 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6376 String action = filter.getAction(0);
6377 String category = filter.getCategory(0);
6378 while (it.hasNext()) {
6379 PreferredActivity pa = it.next();
6380 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6381 it.remove();
6382 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6383 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6384 }
6385 }
6386 addPreferredActivity(filter, match, set, activity);
6387 }
6388 }
6389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006392 int uid = Binder.getCallingUid();
6393 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006394 if (pkg == null || pkg.applicationInfo.uid != uid) {
6395 if (mContext.checkCallingOrSelfPermission(
6396 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6397 != PackageManager.PERMISSION_GRANTED) {
6398 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6399 < Build.VERSION_CODES.FROYO) {
6400 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6401 + Binder.getCallingUid());
6402 return;
6403 }
6404 mContext.enforceCallingOrSelfPermission(
6405 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6406 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006407 }
6408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006409 if (clearPackagePreferredActivitiesLP(packageName)) {
6410 mSettings.writeLP();
6411 }
6412 }
6413 }
6414
6415 boolean clearPackagePreferredActivitiesLP(String packageName) {
6416 boolean changed = false;
6417 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6418 while (it.hasNext()) {
6419 PreferredActivity pa = it.next();
6420 if (pa.mActivity.getPackageName().equals(packageName)) {
6421 it.remove();
6422 changed = true;
6423 }
6424 }
6425 return changed;
6426 }
6427
6428 public int getPreferredActivities(List<IntentFilter> outFilters,
6429 List<ComponentName> outActivities, String packageName) {
6430
6431 int num = 0;
6432 synchronized (mPackages) {
6433 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6434 while (it.hasNext()) {
6435 PreferredActivity pa = it.next();
6436 if (packageName == null
6437 || pa.mActivity.getPackageName().equals(packageName)) {
6438 if (outFilters != null) {
6439 outFilters.add(new IntentFilter(pa));
6440 }
6441 if (outActivities != null) {
6442 outActivities.add(pa.mActivity);
6443 }
6444 }
6445 }
6446 }
6447
6448 return num;
6449 }
6450
6451 public void setApplicationEnabledSetting(String appPackageName,
6452 int newState, int flags) {
6453 setEnabledSetting(appPackageName, null, newState, flags);
6454 }
6455
6456 public void setComponentEnabledSetting(ComponentName componentName,
6457 int newState, int flags) {
6458 setEnabledSetting(componentName.getPackageName(),
6459 componentName.getClassName(), newState, flags);
6460 }
6461
6462 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006463 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006464 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6465 || newState == COMPONENT_ENABLED_STATE_ENABLED
6466 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6467 throw new IllegalArgumentException("Invalid new component state: "
6468 + newState);
6469 }
6470 PackageSetting pkgSetting;
6471 final int uid = Binder.getCallingUid();
6472 final int permission = mContext.checkCallingPermission(
6473 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6474 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006475 boolean sendNow = false;
6476 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006477 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006478 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006479 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006480 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006481 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006482 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006483 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006484 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006485 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006486 }
6487 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006488 "Unknown component: " + packageName
6489 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006490 }
6491 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6492 throw new SecurityException(
6493 "Permission Denial: attempt to change component state from pid="
6494 + Binder.getCallingPid()
6495 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6496 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006497 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006498 // We're dealing with an application/package level state change
6499 pkgSetting.enabled = newState;
6500 } else {
6501 // We're dealing with a component level state change
6502 switch (newState) {
6503 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006504 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006505 break;
6506 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006507 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006508 break;
6509 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006510 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006511 break;
6512 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006513 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006514 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006515 }
6516 }
6517 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006518 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006519 components = mPendingBroadcasts.get(packageName);
6520 boolean newPackage = components == null;
6521 if (newPackage) {
6522 components = new ArrayList<String>();
6523 }
6524 if (!components.contains(componentName)) {
6525 components.add(componentName);
6526 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006527 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6528 sendNow = true;
6529 // Purge entry from pending broadcast list if another one exists already
6530 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006531 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006532 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006533 if (newPackage) {
6534 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006535 }
6536 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6537 // Schedule a message
6538 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6539 }
6540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006541 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006543 long callingId = Binder.clearCallingIdentity();
6544 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006545 if (sendNow) {
6546 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006547 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006548 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006549 } finally {
6550 Binder.restoreCallingIdentity(callingId);
6551 }
6552 }
6553
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006554 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006555 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6556 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6557 + " components=" + componentNames);
6558 Bundle extras = new Bundle(4);
6559 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6560 String nameList[] = new String[componentNames.size()];
6561 componentNames.toArray(nameList);
6562 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006563 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6564 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006565 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006566 }
6567
Jacek Surazski65e13172009-04-28 15:26:38 +02006568 public String getInstallerPackageName(String packageName) {
6569 synchronized (mPackages) {
6570 PackageSetting pkg = mSettings.mPackages.get(packageName);
6571 if (pkg == null) {
6572 throw new IllegalArgumentException("Unknown package: " + packageName);
6573 }
6574 return pkg.installerPackageName;
6575 }
6576 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006578 public int getApplicationEnabledSetting(String appPackageName) {
6579 synchronized (mPackages) {
6580 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6581 if (pkg == null) {
6582 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6583 }
6584 return pkg.enabled;
6585 }
6586 }
6587
6588 public int getComponentEnabledSetting(ComponentName componentName) {
6589 synchronized (mPackages) {
6590 final String packageNameStr = componentName.getPackageName();
6591 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6592 if (pkg == null) {
6593 throw new IllegalArgumentException("Unknown component: " + componentName);
6594 }
6595 final String classNameStr = componentName.getClassName();
6596 return pkg.currentEnabledStateLP(classNameStr);
6597 }
6598 }
6599
6600 public void enterSafeMode() {
6601 if (!mSystemReady) {
6602 mSafeMode = true;
6603 }
6604 }
6605
6606 public void systemReady() {
6607 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006608
6609 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006610 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006611 mContext.getContentResolver(),
6612 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006613 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006614 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006615 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006617 }
6618
6619 public boolean isSafeMode() {
6620 return mSafeMode;
6621 }
6622
6623 public boolean hasSystemUidErrors() {
6624 return mHasSystemUidErrors;
6625 }
6626
6627 static String arrayToString(int[] array) {
6628 StringBuffer buf = new StringBuffer(128);
6629 buf.append('[');
6630 if (array != null) {
6631 for (int i=0; i<array.length; i++) {
6632 if (i > 0) buf.append(", ");
6633 buf.append(array[i]);
6634 }
6635 }
6636 buf.append(']');
6637 return buf.toString();
6638 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006640 @Override
6641 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6642 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6643 != PackageManager.PERMISSION_GRANTED) {
6644 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6645 + Binder.getCallingPid()
6646 + ", uid=" + Binder.getCallingUid()
6647 + " without permission "
6648 + android.Manifest.permission.DUMP);
6649 return;
6650 }
6651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006652 synchronized (mPackages) {
6653 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006654 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006655 pw.println(" ");
6656 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006657 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 pw.println(" ");
6659 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006660 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006661 pw.println(" ");
6662 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006663 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006664 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006665 pw.println("Permissions:");
6666 {
6667 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006668 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6669 pw.print(Integer.toHexString(System.identityHashCode(p)));
6670 pw.println("):");
6671 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6672 pw.print(" uid="); pw.print(p.uid);
6673 pw.print(" gids="); pw.print(arrayToString(p.gids));
6674 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006675 }
6676 }
6677 pw.println(" ");
6678 pw.println("Packages:");
6679 {
6680 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006681 pw.print(" Package [");
6682 pw.print(ps.realName != null ? ps.realName : ps.name);
6683 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006684 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6685 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006686 if (ps.realName != null) {
6687 pw.print(" compat name="); pw.println(ps.name);
6688 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006689 pw.print(" userId="); pw.print(ps.userId);
6690 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6691 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6692 pw.print(" pkg="); pw.println(ps.pkg);
6693 pw.print(" codePath="); pw.println(ps.codePathString);
6694 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006695 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006696 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006697 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006698 pw.print(" supportsScreens=[");
6699 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006700 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006701 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006702 if (!first) pw.print(", ");
6703 first = false;
6704 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006705 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006706 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006707 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006708 if (!first) pw.print(", ");
6709 first = false;
6710 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006711 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006712 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006713 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006714 if (!first) pw.print(", ");
6715 first = false;
6716 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006717 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006718 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006719 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006720 if (!first) pw.print(", ");
6721 first = false;
6722 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006723 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006724 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006725 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6726 if (!first) pw.print(", ");
6727 first = false;
6728 pw.print("anyDensity");
6729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006730 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006731 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006732 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6733 pw.print(" signatures="); pw.println(ps.signatures);
6734 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6735 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6736 pw.print(" installStatus="); pw.print(ps.installStatus);
6737 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006738 if (ps.disabledComponents.size() > 0) {
6739 pw.println(" disabledComponents:");
6740 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006741 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006742 }
6743 }
6744 if (ps.enabledComponents.size() > 0) {
6745 pw.println(" enabledComponents:");
6746 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006747 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006748 }
6749 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006750 if (ps.grantedPermissions.size() > 0) {
6751 pw.println(" grantedPermissions:");
6752 for (String s : ps.grantedPermissions) {
6753 pw.print(" "); pw.println(s);
6754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006755 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006756 if (ps.loadedPermissions.size() > 0) {
6757 pw.println(" loadedPermissions:");
6758 for (String s : ps.loadedPermissions) {
6759 pw.print(" "); pw.println(s);
6760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006761 }
6762 }
6763 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006764 if (mSettings.mRenamedPackages.size() > 0) {
6765 pw.println(" ");
6766 pw.println("Renamed packages:");
6767 for (HashMap.Entry<String, String> e
6768 : mSettings.mRenamedPackages.entrySet()) {
6769 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6770 pw.println(e.getValue());
6771 }
6772 }
6773 if (mSettings.mDisabledSysPackages.size() > 0) {
6774 pw.println(" ");
6775 pw.println("Hidden system packages:");
6776 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
6777 pw.print(" Package [");
6778 pw.print(ps.realName != null ? ps.realName : ps.name);
6779 pw.print("] (");
6780 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6781 pw.println("):");
6782 if (ps.realName != null) {
6783 pw.print(" compat name="); pw.println(ps.name);
6784 }
6785 pw.print(" userId="); pw.println(ps.userId);
6786 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6787 pw.print(" codePath="); pw.println(ps.codePathString);
6788 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
6789 }
6790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006791 pw.println(" ");
6792 pw.println("Shared Users:");
6793 {
6794 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006795 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6796 pw.print(Integer.toHexString(System.identityHashCode(su)));
6797 pw.println("):");
6798 pw.print(" userId="); pw.print(su.userId);
6799 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006800 pw.println(" grantedPermissions:");
6801 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006802 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006803 }
6804 pw.println(" loadedPermissions:");
6805 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006806 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006807 }
6808 }
6809 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006811 pw.println(" ");
6812 pw.println("Settings parse messages:");
6813 pw.println(mSettings.mReadMessages.toString());
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006814
6815 pw.println(" ");
6816 pw.println("Package warning messages:");
6817 File fname = getSettingsProblemFile();
6818 FileInputStream in;
6819 try {
6820 in = new FileInputStream(fname);
6821 int avail = in.available();
6822 byte[] data = new byte[avail];
6823 in.read(data);
6824 pw.println(new String(data));
6825 } catch (FileNotFoundException e) {
6826 } catch (IOException e) {
6827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006828 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006829
6830 synchronized (mProviders) {
6831 pw.println(" ");
6832 pw.println("Registered ContentProviders:");
6833 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006834 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006835 pw.println(p.toString());
6836 }
6837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006838 }
6839
6840 static final class BasePermission {
6841 final static int TYPE_NORMAL = 0;
6842 final static int TYPE_BUILTIN = 1;
6843 final static int TYPE_DYNAMIC = 2;
6844
6845 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006846 String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006847 final int type;
6848 PackageParser.Permission perm;
6849 PermissionInfo pendingInfo;
6850 int uid;
6851 int[] gids;
6852
6853 BasePermission(String _name, String _sourcePackage, int _type) {
6854 name = _name;
6855 sourcePackage = _sourcePackage;
6856 type = _type;
6857 }
6858 }
6859
6860 static class PackageSignatures {
6861 private Signature[] mSignatures;
6862
6863 PackageSignatures(Signature[] sigs) {
6864 assignSignatures(sigs);
6865 }
6866
6867 PackageSignatures() {
6868 }
6869
6870 void writeXml(XmlSerializer serializer, String tagName,
6871 ArrayList<Signature> pastSignatures) throws IOException {
6872 if (mSignatures == null) {
6873 return;
6874 }
6875 serializer.startTag(null, tagName);
6876 serializer.attribute(null, "count",
6877 Integer.toString(mSignatures.length));
6878 for (int i=0; i<mSignatures.length; i++) {
6879 serializer.startTag(null, "cert");
6880 final Signature sig = mSignatures[i];
6881 final int sigHash = sig.hashCode();
6882 final int numPast = pastSignatures.size();
6883 int j;
6884 for (j=0; j<numPast; j++) {
6885 Signature pastSig = pastSignatures.get(j);
6886 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
6887 serializer.attribute(null, "index", Integer.toString(j));
6888 break;
6889 }
6890 }
6891 if (j >= numPast) {
6892 pastSignatures.add(sig);
6893 serializer.attribute(null, "index", Integer.toString(numPast));
6894 serializer.attribute(null, "key", sig.toCharsString());
6895 }
6896 serializer.endTag(null, "cert");
6897 }
6898 serializer.endTag(null, tagName);
6899 }
6900
6901 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
6902 throws IOException, XmlPullParserException {
6903 String countStr = parser.getAttributeValue(null, "count");
6904 if (countStr == null) {
6905 reportSettingsProblem(Log.WARN,
6906 "Error in package manager settings: <signatures> has"
6907 + " no count at " + parser.getPositionDescription());
6908 XmlUtils.skipCurrentTag(parser);
6909 }
6910 final int count = Integer.parseInt(countStr);
6911 mSignatures = new Signature[count];
6912 int pos = 0;
6913
6914 int outerDepth = parser.getDepth();
6915 int type;
6916 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6917 && (type != XmlPullParser.END_TAG
6918 || parser.getDepth() > outerDepth)) {
6919 if (type == XmlPullParser.END_TAG
6920 || type == XmlPullParser.TEXT) {
6921 continue;
6922 }
6923
6924 String tagName = parser.getName();
6925 if (tagName.equals("cert")) {
6926 if (pos < count) {
6927 String index = parser.getAttributeValue(null, "index");
6928 if (index != null) {
6929 try {
6930 int idx = Integer.parseInt(index);
6931 String key = parser.getAttributeValue(null, "key");
6932 if (key == null) {
6933 if (idx >= 0 && idx < pastSignatures.size()) {
6934 Signature sig = pastSignatures.get(idx);
6935 if (sig != null) {
6936 mSignatures[pos] = pastSignatures.get(idx);
6937 pos++;
6938 } else {
6939 reportSettingsProblem(Log.WARN,
6940 "Error in package manager settings: <cert> "
6941 + "index " + index + " is not defined at "
6942 + parser.getPositionDescription());
6943 }
6944 } else {
6945 reportSettingsProblem(Log.WARN,
6946 "Error in package manager settings: <cert> "
6947 + "index " + index + " is out of bounds at "
6948 + parser.getPositionDescription());
6949 }
6950 } else {
6951 while (pastSignatures.size() <= idx) {
6952 pastSignatures.add(null);
6953 }
6954 Signature sig = new Signature(key);
6955 pastSignatures.set(idx, sig);
6956 mSignatures[pos] = sig;
6957 pos++;
6958 }
6959 } catch (NumberFormatException e) {
6960 reportSettingsProblem(Log.WARN,
6961 "Error in package manager settings: <cert> "
6962 + "index " + index + " is not a number at "
6963 + parser.getPositionDescription());
6964 }
6965 } else {
6966 reportSettingsProblem(Log.WARN,
6967 "Error in package manager settings: <cert> has"
6968 + " no index at " + parser.getPositionDescription());
6969 }
6970 } else {
6971 reportSettingsProblem(Log.WARN,
6972 "Error in package manager settings: too "
6973 + "many <cert> tags, expected " + count
6974 + " at " + parser.getPositionDescription());
6975 }
6976 } else {
6977 reportSettingsProblem(Log.WARN,
6978 "Unknown element under <cert>: "
6979 + parser.getName());
6980 }
6981 XmlUtils.skipCurrentTag(parser);
6982 }
6983
6984 if (pos < count) {
6985 // Should never happen -- there is an error in the written
6986 // settings -- but if it does we don't want to generate
6987 // a bad array.
6988 Signature[] newSigs = new Signature[pos];
6989 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6990 mSignatures = newSigs;
6991 }
6992 }
6993
6994 /**
6995 * If any of the given 'sigs' is contained in the existing signatures,
6996 * then completely replace the current signatures with the ones in
6997 * 'sigs'. This is used for updating an existing package to a newly
6998 * installed version.
6999 */
7000 boolean updateSignatures(Signature[] sigs, boolean update) {
7001 if (mSignatures == null) {
7002 if (update) {
7003 assignSignatures(sigs);
7004 }
7005 return true;
7006 }
7007 if (sigs == null) {
7008 return false;
7009 }
7010
7011 for (int i=0; i<sigs.length; i++) {
7012 Signature sig = sigs[i];
7013 for (int j=0; j<mSignatures.length; j++) {
7014 if (mSignatures[j].equals(sig)) {
7015 if (update) {
7016 assignSignatures(sigs);
7017 }
7018 return true;
7019 }
7020 }
7021 }
7022 return false;
7023 }
7024
7025 /**
7026 * If any of the given 'sigs' is contained in the existing signatures,
7027 * then add in any new signatures found in 'sigs'. This is used for
7028 * including a new package into an existing shared user id.
7029 */
7030 boolean mergeSignatures(Signature[] sigs, boolean update) {
7031 if (mSignatures == null) {
7032 if (update) {
7033 assignSignatures(sigs);
7034 }
7035 return true;
7036 }
7037 if (sigs == null) {
7038 return false;
7039 }
7040
7041 Signature[] added = null;
7042 int addedCount = 0;
7043 boolean haveMatch = false;
7044 for (int i=0; i<sigs.length; i++) {
7045 Signature sig = sigs[i];
7046 boolean found = false;
7047 for (int j=0; j<mSignatures.length; j++) {
7048 if (mSignatures[j].equals(sig)) {
7049 found = true;
7050 haveMatch = true;
7051 break;
7052 }
7053 }
7054
7055 if (!found) {
7056 if (added == null) {
7057 added = new Signature[sigs.length];
7058 }
7059 added[i] = sig;
7060 addedCount++;
7061 }
7062 }
7063
7064 if (!haveMatch) {
7065 // Nothing matched -- reject the new signatures.
7066 return false;
7067 }
7068 if (added == null) {
7069 // Completely matched -- nothing else to do.
7070 return true;
7071 }
7072
7073 // Add additional signatures in.
7074 if (update) {
7075 Signature[] total = new Signature[addedCount+mSignatures.length];
7076 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
7077 int j = mSignatures.length;
7078 for (int i=0; i<added.length; i++) {
7079 if (added[i] != null) {
7080 total[j] = added[i];
7081 j++;
7082 }
7083 }
7084 mSignatures = total;
7085 }
7086 return true;
7087 }
7088
7089 private void assignSignatures(Signature[] sigs) {
7090 if (sigs == null) {
7091 mSignatures = null;
7092 return;
7093 }
7094 mSignatures = new Signature[sigs.length];
7095 for (int i=0; i<sigs.length; i++) {
7096 mSignatures[i] = sigs[i];
7097 }
7098 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007100 @Override
7101 public String toString() {
7102 StringBuffer buf = new StringBuffer(128);
7103 buf.append("PackageSignatures{");
7104 buf.append(Integer.toHexString(System.identityHashCode(this)));
7105 buf.append(" [");
7106 if (mSignatures != null) {
7107 for (int i=0; i<mSignatures.length; i++) {
7108 if (i > 0) buf.append(", ");
7109 buf.append(Integer.toHexString(
7110 System.identityHashCode(mSignatures[i])));
7111 }
7112 }
7113 buf.append("]}");
7114 return buf.toString();
7115 }
7116 }
7117
7118 static class PreferredActivity extends IntentFilter {
7119 final int mMatch;
7120 final String[] mSetPackages;
7121 final String[] mSetClasses;
7122 final String[] mSetComponents;
7123 final ComponentName mActivity;
7124 final String mShortActivity;
7125 String mParseError;
7126
7127 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7128 ComponentName activity) {
7129 super(filter);
7130 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7131 mActivity = activity;
7132 mShortActivity = activity.flattenToShortString();
7133 mParseError = null;
7134 if (set != null) {
7135 final int N = set.length;
7136 String[] myPackages = new String[N];
7137 String[] myClasses = new String[N];
7138 String[] myComponents = new String[N];
7139 for (int i=0; i<N; i++) {
7140 ComponentName cn = set[i];
7141 if (cn == null) {
7142 mSetPackages = null;
7143 mSetClasses = null;
7144 mSetComponents = null;
7145 return;
7146 }
7147 myPackages[i] = cn.getPackageName().intern();
7148 myClasses[i] = cn.getClassName().intern();
7149 myComponents[i] = cn.flattenToShortString().intern();
7150 }
7151 mSetPackages = myPackages;
7152 mSetClasses = myClasses;
7153 mSetComponents = myComponents;
7154 } else {
7155 mSetPackages = null;
7156 mSetClasses = null;
7157 mSetComponents = null;
7158 }
7159 }
7160
7161 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7162 IOException {
7163 mShortActivity = parser.getAttributeValue(null, "name");
7164 mActivity = ComponentName.unflattenFromString(mShortActivity);
7165 if (mActivity == null) {
7166 mParseError = "Bad activity name " + mShortActivity;
7167 }
7168 String matchStr = parser.getAttributeValue(null, "match");
7169 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7170 String setCountStr = parser.getAttributeValue(null, "set");
7171 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7172
7173 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7174 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7175 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7176
7177 int setPos = 0;
7178
7179 int outerDepth = parser.getDepth();
7180 int type;
7181 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7182 && (type != XmlPullParser.END_TAG
7183 || parser.getDepth() > outerDepth)) {
7184 if (type == XmlPullParser.END_TAG
7185 || type == XmlPullParser.TEXT) {
7186 continue;
7187 }
7188
7189 String tagName = parser.getName();
7190 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7191 // + parser.getDepth() + " tag=" + tagName);
7192 if (tagName.equals("set")) {
7193 String name = parser.getAttributeValue(null, "name");
7194 if (name == null) {
7195 if (mParseError == null) {
7196 mParseError = "No name in set tag in preferred activity "
7197 + mShortActivity;
7198 }
7199 } else if (setPos >= setCount) {
7200 if (mParseError == null) {
7201 mParseError = "Too many set tags in preferred activity "
7202 + mShortActivity;
7203 }
7204 } else {
7205 ComponentName cn = ComponentName.unflattenFromString(name);
7206 if (cn == null) {
7207 if (mParseError == null) {
7208 mParseError = "Bad set name " + name + " in preferred activity "
7209 + mShortActivity;
7210 }
7211 } else {
7212 myPackages[setPos] = cn.getPackageName();
7213 myClasses[setPos] = cn.getClassName();
7214 myComponents[setPos] = name;
7215 setPos++;
7216 }
7217 }
7218 XmlUtils.skipCurrentTag(parser);
7219 } else if (tagName.equals("filter")) {
7220 //Log.i(TAG, "Starting to parse filter...");
7221 readFromXml(parser);
7222 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7223 // + parser.getDepth() + " tag=" + parser.getName());
7224 } else {
7225 reportSettingsProblem(Log.WARN,
7226 "Unknown element under <preferred-activities>: "
7227 + parser.getName());
7228 XmlUtils.skipCurrentTag(parser);
7229 }
7230 }
7231
7232 if (setPos != setCount) {
7233 if (mParseError == null) {
7234 mParseError = "Not enough set tags (expected " + setCount
7235 + " but found " + setPos + ") in " + mShortActivity;
7236 }
7237 }
7238
7239 mSetPackages = myPackages;
7240 mSetClasses = myClasses;
7241 mSetComponents = myComponents;
7242 }
7243
7244 public void writeToXml(XmlSerializer serializer) throws IOException {
7245 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7246 serializer.attribute(null, "name", mShortActivity);
7247 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7248 serializer.attribute(null, "set", Integer.toString(NS));
7249 for (int s=0; s<NS; s++) {
7250 serializer.startTag(null, "set");
7251 serializer.attribute(null, "name", mSetComponents[s]);
7252 serializer.endTag(null, "set");
7253 }
7254 serializer.startTag(null, "filter");
7255 super.writeToXml(serializer);
7256 serializer.endTag(null, "filter");
7257 }
7258
7259 boolean sameSet(List<ResolveInfo> query, int priority) {
7260 if (mSetPackages == null) return false;
7261 final int NQ = query.size();
7262 final int NS = mSetPackages.length;
7263 int numMatch = 0;
7264 for (int i=0; i<NQ; i++) {
7265 ResolveInfo ri = query.get(i);
7266 if (ri.priority != priority) continue;
7267 ActivityInfo ai = ri.activityInfo;
7268 boolean good = false;
7269 for (int j=0; j<NS; j++) {
7270 if (mSetPackages[j].equals(ai.packageName)
7271 && mSetClasses[j].equals(ai.name)) {
7272 numMatch++;
7273 good = true;
7274 break;
7275 }
7276 }
7277 if (!good) return false;
7278 }
7279 return numMatch == NS;
7280 }
7281 }
7282
7283 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007284 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007286 HashSet<String> grantedPermissions = new HashSet<String>();
7287 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007289 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007291 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007292 setFlags(pkgFlags);
7293 }
7294
7295 void setFlags(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007296 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007297 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08007298 (pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) |
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08007299 (pkgFlags & ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007300 }
7301 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007303 /**
7304 * Settings base class for pending and resolved classes.
7305 */
7306 static class PackageSettingBase extends GrantedPermissions {
7307 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007308 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007309 File codePath;
7310 String codePathString;
7311 File resourcePath;
7312 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007313 private long timeStamp;
7314 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007315 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007316
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007317 boolean uidError;
7318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007319 PackageSignatures signatures = new PackageSignatures();
7320
7321 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007323 /* Explicitly disabled components */
7324 HashSet<String> disabledComponents = new HashSet<String>(0);
7325 /* Explicitly enabled components */
7326 HashSet<String> enabledComponents = new HashSet<String>(0);
7327 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7328 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007329
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007330 PackageSettingBase origPackage;
7331
Jacek Surazski65e13172009-04-28 15:26:38 +02007332 /* package name of the app that installed this package */
7333 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007334
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007335 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007336 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007337 super(pkgFlags);
7338 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007339 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007340 init(codePath, resourcePath, pVersionCode);
7341 }
7342
7343 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007344 this.codePath = codePath;
7345 this.codePathString = codePath.toString();
7346 this.resourcePath = resourcePath;
7347 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007348 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007349 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007350
Jacek Surazski65e13172009-04-28 15:26:38 +02007351 public void setInstallerPackageName(String packageName) {
7352 installerPackageName = packageName;
7353 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007354
Jacek Surazski65e13172009-04-28 15:26:38 +02007355 String getInstallerPackageName() {
7356 return installerPackageName;
7357 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007359 public void setInstallStatus(int newStatus) {
7360 installStatus = newStatus;
7361 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007363 public int getInstallStatus() {
7364 return installStatus;
7365 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007367 public void setTimeStamp(long newStamp) {
7368 if (newStamp != timeStamp) {
7369 timeStamp = newStamp;
7370 timeStampString = Long.toString(newStamp);
7371 }
7372 }
7373
7374 public void setTimeStamp(long newStamp, String newStampStr) {
7375 timeStamp = newStamp;
7376 timeStampString = newStampStr;
7377 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007379 public long getTimeStamp() {
7380 return timeStamp;
7381 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007383 public String getTimeStampStr() {
7384 return timeStampString;
7385 }
7386
7387 public void copyFrom(PackageSettingBase base) {
7388 grantedPermissions = base.grantedPermissions;
7389 gids = base.gids;
7390 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007392 timeStamp = base.timeStamp;
7393 timeStampString = base.timeStampString;
7394 signatures = base.signatures;
7395 permissionsFixed = base.permissionsFixed;
7396 disabledComponents = base.disabledComponents;
7397 enabledComponents = base.enabledComponents;
7398 enabled = base.enabled;
7399 installStatus = base.installStatus;
7400 }
7401
7402 void enableComponentLP(String componentClassName) {
7403 disabledComponents.remove(componentClassName);
7404 enabledComponents.add(componentClassName);
7405 }
7406
7407 void disableComponentLP(String componentClassName) {
7408 enabledComponents.remove(componentClassName);
7409 disabledComponents.add(componentClassName);
7410 }
7411
7412 void restoreComponentLP(String componentClassName) {
7413 enabledComponents.remove(componentClassName);
7414 disabledComponents.remove(componentClassName);
7415 }
7416
7417 int currentEnabledStateLP(String componentName) {
7418 if (enabledComponents.contains(componentName)) {
7419 return COMPONENT_ENABLED_STATE_ENABLED;
7420 } else if (disabledComponents.contains(componentName)) {
7421 return COMPONENT_ENABLED_STATE_DISABLED;
7422 } else {
7423 return COMPONENT_ENABLED_STATE_DEFAULT;
7424 }
7425 }
7426 }
7427
7428 /**
7429 * Settings data for a particular package we know about.
7430 */
7431 static final class PackageSetting extends PackageSettingBase {
7432 int userId;
7433 PackageParser.Package pkg;
7434 SharedUserSetting sharedUser;
7435
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007436 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007437 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007438 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007439 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007441 @Override
7442 public String toString() {
7443 return "PackageSetting{"
7444 + Integer.toHexString(System.identityHashCode(this))
7445 + " " + name + "/" + userId + "}";
7446 }
7447 }
7448
7449 /**
7450 * Settings data for a particular shared user ID we know about.
7451 */
7452 static final class SharedUserSetting extends GrantedPermissions {
7453 final String name;
7454 int userId;
7455 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7456 final PackageSignatures signatures = new PackageSignatures();
7457
7458 SharedUserSetting(String _name, int _pkgFlags) {
7459 super(_pkgFlags);
7460 name = _name;
7461 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007463 @Override
7464 public String toString() {
7465 return "SharedUserSetting{"
7466 + Integer.toHexString(System.identityHashCode(this))
7467 + " " + name + "/" + userId + "}";
7468 }
7469 }
7470
7471 /**
7472 * Holds information about dynamic settings.
7473 */
7474 private static final class Settings {
7475 private final File mSettingsFilename;
7476 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007477 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007478 private final HashMap<String, PackageSetting> mPackages =
7479 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007480 // List of replaced system applications
7481 final HashMap<String, PackageSetting> mDisabledSysPackages =
7482 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007484 // The user's preferred activities associated with particular intent
7485 // filters.
7486 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7487 new IntentResolver<PreferredActivity, PreferredActivity>() {
7488 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007489 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007490 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007491 out.print(prefix); out.print(
7492 Integer.toHexString(System.identityHashCode(filter)));
7493 out.print(' ');
7494 out.print(filter.mActivity.flattenToShortString());
7495 out.print(" match=0x");
7496 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007497 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007498 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007499 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007500 out.print(prefix); out.print(" ");
7501 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007502 }
7503 }
7504 }
7505 };
7506 private final HashMap<String, SharedUserSetting> mSharedUsers =
7507 new HashMap<String, SharedUserSetting>();
7508 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7509 private final SparseArray<Object> mOtherUserIds =
7510 new SparseArray<Object>();
7511
7512 // For reading/writing settings file.
7513 private final ArrayList<Signature> mPastSignatures =
7514 new ArrayList<Signature>();
7515
7516 // Mapping from permission names to info about them.
7517 final HashMap<String, BasePermission> mPermissions =
7518 new HashMap<String, BasePermission>();
7519
7520 // Mapping from permission tree names to info about them.
7521 final HashMap<String, BasePermission> mPermissionTrees =
7522 new HashMap<String, BasePermission>();
7523
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007524 // Packages that have been uninstalled and still need their external
7525 // storage data deleted.
7526 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7527
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007528 // Packages that have been renamed since they were first installed.
7529 // Keys are the new names of the packages, values are the original
7530 // names. The packages appear everwhere else under their original
7531 // names.
7532 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007534 private final StringBuilder mReadMessages = new StringBuilder();
7535
7536 private static final class PendingPackage extends PackageSettingBase {
7537 final int sharedId;
7538
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007539 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007540 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007541 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007542 this.sharedId = sharedId;
7543 }
7544 }
7545 private final ArrayList<PendingPackage> mPendingPackages
7546 = new ArrayList<PendingPackage>();
7547
7548 Settings() {
7549 File dataDir = Environment.getDataDirectory();
7550 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007551 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7552 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007553 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007554 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007555 FileUtils.setPermissions(systemDir.toString(),
7556 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7557 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7558 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007559 FileUtils.setPermissions(systemSecureDir.toString(),
7560 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7561 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7562 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007563 mSettingsFilename = new File(systemDir, "packages.xml");
7564 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007565 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007566 }
7567
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007568 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007569 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007570 int pkgFlags, boolean create, boolean add) {
7571 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007572 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007573 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007574 return p;
7575 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007576
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007577 PackageSetting peekPackageLP(String name) {
7578 return mPackages.get(name);
7579 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007580 PackageSetting p = mPackages.get(name);
7581 if (p != null && p.codePath.getPath().equals(codePath)) {
7582 return p;
7583 }
7584 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007585 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007586 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007588 void setInstallStatus(String pkgName, int status) {
7589 PackageSetting p = mPackages.get(pkgName);
7590 if(p != null) {
7591 if(p.getInstallStatus() != status) {
7592 p.setInstallStatus(status);
7593 }
7594 }
7595 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007596
Jacek Surazski65e13172009-04-28 15:26:38 +02007597 void setInstallerPackageName(String pkgName,
7598 String installerPkgName) {
7599 PackageSetting p = mPackages.get(pkgName);
7600 if(p != null) {
7601 p.setInstallerPackageName(installerPkgName);
7602 }
7603 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007604
Jacek Surazski65e13172009-04-28 15:26:38 +02007605 String getInstallerPackageName(String pkgName) {
7606 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007607 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007608 }
7609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007610 int getInstallStatus(String pkgName) {
7611 PackageSetting p = mPackages.get(pkgName);
7612 if(p != null) {
7613 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007615 return -1;
7616 }
7617
7618 SharedUserSetting getSharedUserLP(String name,
7619 int pkgFlags, boolean create) {
7620 SharedUserSetting s = mSharedUsers.get(name);
7621 if (s == null) {
7622 if (!create) {
7623 return null;
7624 }
7625 s = new SharedUserSetting(name, pkgFlags);
7626 if (MULTIPLE_APPLICATION_UIDS) {
7627 s.userId = newUserIdLP(s);
7628 } else {
7629 s.userId = FIRST_APPLICATION_UID;
7630 }
7631 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7632 // < 0 means we couldn't assign a userid; fall out and return
7633 // s, which is currently null
7634 if (s.userId >= 0) {
7635 mSharedUsers.put(name, s);
7636 }
7637 }
7638
7639 return s;
7640 }
7641
7642 int disableSystemPackageLP(String name) {
7643 PackageSetting p = mPackages.get(name);
7644 if(p == null) {
7645 Log.w(TAG, "Package:"+name+" is not an installed package");
7646 return -1;
7647 }
7648 PackageSetting dp = mDisabledSysPackages.get(name);
7649 // always make sure the system package code and resource paths dont change
7650 if(dp == null) {
7651 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7652 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7653 }
7654 mDisabledSysPackages.put(name, p);
7655 }
7656 return removePackageLP(name);
7657 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007659 PackageSetting enableSystemPackageLP(String name) {
7660 PackageSetting p = mDisabledSysPackages.get(name);
7661 if(p == null) {
7662 Log.w(TAG, "Package:"+name+" is not disabled");
7663 return null;
7664 }
7665 // Reset flag in ApplicationInfo object
7666 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7667 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7668 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007669 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007670 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007671 mDisabledSysPackages.remove(name);
7672 return ret;
7673 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007674
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007675 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007676 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007677 PackageSetting p = mPackages.get(name);
7678 if (p != null) {
7679 if (p.userId == uid) {
7680 return p;
7681 }
7682 reportSettingsProblem(Log.ERROR,
7683 "Adding duplicate package, keeping first: " + name);
7684 return null;
7685 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007686 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007687 p.userId = uid;
7688 if (addUserIdLP(uid, p, name)) {
7689 mPackages.put(name, p);
7690 return p;
7691 }
7692 return null;
7693 }
7694
7695 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7696 SharedUserSetting s = mSharedUsers.get(name);
7697 if (s != null) {
7698 if (s.userId == uid) {
7699 return s;
7700 }
7701 reportSettingsProblem(Log.ERROR,
7702 "Adding duplicate shared user, keeping first: " + name);
7703 return null;
7704 }
7705 s = new SharedUserSetting(name, pkgFlags);
7706 s.userId = uid;
7707 if (addUserIdLP(uid, s, name)) {
7708 mSharedUsers.put(name, s);
7709 return s;
7710 }
7711 return null;
7712 }
7713
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007714 // Transfer ownership of permissions from one package to another.
7715 private void transferPermissions(String origPkg, String newPkg) {
7716 // Transfer ownership of permissions to the new package.
7717 for (int i=0; i<2; i++) {
7718 HashMap<String, BasePermission> permissions =
7719 i == 0 ? mPermissionTrees : mPermissions;
7720 for (BasePermission bp : permissions.values()) {
7721 if (origPkg.equals(bp.sourcePackage)) {
7722 if (DEBUG_UPGRADE) Log.v(TAG,
7723 "Moving permission " + bp.name
7724 + " from pkg " + bp.sourcePackage
7725 + " to " + newPkg);
7726 bp.sourcePackage = newPkg;
7727 bp.perm = null;
7728 if (bp.pendingInfo != null) {
7729 bp.sourcePackage = newPkg;
7730 }
7731 bp.uid = 0;
7732 bp.gids = null;
7733 }
7734 }
7735 }
7736 }
7737
7738 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007739 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007740 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007741 PackageSetting p = mPackages.get(name);
7742 if (p != null) {
7743 if (!p.codePath.equals(codePath)) {
7744 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007745 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007746 // This is an updated system app with versions in both system
7747 // and data partition. Just let the most recent version
7748 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007749 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007750 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007751 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007752 // Just a change in the code path is not an issue, but
7753 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007754 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007755 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007756 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007757 }
7758 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007759 reportSettingsProblem(Log.WARN,
7760 "Package " + name + " shared user changed from "
7761 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7762 + " to "
7763 + (sharedUser != null ? sharedUser.name : "<nothing>")
7764 + "; replacing with new");
7765 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007766 } else {
7767 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7768 // If what we are scanning is a system package, then
7769 // make it so, regardless of whether it was previously
7770 // installed only in the data partition.
7771 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007773 }
7774 }
7775 if (p == null) {
7776 // Create a new PackageSettings entry. this can end up here because
7777 // of code path mismatch or user id mismatch of an updated system partition
7778 if (!create) {
7779 return null;
7780 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007781 if (origPackage != null) {
7782 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007783 p = new PackageSetting(origPackage.name, name, codePath,
7784 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007785 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
7786 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08007787 // Note that we will retain the new package's signature so
7788 // that we can keep its data.
7789 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007790 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08007791 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007792 p.sharedUser = origPackage.sharedUser;
7793 p.userId = origPackage.userId;
7794 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007795 mRenamedPackages.put(name, origPackage.name);
7796 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007797 // Update new package state.
7798 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007799 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007800 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007801 p.setTimeStamp(codePath.lastModified());
7802 p.sharedUser = sharedUser;
7803 if (sharedUser != null) {
7804 p.userId = sharedUser.userId;
7805 } else if (MULTIPLE_APPLICATION_UIDS) {
7806 // Clone the setting here for disabled system packages
7807 PackageSetting dis = mDisabledSysPackages.get(name);
7808 if (dis != null) {
7809 // For disabled packages a new setting is created
7810 // from the existing user id. This still has to be
7811 // added to list of user id's
7812 // Copy signatures from previous setting
7813 if (dis.signatures.mSignatures != null) {
7814 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
7815 }
7816 p.userId = dis.userId;
7817 // Clone permissions
7818 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
7819 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
7820 // Clone component info
7821 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
7822 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
7823 // Add new setting to list of user ids
7824 addUserIdLP(p.userId, p, name);
7825 } else {
7826 // Assign new user id
7827 p.userId = newUserIdLP(p);
7828 }
7829 } else {
7830 p.userId = FIRST_APPLICATION_UID;
7831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007832 }
7833 if (p.userId < 0) {
7834 reportSettingsProblem(Log.WARN,
7835 "Package " + name + " could not be assigned a valid uid");
7836 return null;
7837 }
7838 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007839 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007840 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007841 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007842 }
7843 }
7844 return p;
7845 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007846
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007847 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007848 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007849 String codePath = pkg.applicationInfo.sourceDir;
7850 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007851 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007852 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007853 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007854 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007855 p.codePath = new File(codePath);
7856 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007857 }
7858 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007859 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007860 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007861 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007862 p.resourcePath = new File(resourcePath);
7863 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007864 }
7865 // Update version code if needed
7866 if (pkg.mVersionCode != p.versionCode) {
7867 p.versionCode = pkg.mVersionCode;
7868 }
7869 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
7870 }
7871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007872 // Utility method that adds a PackageSetting to mPackages and
7873 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007874 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007875 SharedUserSetting sharedUser) {
7876 mPackages.put(name, p);
7877 if (sharedUser != null) {
7878 if (p.sharedUser != null && p.sharedUser != sharedUser) {
7879 reportSettingsProblem(Log.ERROR,
7880 "Package " + p.name + " was user "
7881 + p.sharedUser + " but is now " + sharedUser
7882 + "; I am not changing its files so it will probably fail!");
7883 p.sharedUser.packages.remove(p);
7884 } else if (p.userId != sharedUser.userId) {
7885 reportSettingsProblem(Log.ERROR,
7886 "Package " + p.name + " was user id " + p.userId
7887 + " but is now user " + sharedUser
7888 + " with id " + sharedUser.userId
7889 + "; I am not changing its files so it will probably fail!");
7890 }
7891
7892 sharedUser.packages.add(p);
7893 p.sharedUser = sharedUser;
7894 p.userId = sharedUser.userId;
7895 }
7896 }
7897
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007898 /*
7899 * Update the shared user setting when a package using
7900 * specifying the shared user id is removed. The gids
7901 * associated with each permission of the deleted package
7902 * are removed from the shared user's gid list only if its
7903 * not in use by other permissions of packages in the
7904 * shared user setting.
7905 */
7906 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007907 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007908 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 return;
7910 }
7911 // No sharedUserId
7912 if (deletedPs.sharedUser == null) {
7913 return;
7914 }
7915 SharedUserSetting sus = deletedPs.sharedUser;
7916 // Update permissions
7917 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
7918 boolean used = false;
7919 if (!sus.grantedPermissions.contains (eachPerm)) {
7920 continue;
7921 }
7922 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007923 if (pkg.pkg != null &&
7924 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
7925 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007926 used = true;
7927 break;
7928 }
7929 }
7930 if (!used) {
7931 // can safely delete this permission from list
7932 sus.grantedPermissions.remove(eachPerm);
7933 sus.loadedPermissions.remove(eachPerm);
7934 }
7935 }
7936 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007937 int newGids[] = globalGids;
7938 for (String eachPerm : sus.grantedPermissions) {
7939 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007940 if (bp != null) {
7941 newGids = appendInts(newGids, bp.gids);
7942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007943 }
7944 sus.gids = newGids;
7945 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007947 private int removePackageLP(String name) {
7948 PackageSetting p = mPackages.get(name);
7949 if (p != null) {
7950 mPackages.remove(name);
7951 if (p.sharedUser != null) {
7952 p.sharedUser.packages.remove(p);
7953 if (p.sharedUser.packages.size() == 0) {
7954 mSharedUsers.remove(p.sharedUser.name);
7955 removeUserIdLP(p.sharedUser.userId);
7956 return p.sharedUser.userId;
7957 }
7958 } else {
7959 removeUserIdLP(p.userId);
7960 return p.userId;
7961 }
7962 }
7963 return -1;
7964 }
7965
7966 private boolean addUserIdLP(int uid, Object obj, Object name) {
7967 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
7968 return false;
7969 }
7970
7971 if (uid >= FIRST_APPLICATION_UID) {
7972 int N = mUserIds.size();
7973 final int index = uid - FIRST_APPLICATION_UID;
7974 while (index >= N) {
7975 mUserIds.add(null);
7976 N++;
7977 }
7978 if (mUserIds.get(index) != null) {
7979 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007980 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007981 + " name=" + name);
7982 return false;
7983 }
7984 mUserIds.set(index, obj);
7985 } else {
7986 if (mOtherUserIds.get(uid) != null) {
7987 reportSettingsProblem(Log.ERROR,
7988 "Adding duplicate shared id: " + uid
7989 + " name=" + name);
7990 return false;
7991 }
7992 mOtherUserIds.put(uid, obj);
7993 }
7994 return true;
7995 }
7996
7997 public Object getUserIdLP(int uid) {
7998 if (uid >= FIRST_APPLICATION_UID) {
7999 int N = mUserIds.size();
8000 final int index = uid - FIRST_APPLICATION_UID;
8001 return index < N ? mUserIds.get(index) : null;
8002 } else {
8003 return mOtherUserIds.get(uid);
8004 }
8005 }
8006
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008007 private Set<String> findPackagesWithFlag(int flag) {
8008 Set<String> ret = new HashSet<String>();
8009 for (PackageSetting ps : mPackages.values()) {
8010 // Has to match atleast all the flag bits set on flag
8011 if ((ps.pkgFlags & flag) == flag) {
8012 ret.add(ps.name);
8013 }
8014 }
8015 return ret;
8016 }
8017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008018 private void removeUserIdLP(int uid) {
8019 if (uid >= FIRST_APPLICATION_UID) {
8020 int N = mUserIds.size();
8021 final int index = uid - FIRST_APPLICATION_UID;
8022 if (index < N) mUserIds.set(index, null);
8023 } else {
8024 mOtherUserIds.remove(uid);
8025 }
8026 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008028 void writeLP() {
8029 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8030
8031 // Keep the old settings around until we know the new ones have
8032 // been successfully written.
8033 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008034 // Presence of backup settings file indicates that we failed
8035 // to persist settings earlier. So preserve the older
8036 // backup for future reference since the current settings
8037 // might have been corrupted.
8038 if (!mBackupSettingsFilename.exists()) {
8039 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008040 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008041 return;
8042 }
8043 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008044 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008045 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008046 }
8047
8048 mPastSignatures.clear();
8049
8050 try {
8051 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8052
8053 //XmlSerializer serializer = XmlUtils.serializerInstance();
8054 XmlSerializer serializer = new FastXmlSerializer();
8055 serializer.setOutput(str, "utf-8");
8056 serializer.startDocument(null, true);
8057 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8058
8059 serializer.startTag(null, "packages");
8060
8061 serializer.startTag(null, "permission-trees");
8062 for (BasePermission bp : mPermissionTrees.values()) {
8063 writePermission(serializer, bp);
8064 }
8065 serializer.endTag(null, "permission-trees");
8066
8067 serializer.startTag(null, "permissions");
8068 for (BasePermission bp : mPermissions.values()) {
8069 writePermission(serializer, bp);
8070 }
8071 serializer.endTag(null, "permissions");
8072
8073 for (PackageSetting pkg : mPackages.values()) {
8074 writePackage(serializer, pkg);
8075 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008077 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8078 writeDisabledSysPackage(serializer, pkg);
8079 }
8080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008081 serializer.startTag(null, "preferred-activities");
8082 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8083 serializer.startTag(null, "item");
8084 pa.writeToXml(serializer);
8085 serializer.endTag(null, "item");
8086 }
8087 serializer.endTag(null, "preferred-activities");
8088
8089 for (SharedUserSetting usr : mSharedUsers.values()) {
8090 serializer.startTag(null, "shared-user");
8091 serializer.attribute(null, "name", usr.name);
8092 serializer.attribute(null, "userId",
8093 Integer.toString(usr.userId));
8094 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8095 serializer.startTag(null, "perms");
8096 for (String name : usr.grantedPermissions) {
8097 serializer.startTag(null, "item");
8098 serializer.attribute(null, "name", name);
8099 serializer.endTag(null, "item");
8100 }
8101 serializer.endTag(null, "perms");
8102 serializer.endTag(null, "shared-user");
8103 }
8104
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008105 if (mPackagesToBeCleaned.size() > 0) {
8106 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8107 serializer.startTag(null, "cleaning-package");
8108 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8109 serializer.endTag(null, "cleaning-package");
8110 }
8111 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008112
8113 if (mRenamedPackages.size() > 0) {
8114 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8115 serializer.startTag(null, "renamed-package");
8116 serializer.attribute(null, "new", e.getKey());
8117 serializer.attribute(null, "old", e.getValue());
8118 serializer.endTag(null, "renamed-package");
8119 }
8120 }
8121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008122 serializer.endTag(null, "packages");
8123
8124 serializer.endDocument();
8125
8126 str.flush();
8127 str.close();
8128
8129 // New settings successfully written, old ones are no longer
8130 // needed.
8131 mBackupSettingsFilename.delete();
8132 FileUtils.setPermissions(mSettingsFilename.toString(),
8133 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8134 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8135 |FileUtils.S_IROTH,
8136 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008137
8138 // Write package list file now, use a JournaledFile.
8139 //
8140 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8141 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8142
8143 str = new FileOutputStream(journal.chooseForWrite());
8144 try {
8145 StringBuilder sb = new StringBuilder();
8146 for (PackageSetting pkg : mPackages.values()) {
8147 ApplicationInfo ai = pkg.pkg.applicationInfo;
8148 String dataPath = ai.dataDir;
8149 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8150
8151 // Avoid any application that has a space in its path
8152 // or that is handled by the system.
8153 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8154 continue;
8155
8156 // we store on each line the following information for now:
8157 //
8158 // pkgName - package name
8159 // userId - application-specific user id
8160 // debugFlag - 0 or 1 if the package is debuggable.
8161 // dataPath - path to package's data path
8162 //
8163 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8164 //
8165 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8166 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8167 // system/core/run-as/run-as.c
8168 //
8169 sb.setLength(0);
8170 sb.append(ai.packageName);
8171 sb.append(" ");
8172 sb.append((int)ai.uid);
8173 sb.append(isDebug ? " 1 " : " 0 ");
8174 sb.append(dataPath);
8175 sb.append("\n");
8176 str.write(sb.toString().getBytes());
8177 }
8178 str.flush();
8179 str.close();
8180 journal.commit();
8181 }
8182 catch (Exception e) {
8183 journal.rollback();
8184 }
8185
8186 FileUtils.setPermissions(mPackageListFilename.toString(),
8187 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8188 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8189 |FileUtils.S_IROTH,
8190 -1, -1);
8191
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008192 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008193
8194 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008195 Slog.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008196 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008197 Slog.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008198 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008199 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008200 if (mSettingsFilename.exists()) {
8201 if (!mSettingsFilename.delete()) {
8202 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8203 }
8204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008205 //Debug.stopMethodTracing();
8206 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008207
8208 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008209 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008210 serializer.startTag(null, "updated-package");
8211 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008212 if (pkg.realName != null) {
8213 serializer.attribute(null, "realName", pkg.realName);
8214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008215 serializer.attribute(null, "codePath", pkg.codePathString);
8216 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008217 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008218 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8219 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8220 }
8221 if (pkg.sharedUser == null) {
8222 serializer.attribute(null, "userId",
8223 Integer.toString(pkg.userId));
8224 } else {
8225 serializer.attribute(null, "sharedUserId",
8226 Integer.toString(pkg.userId));
8227 }
8228 serializer.startTag(null, "perms");
8229 if (pkg.sharedUser == null) {
8230 // If this is a shared user, the permissions will
8231 // be written there. We still need to write an
8232 // empty permissions list so permissionsFixed will
8233 // be set.
8234 for (final String name : pkg.grantedPermissions) {
8235 BasePermission bp = mPermissions.get(name);
8236 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
8237 // We only need to write signature or system permissions but this wont
8238 // match the semantics of grantedPermissions. So write all permissions.
8239 serializer.startTag(null, "item");
8240 serializer.attribute(null, "name", name);
8241 serializer.endTag(null, "item");
8242 }
8243 }
8244 }
8245 serializer.endTag(null, "perms");
8246 serializer.endTag(null, "updated-package");
8247 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008248
8249 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008250 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008251 serializer.startTag(null, "package");
8252 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008253 if (pkg.realName != null) {
8254 serializer.attribute(null, "realName", pkg.realName);
8255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008256 serializer.attribute(null, "codePath", pkg.codePathString);
8257 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8258 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8259 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008260 serializer.attribute(null, "flags",
8261 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008262 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008263 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008264 if (pkg.sharedUser == null) {
8265 serializer.attribute(null, "userId",
8266 Integer.toString(pkg.userId));
8267 } else {
8268 serializer.attribute(null, "sharedUserId",
8269 Integer.toString(pkg.userId));
8270 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008271 if (pkg.uidError) {
8272 serializer.attribute(null, "uidError", "true");
8273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008274 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8275 serializer.attribute(null, "enabled",
8276 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8277 ? "true" : "false");
8278 }
8279 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8280 serializer.attribute(null, "installStatus", "false");
8281 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008282 if (pkg.installerPackageName != null) {
8283 serializer.attribute(null, "installer", pkg.installerPackageName);
8284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008285 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8286 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8287 serializer.startTag(null, "perms");
8288 if (pkg.sharedUser == null) {
8289 // If this is a shared user, the permissions will
8290 // be written there. We still need to write an
8291 // empty permissions list so permissionsFixed will
8292 // be set.
8293 for (final String name : pkg.grantedPermissions) {
8294 serializer.startTag(null, "item");
8295 serializer.attribute(null, "name", name);
8296 serializer.endTag(null, "item");
8297 }
8298 }
8299 serializer.endTag(null, "perms");
8300 }
8301 if (pkg.disabledComponents.size() > 0) {
8302 serializer.startTag(null, "disabled-components");
8303 for (final String name : pkg.disabledComponents) {
8304 serializer.startTag(null, "item");
8305 serializer.attribute(null, "name", name);
8306 serializer.endTag(null, "item");
8307 }
8308 serializer.endTag(null, "disabled-components");
8309 }
8310 if (pkg.enabledComponents.size() > 0) {
8311 serializer.startTag(null, "enabled-components");
8312 for (final String name : pkg.enabledComponents) {
8313 serializer.startTag(null, "item");
8314 serializer.attribute(null, "name", name);
8315 serializer.endTag(null, "item");
8316 }
8317 serializer.endTag(null, "enabled-components");
8318 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008320 serializer.endTag(null, "package");
8321 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008323 void writePermission(XmlSerializer serializer, BasePermission bp)
8324 throws XmlPullParserException, java.io.IOException {
8325 if (bp.type != BasePermission.TYPE_BUILTIN
8326 && bp.sourcePackage != null) {
8327 serializer.startTag(null, "item");
8328 serializer.attribute(null, "name", bp.name);
8329 serializer.attribute(null, "package", bp.sourcePackage);
8330 if (DEBUG_SETTINGS) Log.v(TAG,
8331 "Writing perm: name=" + bp.name + " type=" + bp.type);
8332 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8333 PermissionInfo pi = bp.perm != null ? bp.perm.info
8334 : bp.pendingInfo;
8335 if (pi != null) {
8336 serializer.attribute(null, "type", "dynamic");
8337 if (pi.icon != 0) {
8338 serializer.attribute(null, "icon",
8339 Integer.toString(pi.icon));
8340 }
8341 if (pi.nonLocalizedLabel != null) {
8342 serializer.attribute(null, "label",
8343 pi.nonLocalizedLabel.toString());
8344 }
8345 if (pi.protectionLevel !=
8346 PermissionInfo.PROTECTION_NORMAL) {
8347 serializer.attribute(null, "protection",
8348 Integer.toString(pi.protectionLevel));
8349 }
8350 }
8351 }
8352 serializer.endTag(null, "item");
8353 }
8354 }
8355
8356 String getReadMessagesLP() {
8357 return mReadMessages.toString();
8358 }
8359
Oscar Montemayora8529f62009-11-18 10:14:20 -08008360 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008361 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8362 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008363 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008364 while(its.hasNext()) {
8365 String key = its.next();
8366 PackageSetting ps = mPackages.get(key);
8367 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008368 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008369 }
8370 }
8371 return ret;
8372 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008374 boolean readLP() {
8375 FileInputStream str = null;
8376 if (mBackupSettingsFilename.exists()) {
8377 try {
8378 str = new FileInputStream(mBackupSettingsFilename);
8379 mReadMessages.append("Reading from backup settings file\n");
8380 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008381 if (mSettingsFilename.exists()) {
8382 // If both the backup and settings file exist, we
8383 // ignore the settings since it might have been
8384 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008385 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008386 mSettingsFilename.delete();
8387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008388 } catch (java.io.IOException e) {
8389 // We'll try for the normal settings file.
8390 }
8391 }
8392
8393 mPastSignatures.clear();
8394
8395 try {
8396 if (str == null) {
8397 if (!mSettingsFilename.exists()) {
8398 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008399 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008400 return false;
8401 }
8402 str = new FileInputStream(mSettingsFilename);
8403 }
8404 XmlPullParser parser = Xml.newPullParser();
8405 parser.setInput(str, null);
8406
8407 int type;
8408 while ((type=parser.next()) != XmlPullParser.START_TAG
8409 && type != XmlPullParser.END_DOCUMENT) {
8410 ;
8411 }
8412
8413 if (type != XmlPullParser.START_TAG) {
8414 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008415 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008416 return false;
8417 }
8418
8419 int outerDepth = parser.getDepth();
8420 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8421 && (type != XmlPullParser.END_TAG
8422 || parser.getDepth() > outerDepth)) {
8423 if (type == XmlPullParser.END_TAG
8424 || type == XmlPullParser.TEXT) {
8425 continue;
8426 }
8427
8428 String tagName = parser.getName();
8429 if (tagName.equals("package")) {
8430 readPackageLP(parser);
8431 } else if (tagName.equals("permissions")) {
8432 readPermissionsLP(mPermissions, parser);
8433 } else if (tagName.equals("permission-trees")) {
8434 readPermissionsLP(mPermissionTrees, parser);
8435 } else if (tagName.equals("shared-user")) {
8436 readSharedUserLP(parser);
8437 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008438 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008439 } else if (tagName.equals("preferred-activities")) {
8440 readPreferredActivitiesLP(parser);
8441 } else if(tagName.equals("updated-package")) {
8442 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008443 } else if (tagName.equals("cleaning-package")) {
8444 String name = parser.getAttributeValue(null, "name");
8445 if (name != null) {
8446 mPackagesToBeCleaned.add(name);
8447 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008448 } else if (tagName.equals("renamed-package")) {
8449 String nname = parser.getAttributeValue(null, "new");
8450 String oname = parser.getAttributeValue(null, "old");
8451 if (nname != null && oname != null) {
8452 mRenamedPackages.put(nname, oname);
8453 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008454 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008455 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008456 + parser.getName());
8457 XmlUtils.skipCurrentTag(parser);
8458 }
8459 }
8460
8461 str.close();
8462
8463 } catch(XmlPullParserException e) {
8464 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008465 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008466
8467 } catch(java.io.IOException e) {
8468 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008469 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008470
8471 }
8472
8473 int N = mPendingPackages.size();
8474 for (int i=0; i<N; i++) {
8475 final PendingPackage pp = mPendingPackages.get(i);
8476 Object idObj = getUserIdLP(pp.sharedId);
8477 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008478 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008479 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008480 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008481 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008482 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008483 + pp.name);
8484 continue;
8485 }
8486 p.copyFrom(pp);
8487 } else if (idObj != null) {
8488 String msg = "Bad package setting: package " + pp.name
8489 + " has shared uid " + pp.sharedId
8490 + " that is not a shared uid\n";
8491 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008492 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008493 } else {
8494 String msg = "Bad package setting: package " + pp.name
8495 + " has shared uid " + pp.sharedId
8496 + " that is not defined\n";
8497 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008498 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008499 }
8500 }
8501 mPendingPackages.clear();
8502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008503 mReadMessages.append("Read completed successfully: "
8504 + mPackages.size() + " packages, "
8505 + mSharedUsers.size() + " shared uids\n");
8506
8507 return true;
8508 }
8509
8510 private int readInt(XmlPullParser parser, String ns, String name,
8511 int defValue) {
8512 String v = parser.getAttributeValue(ns, name);
8513 try {
8514 if (v == null) {
8515 return defValue;
8516 }
8517 return Integer.parseInt(v);
8518 } catch (NumberFormatException e) {
8519 reportSettingsProblem(Log.WARN,
8520 "Error in package manager settings: attribute " +
8521 name + " has bad integer value " + v + " at "
8522 + parser.getPositionDescription());
8523 }
8524 return defValue;
8525 }
8526
8527 private void readPermissionsLP(HashMap<String, BasePermission> out,
8528 XmlPullParser parser)
8529 throws IOException, XmlPullParserException {
8530 int outerDepth = parser.getDepth();
8531 int type;
8532 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8533 && (type != XmlPullParser.END_TAG
8534 || parser.getDepth() > outerDepth)) {
8535 if (type == XmlPullParser.END_TAG
8536 || type == XmlPullParser.TEXT) {
8537 continue;
8538 }
8539
8540 String tagName = parser.getName();
8541 if (tagName.equals("item")) {
8542 String name = parser.getAttributeValue(null, "name");
8543 String sourcePackage = parser.getAttributeValue(null, "package");
8544 String ptype = parser.getAttributeValue(null, "type");
8545 if (name != null && sourcePackage != null) {
8546 boolean dynamic = "dynamic".equals(ptype);
8547 BasePermission bp = new BasePermission(name, sourcePackage,
8548 dynamic
8549 ? BasePermission.TYPE_DYNAMIC
8550 : BasePermission.TYPE_NORMAL);
8551 if (dynamic) {
8552 PermissionInfo pi = new PermissionInfo();
8553 pi.packageName = sourcePackage.intern();
8554 pi.name = name.intern();
8555 pi.icon = readInt(parser, null, "icon", 0);
8556 pi.nonLocalizedLabel = parser.getAttributeValue(
8557 null, "label");
8558 pi.protectionLevel = readInt(parser, null, "protection",
8559 PermissionInfo.PROTECTION_NORMAL);
8560 bp.pendingInfo = pi;
8561 }
8562 out.put(bp.name, bp);
8563 } else {
8564 reportSettingsProblem(Log.WARN,
8565 "Error in package manager settings: permissions has"
8566 + " no name at " + parser.getPositionDescription());
8567 }
8568 } else {
8569 reportSettingsProblem(Log.WARN,
8570 "Unknown element reading permissions: "
8571 + parser.getName() + " at "
8572 + parser.getPositionDescription());
8573 }
8574 XmlUtils.skipCurrentTag(parser);
8575 }
8576 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008578 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008579 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008580 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008581 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008582 String codePathStr = parser.getAttributeValue(null, "codePath");
8583 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008584 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008585 resourcePathStr = codePathStr;
8586 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008587 String version = parser.getAttributeValue(null, "version");
8588 int versionCode = 0;
8589 if (version != null) {
8590 try {
8591 versionCode = Integer.parseInt(version);
8592 } catch (NumberFormatException e) {
8593 }
8594 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008596 int pkgFlags = 0;
8597 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008598 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008599 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008600 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008601 String timeStampStr = parser.getAttributeValue(null, "ts");
8602 if (timeStampStr != null) {
8603 try {
8604 long timeStamp = Long.parseLong(timeStampStr);
8605 ps.setTimeStamp(timeStamp, timeStampStr);
8606 } catch (NumberFormatException e) {
8607 }
8608 }
8609 String idStr = parser.getAttributeValue(null, "userId");
8610 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8611 if(ps.userId <= 0) {
8612 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8613 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8614 }
8615 int outerDepth = parser.getDepth();
8616 int type;
8617 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8618 && (type != XmlPullParser.END_TAG
8619 || parser.getDepth() > outerDepth)) {
8620 if (type == XmlPullParser.END_TAG
8621 || type == XmlPullParser.TEXT) {
8622 continue;
8623 }
8624
8625 String tagName = parser.getName();
8626 if (tagName.equals("perms")) {
8627 readGrantedPermissionsLP(parser,
8628 ps.grantedPermissions);
8629 } else {
8630 reportSettingsProblem(Log.WARN,
8631 "Unknown element under <updated-package>: "
8632 + parser.getName());
8633 XmlUtils.skipCurrentTag(parser);
8634 }
8635 }
8636 mDisabledSysPackages.put(name, ps);
8637 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008639 private void readPackageLP(XmlPullParser parser)
8640 throws XmlPullParserException, IOException {
8641 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008642 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008643 String idStr = null;
8644 String sharedIdStr = null;
8645 String codePathStr = null;
8646 String resourcePathStr = null;
8647 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008648 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008649 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008650 int pkgFlags = 0;
8651 String timeStampStr;
8652 long timeStamp = 0;
8653 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008654 String version = null;
8655 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008656 try {
8657 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008658 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008659 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008660 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008661 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8662 codePathStr = parser.getAttributeValue(null, "codePath");
8663 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008664 version = parser.getAttributeValue(null, "version");
8665 if (version != null) {
8666 try {
8667 versionCode = Integer.parseInt(version);
8668 } catch (NumberFormatException e) {
8669 }
8670 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008671 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008672
8673 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008674 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008675 try {
8676 pkgFlags = Integer.parseInt(systemStr);
8677 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008678 }
8679 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008680 // For backward compatibility
8681 systemStr = parser.getAttributeValue(null, "system");
8682 if (systemStr != null) {
8683 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8684 } else {
8685 // Old settings that don't specify system... just treat
8686 // them as system, good enough.
8687 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008689 }
8690 timeStampStr = parser.getAttributeValue(null, "ts");
8691 if (timeStampStr != null) {
8692 try {
8693 timeStamp = Long.parseLong(timeStampStr);
8694 } catch (NumberFormatException e) {
8695 }
8696 }
8697 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8698 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8699 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8700 if (resourcePathStr == null) {
8701 resourcePathStr = codePathStr;
8702 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008703 if (realName != null) {
8704 realName = realName.intern();
8705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008706 if (name == null) {
8707 reportSettingsProblem(Log.WARN,
8708 "Error in package manager settings: <package> has no name at "
8709 + parser.getPositionDescription());
8710 } else if (codePathStr == null) {
8711 reportSettingsProblem(Log.WARN,
8712 "Error in package manager settings: <package> has no codePath at "
8713 + parser.getPositionDescription());
8714 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008715 packageSetting = addPackageLP(name.intern(), realName,
8716 new File(codePathStr), new File(resourcePathStr),
8717 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008718 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8719 + ": userId=" + userId + " pkg=" + packageSetting);
8720 if (packageSetting == null) {
8721 reportSettingsProblem(Log.ERROR,
8722 "Failure adding uid " + userId
8723 + " while parsing settings at "
8724 + parser.getPositionDescription());
8725 } else {
8726 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8727 }
8728 } else if (sharedIdStr != null) {
8729 userId = sharedIdStr != null
8730 ? Integer.parseInt(sharedIdStr) : 0;
8731 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008732 packageSetting = new PendingPackage(name.intern(), realName,
8733 new File(codePathStr), new File(resourcePathStr),
8734 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008735 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8736 mPendingPackages.add((PendingPackage) packageSetting);
8737 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8738 + ": sharedUserId=" + userId + " pkg="
8739 + packageSetting);
8740 } else {
8741 reportSettingsProblem(Log.WARN,
8742 "Error in package manager settings: package "
8743 + name + " has bad sharedId " + sharedIdStr
8744 + " at " + parser.getPositionDescription());
8745 }
8746 } else {
8747 reportSettingsProblem(Log.WARN,
8748 "Error in package manager settings: package "
8749 + name + " has bad userId " + idStr + " at "
8750 + parser.getPositionDescription());
8751 }
8752 } catch (NumberFormatException e) {
8753 reportSettingsProblem(Log.WARN,
8754 "Error in package manager settings: package "
8755 + name + " has bad userId " + idStr + " at "
8756 + parser.getPositionDescription());
8757 }
8758 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008759 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008760 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008761 final String enabledStr = parser.getAttributeValue(null, "enabled");
8762 if (enabledStr != null) {
8763 if (enabledStr.equalsIgnoreCase("true")) {
8764 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8765 } else if (enabledStr.equalsIgnoreCase("false")) {
8766 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
8767 } else if (enabledStr.equalsIgnoreCase("default")) {
8768 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8769 } else {
8770 reportSettingsProblem(Log.WARN,
8771 "Error in package manager settings: package "
8772 + name + " has bad enabled value: " + idStr
8773 + " at " + parser.getPositionDescription());
8774 }
8775 } else {
8776 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8777 }
8778 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
8779 if (installStatusStr != null) {
8780 if (installStatusStr.equalsIgnoreCase("false")) {
8781 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
8782 } else {
8783 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
8784 }
8785 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008787 int outerDepth = parser.getDepth();
8788 int type;
8789 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8790 && (type != XmlPullParser.END_TAG
8791 || parser.getDepth() > outerDepth)) {
8792 if (type == XmlPullParser.END_TAG
8793 || type == XmlPullParser.TEXT) {
8794 continue;
8795 }
8796
8797 String tagName = parser.getName();
8798 if (tagName.equals("disabled-components")) {
8799 readDisabledComponentsLP(packageSetting, parser);
8800 } else if (tagName.equals("enabled-components")) {
8801 readEnabledComponentsLP(packageSetting, parser);
8802 } else if (tagName.equals("sigs")) {
8803 packageSetting.signatures.readXml(parser, mPastSignatures);
8804 } else if (tagName.equals("perms")) {
8805 readGrantedPermissionsLP(parser,
8806 packageSetting.loadedPermissions);
8807 packageSetting.permissionsFixed = true;
8808 } else {
8809 reportSettingsProblem(Log.WARN,
8810 "Unknown element under <package>: "
8811 + parser.getName());
8812 XmlUtils.skipCurrentTag(parser);
8813 }
8814 }
8815 } else {
8816 XmlUtils.skipCurrentTag(parser);
8817 }
8818 }
8819
8820 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
8821 XmlPullParser parser)
8822 throws IOException, XmlPullParserException {
8823 int outerDepth = parser.getDepth();
8824 int type;
8825 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8826 && (type != XmlPullParser.END_TAG
8827 || parser.getDepth() > outerDepth)) {
8828 if (type == XmlPullParser.END_TAG
8829 || type == XmlPullParser.TEXT) {
8830 continue;
8831 }
8832
8833 String tagName = parser.getName();
8834 if (tagName.equals("item")) {
8835 String name = parser.getAttributeValue(null, "name");
8836 if (name != null) {
8837 packageSetting.disabledComponents.add(name.intern());
8838 } else {
8839 reportSettingsProblem(Log.WARN,
8840 "Error in package manager settings: <disabled-components> has"
8841 + " no name at " + parser.getPositionDescription());
8842 }
8843 } else {
8844 reportSettingsProblem(Log.WARN,
8845 "Unknown element under <disabled-components>: "
8846 + parser.getName());
8847 }
8848 XmlUtils.skipCurrentTag(parser);
8849 }
8850 }
8851
8852 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
8853 XmlPullParser parser)
8854 throws IOException, XmlPullParserException {
8855 int outerDepth = parser.getDepth();
8856 int type;
8857 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8858 && (type != XmlPullParser.END_TAG
8859 || parser.getDepth() > outerDepth)) {
8860 if (type == XmlPullParser.END_TAG
8861 || type == XmlPullParser.TEXT) {
8862 continue;
8863 }
8864
8865 String tagName = parser.getName();
8866 if (tagName.equals("item")) {
8867 String name = parser.getAttributeValue(null, "name");
8868 if (name != null) {
8869 packageSetting.enabledComponents.add(name.intern());
8870 } else {
8871 reportSettingsProblem(Log.WARN,
8872 "Error in package manager settings: <enabled-components> has"
8873 + " no name at " + parser.getPositionDescription());
8874 }
8875 } else {
8876 reportSettingsProblem(Log.WARN,
8877 "Unknown element under <enabled-components>: "
8878 + parser.getName());
8879 }
8880 XmlUtils.skipCurrentTag(parser);
8881 }
8882 }
8883
8884 private void readSharedUserLP(XmlPullParser parser)
8885 throws XmlPullParserException, IOException {
8886 String name = null;
8887 String idStr = null;
8888 int pkgFlags = 0;
8889 SharedUserSetting su = null;
8890 try {
8891 name = parser.getAttributeValue(null, "name");
8892 idStr = parser.getAttributeValue(null, "userId");
8893 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8894 if ("true".equals(parser.getAttributeValue(null, "system"))) {
8895 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8896 }
8897 if (name == null) {
8898 reportSettingsProblem(Log.WARN,
8899 "Error in package manager settings: <shared-user> has no name at "
8900 + parser.getPositionDescription());
8901 } else if (userId == 0) {
8902 reportSettingsProblem(Log.WARN,
8903 "Error in package manager settings: shared-user "
8904 + name + " has bad userId " + idStr + " at "
8905 + parser.getPositionDescription());
8906 } else {
8907 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
8908 reportSettingsProblem(Log.ERROR,
8909 "Occurred while parsing settings at "
8910 + parser.getPositionDescription());
8911 }
8912 }
8913 } catch (NumberFormatException e) {
8914 reportSettingsProblem(Log.WARN,
8915 "Error in package manager settings: package "
8916 + name + " has bad userId " + idStr + " at "
8917 + parser.getPositionDescription());
8918 };
8919
8920 if (su != null) {
8921 int outerDepth = parser.getDepth();
8922 int type;
8923 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8924 && (type != XmlPullParser.END_TAG
8925 || parser.getDepth() > outerDepth)) {
8926 if (type == XmlPullParser.END_TAG
8927 || type == XmlPullParser.TEXT) {
8928 continue;
8929 }
8930
8931 String tagName = parser.getName();
8932 if (tagName.equals("sigs")) {
8933 su.signatures.readXml(parser, mPastSignatures);
8934 } else if (tagName.equals("perms")) {
8935 readGrantedPermissionsLP(parser, su.loadedPermissions);
8936 } else {
8937 reportSettingsProblem(Log.WARN,
8938 "Unknown element under <shared-user>: "
8939 + parser.getName());
8940 XmlUtils.skipCurrentTag(parser);
8941 }
8942 }
8943
8944 } else {
8945 XmlUtils.skipCurrentTag(parser);
8946 }
8947 }
8948
8949 private void readGrantedPermissionsLP(XmlPullParser parser,
8950 HashSet<String> outPerms) throws IOException, XmlPullParserException {
8951 int outerDepth = parser.getDepth();
8952 int type;
8953 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8954 && (type != XmlPullParser.END_TAG
8955 || parser.getDepth() > outerDepth)) {
8956 if (type == XmlPullParser.END_TAG
8957 || type == XmlPullParser.TEXT) {
8958 continue;
8959 }
8960
8961 String tagName = parser.getName();
8962 if (tagName.equals("item")) {
8963 String name = parser.getAttributeValue(null, "name");
8964 if (name != null) {
8965 outPerms.add(name.intern());
8966 } else {
8967 reportSettingsProblem(Log.WARN,
8968 "Error in package manager settings: <perms> has"
8969 + " no name at " + parser.getPositionDescription());
8970 }
8971 } else {
8972 reportSettingsProblem(Log.WARN,
8973 "Unknown element under <perms>: "
8974 + parser.getName());
8975 }
8976 XmlUtils.skipCurrentTag(parser);
8977 }
8978 }
8979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008980 private void readPreferredActivitiesLP(XmlPullParser parser)
8981 throws XmlPullParserException, IOException {
8982 int outerDepth = parser.getDepth();
8983 int type;
8984 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8985 && (type != XmlPullParser.END_TAG
8986 || parser.getDepth() > outerDepth)) {
8987 if (type == XmlPullParser.END_TAG
8988 || type == XmlPullParser.TEXT) {
8989 continue;
8990 }
8991
8992 String tagName = parser.getName();
8993 if (tagName.equals("item")) {
8994 PreferredActivity pa = new PreferredActivity(parser);
8995 if (pa.mParseError == null) {
8996 mPreferredActivities.addFilter(pa);
8997 } else {
8998 reportSettingsProblem(Log.WARN,
8999 "Error in package manager settings: <preferred-activity> "
9000 + pa.mParseError + " at "
9001 + parser.getPositionDescription());
9002 }
9003 } else {
9004 reportSettingsProblem(Log.WARN,
9005 "Unknown element under <preferred-activities>: "
9006 + parser.getName());
9007 XmlUtils.skipCurrentTag(parser);
9008 }
9009 }
9010 }
9011
9012 // Returns -1 if we could not find an available UserId to assign
9013 private int newUserIdLP(Object obj) {
9014 // Let's be stupidly inefficient for now...
9015 final int N = mUserIds.size();
9016 for (int i=0; i<N; i++) {
9017 if (mUserIds.get(i) == null) {
9018 mUserIds.set(i, obj);
9019 return FIRST_APPLICATION_UID + i;
9020 }
9021 }
9022
9023 // None left?
9024 if (N >= MAX_APPLICATION_UIDS) {
9025 return -1;
9026 }
9027
9028 mUserIds.add(obj);
9029 return FIRST_APPLICATION_UID + N;
9030 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009032 public PackageSetting getDisabledSystemPkg(String name) {
9033 synchronized(mPackages) {
9034 PackageSetting ps = mDisabledSysPackages.get(name);
9035 return ps;
9036 }
9037 }
9038
9039 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9040 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9041 if (Config.LOGV) {
9042 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9043 + " componentName = " + componentInfo.name);
9044 Log.v(TAG, "enabledComponents: "
9045 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9046 Log.v(TAG, "disabledComponents: "
9047 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9048 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009049 if (packageSettings == null) {
9050 if (false) {
9051 Log.w(TAG, "WAITING FOR DEBUGGER");
9052 Debug.waitForDebugger();
9053 Log.i(TAG, "We will crash!");
9054 }
9055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009056 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9057 || ((componentInfo.enabled
9058 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9059 || (componentInfo.applicationInfo.enabled
9060 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9061 && !packageSettings.disabledComponents.contains(componentInfo.name))
9062 || packageSettings.enabledComponents.contains(componentInfo.name));
9063 }
9064 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009065
9066 // ------- apps on sdcard specific code -------
9067 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009068 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009069 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009070 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009071 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009072
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009073 private String getEncryptKey() {
9074 try {
9075 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9076 if (sdEncKey == null) {
9077 sdEncKey = SystemKeyStore.getInstance().
9078 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9079 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009080 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009081 return null;
9082 }
9083 }
9084 return sdEncKey;
9085 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009086 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009087 return null;
9088 }
9089 }
9090
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009091 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009092 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009093 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009094 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009095 if (list != null) {
9096 int idx = 0;
9097 int idList[] = new int[MAX_CONTAINERS];
9098 boolean neverFound = true;
9099 for (String name : list) {
9100 // Ignore null entries
9101 if (name == null) {
9102 continue;
9103 }
9104 int sidx = name.indexOf(prefix);
9105 if (sidx == -1) {
9106 // Not a temp file. just ignore
9107 continue;
9108 }
9109 String subStr = name.substring(sidx + prefix.length());
9110 idList[idx] = -1;
9111 if (subStr != null) {
9112 try {
9113 int cid = Integer.parseInt(subStr);
9114 idList[idx++] = cid;
9115 neverFound = false;
9116 } catch (NumberFormatException e) {
9117 }
9118 }
9119 }
9120 if (!neverFound) {
9121 // Sort idList
9122 Arrays.sort(idList);
9123 for (int j = 1; j <= idList.length; j++) {
9124 if (idList[j-1] != j) {
9125 tmpIdx = j;
9126 break;
9127 }
9128 }
9129 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009130 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009131 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009132 }
9133
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009134 /*
9135 * Return true if PackageManager does have packages to be updated.
9136 */
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009137 public boolean updateExternalMediaStatus(final boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009138 final boolean ret;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009139 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009140 Log.i(TAG, "Updating external media status from " +
9141 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9142 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009143 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9144 mediaStatus+", mMediaMounted=" + mMediaMounted);
9145 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009146 return false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009147 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009148 mMediaMounted = mediaStatus;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009149 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_EXTERNAL_STORAGE);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009150 ret = appList != null && appList.size() > 0;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009151 if (DEBUG_SD_INSTALL) {
9152 if (appList != null) {
9153 for (String app : appList) {
9154 Log.i(TAG, "Should enable " + app + " on sdcard");
9155 }
9156 }
9157 }
9158 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus returning " + ret);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009159 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009160 // Queue up an async operation since the package installation may take a little while.
9161 mHandler.post(new Runnable() {
9162 public void run() {
9163 mHandler.removeCallbacks(this);
9164 updateExternalMediaStatusInner(mediaStatus, ret);
9165 }
9166 });
9167 return ret;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009168 }
9169
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009170 private void updateExternalMediaStatusInner(boolean mediaStatus,
9171 boolean sendUpdateBroadcast) {
9172 // If we are up here that means there are packages to be
9173 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009174 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009175 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009176 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009177 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009178 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009179
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009180 int uidList[] = new int[list.length];
9181 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009182 HashSet<String> removeCids = new HashSet<String>();
9183 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009184 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009185 for (String cid : list) {
9186 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009187 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9188 boolean failed = true;
9189 try {
9190 String pkgName = args.getPackageName();
9191 if (pkgName == null) {
9192 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009193 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009194 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9195 PackageSetting ps = mSettings.mPackages.get(pkgName);
9196 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009197 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009198 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9199 " corresponds to pkg : " + pkgName +
9200 " at code path: " + ps.codePathString);
9201 // We do have a valid package installed on sdcard
9202 processCids.put(args, ps.codePathString);
9203 failed = false;
9204 int uid = ps.userId;
9205 if (uid != -1) {
9206 uidList[num++] = uid;
9207 }
9208 }
9209 } finally {
9210 if (failed) {
9211 // Stale container on sdcard. Just delete
9212 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9213 removeCids.add(cid);
9214 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009215 }
9216 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009217 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009218 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009219 int uidArr[] = null;
9220 if (num > 0) {
9221 // Sort uid list
9222 Arrays.sort(uidList, 0, num);
9223 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009224 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009225 uidArr[0] = uidList[0];
9226 int di = 0;
9227 for (int i = 1; i < num; i++) {
9228 if (uidList[i-1] != uidList[i]) {
9229 uidArr[di++] = uidList[i];
9230 }
9231 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009232 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009233 // Process packages with valid entries.
9234 if (mediaStatus) {
9235 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
9236 loadMediaPackages(processCids, uidArr, sendUpdateBroadcast, removeCids);
9237 startCleaningPackages();
9238 } else {
9239 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
9240 unloadMediaPackages(processCids, uidArr, sendUpdateBroadcast);
9241 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009242 }
9243
9244 private void sendResourcesChangedBroadcast(boolean mediaStatus,
9245 ArrayList<String> pkgList, int uidArr[]) {
9246 int size = pkgList.size();
9247 if (size > 0) {
9248 // Send broadcasts here
9249 Bundle extras = new Bundle();
9250 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9251 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009252 if (uidArr != null) {
9253 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9254 }
9255 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9256 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009257 sendPackageBroadcast(action, null, extras);
9258 }
9259 }
9260
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009261 /*
9262 * Look at potentially valid container ids from processCids
9263 * If package information doesn't match the one on record
9264 * or package scanning fails, the cid is added to list of
9265 * removeCids and cleaned up. Since cleaning up containers
9266 * involves destroying them, we do not want any parse
9267 * references to such stale containers. So force gc's
9268 * to avoid unnecessary crashes.
9269 */
9270 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
9271 int uidArr[], boolean sendUpdateBroadcast,
9272 HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009273 ArrayList<String> pkgList = new ArrayList<String>();
9274 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009275 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009276 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009277 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009278 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9279 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009280 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009281 try {
9282 // Make sure there are no container errors first.
9283 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9284 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009285 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009286 " when installing from sdcard");
9287 continue;
9288 }
9289 // Check code path here.
9290 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009291 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009292 " does not match one in settings " + codePath);
9293 continue;
9294 }
9295 // Parse package
9296 int parseFlags = PackageParser.PARSE_CHATTY |
9297 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
9298 PackageParser pp = new PackageParser(codePath);
9299 pp.setSeparateProcesses(mSeparateProcesses);
9300 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
9301 codePath, mMetrics, parseFlags);
9302 pp = null;
9303 doGc = true;
9304 // Check for parse errors
9305 if (pkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009306 Slog.e(TAG, "Parse error when installing install pkg : "
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009307 + args.cid + " from " + args.cachePath);
9308 continue;
9309 }
9310 setApplicationInfoPaths(pkg, codePath, codePath);
9311 synchronized (mInstallLock) {
9312 // Scan the package
9313 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
9314 synchronized (mPackages) {
9315 // Grant permissions
9316 grantPermissionsLP(pkg, false);
9317 // Persist settings
9318 mSettings.writeLP();
9319 retCode = PackageManager.INSTALL_SUCCEEDED;
9320 pkgList.add(pkg.packageName);
9321 // Post process args
9322 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9323 }
9324 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009325 Slog.i(TAG, "Failed to install pkg: " +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009326 pkg.packageName + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009327 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009328 }
9329
9330 } finally {
9331 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9332 // Don't destroy container here. Wait till gc clears things up.
9333 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009334 }
9335 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009336 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009337 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009338 if (sendUpdateBroadcast) {
9339 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9340 }
9341 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009342 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009343 }
9344 // Delete any stale containers if needed.
9345 if (removeCids != null) {
9346 for (String cid : removeCids) {
9347 Log.i(TAG, "Destroying stale container : " + cid);
9348 PackageHelper.destroySdDir(cid);
9349 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009350 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009351 }
9352
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009353 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
9354 int uidArr[], boolean sendUpdateBroadcast) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009355 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009356 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009357 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009358 Set<SdInstallArgs> keys = processCids.keySet();
9359 for (SdInstallArgs args : keys) {
9360 String cid = args.cid;
9361 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009362 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009363 // Delete package internally
9364 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9365 synchronized (mInstallLock) {
9366 boolean res = deletePackageLI(pkgName, false,
9367 PackageManager.DONT_DELETE_DATA, outInfo);
9368 if (res) {
9369 pkgList.add(pkgName);
9370 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009371 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009372 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009373 }
9374 }
9375 }
9376 // Send broadcasts
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009377 if (sendUpdateBroadcast) {
9378 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009379 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009380 // Force gc
9381 Runtime.getRuntime().gc();
9382 // Just unmount all valid containers.
9383 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009384 synchronized (mInstallLock) {
9385 args.doPostDeleteLI(false);
9386 }
9387 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009388 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009389
9390 public void movePackage(final String packageName,
9391 final IPackageMoveObserver observer, final int flags) {
9392 if (packageName == null) {
9393 return;
9394 }
9395 mContext.enforceCallingOrSelfPermission(
9396 android.Manifest.permission.MOVE_PACKAGE, null);
9397 int returnCode = PackageManager.MOVE_SUCCEEDED;
9398 int currFlags = 0;
9399 int newFlags = 0;
9400 synchronized (mPackages) {
9401 PackageParser.Package pkg = mPackages.get(packageName);
9402 if (pkg == null) {
9403 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9404 }
9405 // Disable moving fwd locked apps and system packages
9406 if (pkg.applicationInfo != null &&
9407 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009408 Slog.w(TAG, "Cannot move system application");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009409 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9410 } else if (pkg.applicationInfo != null &&
9411 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009412 Slog.w(TAG, "Cannot move forward locked app.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009413 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9414 } else {
9415 // Find install location first
9416 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9417 (flags & PackageManager.MOVE_INTERNAL) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009418 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009419 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9420 } else {
9421 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9422 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009423 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009424 PackageManager.INSTALL_EXTERNAL : 0;
9425 if (newFlags == currFlags) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009426 Slog.w(TAG, "No move required. Trying to move to same location");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009427 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9428 }
9429 }
9430 }
9431 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9432 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9433 } else {
9434 Message msg = mHandler.obtainMessage(INIT_COPY);
9435 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9436 pkg.applicationInfo.publicSourceDir);
9437 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9438 packageName);
9439 msg.obj = mp;
9440 mHandler.sendMessage(msg);
9441 }
9442 }
9443 }
9444
9445 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9446 // Queue up an async operation since the package deletion may take a little while.
9447 mHandler.post(new Runnable() {
9448 public void run() {
9449 mHandler.removeCallbacks(this);
9450 int returnCode = currentStatus;
9451 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9452 if (moveSucceeded) {
9453 int uid = -1;
9454 synchronized (mPackages) {
9455 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9456 }
9457 ArrayList<String> pkgList = new ArrayList<String>();
9458 pkgList.add(mp.packageName);
9459 int uidArr[] = new int[] { uid };
9460 // Send resources unavailable broadcast
9461 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9462
9463 // Update package code and resource paths
9464 synchronized (mPackages) {
9465 PackageParser.Package pkg = mPackages.get(mp.packageName);
9466 if (pkg != null) {
9467 String oldCodePath = pkg.mPath;
9468 String newCodePath = mp.targetArgs.getCodePath();
9469 String newResPath = mp.targetArgs.getResourcePath();
9470 pkg.mPath = newCodePath;
9471 // Move dex files around
9472 if (moveDexFiles(pkg)
9473 != PackageManager.INSTALL_SUCCEEDED) {
9474 // Moving of dex files failed. Set
9475 // error code and abort move.
9476 pkg.mPath = pkg.mScanPath;
9477 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9478 moveSucceeded = false;
9479 } else {
9480 pkg.mScanPath = newCodePath;
9481 pkg.applicationInfo.sourceDir = newCodePath;
9482 pkg.applicationInfo.publicSourceDir = newResPath;
9483 PackageSetting ps = (PackageSetting) pkg.mExtras;
9484 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9485 ps.codePathString = ps.codePath.getPath();
9486 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9487 ps.resourcePathString = ps.resourcePath.getPath();
9488 // Set the application info flag correctly.
9489 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009490 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009491 } else {
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009492 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009493 }
9494 ps.setFlags(pkg.applicationInfo.flags);
9495 mAppDirs.remove(oldCodePath);
9496 mAppDirs.put(newCodePath, pkg);
9497 // Persist settings
9498 mSettings.writeLP();
9499 }
9500 }
9501 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009502 // Send resources available broadcast
9503 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009504 }
9505 if (!moveSucceeded){
9506 // Clean up failed installation
9507 if (mp.targetArgs != null) {
9508 mp.targetArgs.doPostInstall(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009509 returnCode);
9510 }
9511 } else {
9512 // Force a gc to clear things up.
9513 Runtime.getRuntime().gc();
9514 // Delete older code
9515 synchronized (mInstallLock) {
9516 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009517 }
9518 }
9519 IPackageMoveObserver observer = mp.observer;
9520 if (observer != null) {
9521 try {
9522 observer.packageMoved(mp.packageName, returnCode);
9523 } catch (RemoteException e) {
9524 Log.i(TAG, "Observer no longer exists.");
9525 }
9526 }
9527 }
9528 });
9529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009530}