blob: 55725bdab76321ca4eeef666fa1f7e4988678d26 [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 Amalapurapu14b6abd2010-03-17 08:37:04 -0700598 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800599 return false;
600 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700601 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
602 return true;
603 }
604 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800605 }
606
607 static boolean isFwdLocked(int flags) {
608 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
609 return true;
610 }
611 return false;
612 }
613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614 public static final IPackageManager main(Context context, boolean factoryTest) {
615 PackageManagerService m = new PackageManagerService(context, factoryTest);
616 ServiceManager.addService("package", m);
617 return m;
618 }
619
620 static String[] splitString(String str, char sep) {
621 int count = 1;
622 int i = 0;
623 while ((i=str.indexOf(sep, i)) >= 0) {
624 count++;
625 i++;
626 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 String[] res = new String[count];
629 i=0;
630 count = 0;
631 int lastI=0;
632 while ((i=str.indexOf(sep, i)) >= 0) {
633 res[count] = str.substring(lastI, i);
634 count++;
635 i++;
636 lastI = i;
637 }
638 res[count] = str.substring(lastI, str.length());
639 return res;
640 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800643 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800647 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 mContext = context;
651 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700652 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 mMetrics = new DisplayMetrics();
654 mSettings = new Settings();
655 mSettings.addSharedUserLP("android.uid.system",
656 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
657 mSettings.addSharedUserLP("android.uid.phone",
658 MULTIPLE_APPLICATION_UIDS
659 ? RADIO_UID : FIRST_APPLICATION_UID,
660 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400661 mSettings.addSharedUserLP("android.uid.log",
662 MULTIPLE_APPLICATION_UIDS
663 ? LOG_UID : FIRST_APPLICATION_UID,
664 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665
666 String separateProcesses = SystemProperties.get("debug.separate_processes");
667 if (separateProcesses != null && separateProcesses.length() > 0) {
668 if ("*".equals(separateProcesses)) {
669 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
670 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800671 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 } else {
673 mDefParseFlags = 0;
674 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800675 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 + separateProcesses);
677 }
678 } else {
679 mDefParseFlags = 0;
680 mSeparateProcesses = null;
681 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 Installer installer = new Installer();
684 // Little hacky thing to check if installd is here, to determine
685 // whether we are running on the simulator and thus need to take
686 // care of building the /data file structure ourself.
687 // (apparently the sim now has a working installer)
688 if (installer.ping() && Process.supportsProcesses()) {
689 mInstaller = installer;
690 } else {
691 mInstaller = null;
692 }
693
694 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
695 Display d = wm.getDefaultDisplay();
696 d.getMetrics(mMetrics);
697
698 synchronized (mInstallLock) {
699 synchronized (mPackages) {
700 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700701 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 File dataDir = Environment.getDataDirectory();
704 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800705 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
707
708 if (mInstaller == null) {
709 // Make sure these dirs exist, when we are running in
710 // the simulator.
711 // Make a wide-open directory for random misc stuff.
712 File miscDir = new File(dataDir, "misc");
713 miscDir.mkdirs();
714 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800715 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 mDrmAppPrivateInstallDir.mkdirs();
717 }
718
719 readPermissions();
720
721 mRestoredSettings = mSettings.readLP();
722 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800723
724 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800726
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800727 // Set flag to monitor and not change apk file paths when
728 // scanning install directories.
729 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700730 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800731 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800732 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700733 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700738 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700741 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 /**
744 * Out of paranoia, ensure that everything in the boot class
745 * path has been dexed.
746 */
747 String bootClassPath = System.getProperty("java.boot.class.path");
748 if (bootClassPath != null) {
749 String[] paths = splitString(bootClassPath, ':');
750 for (int i=0; i<paths.length; i++) {
751 try {
752 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
753 libFiles.add(paths[i]);
754 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700755 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 }
757 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800758 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800760 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 }
762 }
763 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800764 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 /**
768 * Also ensure all external libraries have had dexopt run on them.
769 */
770 if (mSharedLibraries.size() > 0) {
771 Iterator<String> libs = mSharedLibraries.values().iterator();
772 while (libs.hasNext()) {
773 String lib = libs.next();
774 try {
775 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
776 libFiles.add(lib);
777 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700778 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 }
780 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800781 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800783 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 }
785 }
786 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 // Gross hack for now: we know this file doesn't contain any
789 // code, so don't dexopt it to avoid the resulting log spew.
790 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 /**
793 * And there are a number of commands implemented in Java, which
794 * we currently need to do the dexopt on so that they can be
795 * run from a non-root shell.
796 */
797 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700798 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 for (int i=0; i<frameworkFiles.length; i++) {
800 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
801 String path = libPath.getPath();
802 // Skip the file if we alrady did it.
803 if (libFiles.contains(path)) {
804 continue;
805 }
806 // Skip the file if it is not a type we want to dexopt.
807 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
808 continue;
809 }
810 try {
811 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
812 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700813 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 }
815 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800816 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800818 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 }
820 }
821 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800822
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700823 if (didDexOpt) {
824 // If we had to do a dexopt of one of the previous
825 // things, then something on the system has changed.
826 // Consider this significant, and wipe away all other
827 // existing dexopt files to ensure we don't leave any
828 // dangling around.
829 String[] files = mDalvikCacheDir.list();
830 if (files != null) {
831 for (int i=0; i<files.length; i++) {
832 String fn = files[i];
833 if (fn.startsWith("data@app@")
834 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800835 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700836 (new File(mDalvikCacheDir, fn)).delete();
837 }
838 }
839 }
840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800842
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800843 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 mFrameworkInstallObserver = new AppDirObserver(
845 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
846 mFrameworkInstallObserver.startWatching();
847 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800848 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800849
850 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
852 mSystemInstallObserver = new AppDirObserver(
853 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
854 mSystemInstallObserver.startWatching();
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800855 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800856
857 if (mInstaller != null) {
858 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
859 mInstaller.moveFiles();
860 }
861
862 // Prune any system packages that no longer exist.
863 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
864 while (psit.hasNext()) {
865 PackageSetting ps = psit.next();
866 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800867 && !mPackages.containsKey(ps.name)
868 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800869 psit.remove();
870 String msg = "System package " + ps.name
871 + " no longer exists; wiping its data";
872 reportSettingsProblem(Log.WARN, msg);
873 if (mInstaller != null) {
874 // XXX how to set useEncryptedFSDir for packages that
875 // are not encrypted?
876 mInstaller.remove(ps.name, true);
877 }
878 }
879 }
880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 mAppInstallDir = new File(dataDir, "app");
882 if (mInstaller == null) {
883 // Make sure these dirs exist, when we are running in
884 // the simulator.
885 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
886 }
887 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800888 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 //clean up list
890 for(int i = 0; i < deletePkgsList.size(); i++) {
891 //clean up here
892 cleanupInstallFailedPackage(deletePkgsList.get(i));
893 }
894 //delete tmp files
895 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800896
897 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 SystemClock.uptimeMillis());
899 mAppInstallObserver = new AppDirObserver(
900 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
901 mAppInstallObserver.startWatching();
902 scanDirLI(mAppInstallDir, 0, scanMode);
903
904 mDrmAppInstallObserver = new AppDirObserver(
905 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
906 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800907 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800909 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800911 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 + ((SystemClock.uptimeMillis()-startTime)/1000f)
913 + " seconds");
914
915 updatePermissionsLP();
916
917 mSettings.writeLP();
918
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800919 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 // Now after opening every single application zip, make sure they
923 // are all flushed. Not really needed, but keeps things nice and
924 // tidy.
925 Runtime.getRuntime().gc();
926 } // synchronized (mPackages)
927 } // synchronized (mInstallLock)
928 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 @Override
931 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
932 throws RemoteException {
933 try {
934 return super.onTransact(code, data, reply, flags);
935 } catch (RuntimeException e) {
936 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800937 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 }
939 throw e;
940 }
941 }
942
Dianne Hackborne6620b22010-01-22 14:46:21 -0800943 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800944 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800946 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
947 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800949 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800950 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951 }
952 } else {
953 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800954 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 File dataDir = new File(pkg.applicationInfo.dataDir);
956 dataDir.delete();
957 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800958 if (ps.codePath != null) {
959 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800960 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -0800961 }
962 }
963 if (ps.resourcePath != null) {
964 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800965 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -0800966 }
967 }
968 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 }
970
971 void readPermissions() {
972 // Read permissions from .../etc/permission directory.
973 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
974 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800975 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 return;
977 }
978 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800979 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 return;
981 }
982
983 // Iterate over the files in the directory and scan .xml files
984 for (File f : libraryDir.listFiles()) {
985 // We'll read platform.xml last
986 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
987 continue;
988 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800991 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 continue;
993 }
994 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800995 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 continue;
997 }
998
999 readPermissionsFromXml(f);
1000 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1003 final File permFile = new File(Environment.getRootDirectory(),
1004 "etc/permissions/platform.xml");
1005 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001006
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001007 StringBuilder sb = new StringBuilder(128);
1008 sb.append("Libs:");
1009 Iterator<String> it = mSharedLibraries.keySet().iterator();
1010 while (it.hasNext()) {
1011 sb.append(' ');
1012 String name = it.next();
1013 sb.append(name);
1014 sb.append(':');
1015 sb.append(mSharedLibraries.get(name));
1016 }
1017 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001018
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001019 sb.setLength(0);
1020 sb.append("Features:");
1021 it = mAvailableFeatures.keySet().iterator();
1022 while (it.hasNext()) {
1023 sb.append(' ');
1024 sb.append(it.next());
1025 }
1026 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001028
1029 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 FileReader permReader = null;
1031 try {
1032 permReader = new FileReader(permFile);
1033 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001034 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 return;
1036 }
1037
1038 try {
1039 XmlPullParser parser = Xml.newPullParser();
1040 parser.setInput(permReader);
1041
1042 XmlUtils.beginDocument(parser, "permissions");
1043
1044 while (true) {
1045 XmlUtils.nextElement(parser);
1046 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1047 break;
1048 }
1049
1050 String name = parser.getName();
1051 if ("group".equals(name)) {
1052 String gidStr = parser.getAttributeValue(null, "gid");
1053 if (gidStr != null) {
1054 int gid = Integer.parseInt(gidStr);
1055 mGlobalGids = appendInt(mGlobalGids, gid);
1056 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001057 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 + parser.getPositionDescription());
1059 }
1060
1061 XmlUtils.skipCurrentTag(parser);
1062 continue;
1063 } else if ("permission".equals(name)) {
1064 String perm = parser.getAttributeValue(null, "name");
1065 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001066 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 + parser.getPositionDescription());
1068 XmlUtils.skipCurrentTag(parser);
1069 continue;
1070 }
1071 perm = perm.intern();
1072 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 } else if ("assign-permission".equals(name)) {
1075 String perm = parser.getAttributeValue(null, "name");
1076 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001077 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 + parser.getPositionDescription());
1079 XmlUtils.skipCurrentTag(parser);
1080 continue;
1081 }
1082 String uidStr = parser.getAttributeValue(null, "uid");
1083 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001084 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 + parser.getPositionDescription());
1086 XmlUtils.skipCurrentTag(parser);
1087 continue;
1088 }
1089 int uid = Process.getUidForName(uidStr);
1090 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001091 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 + uidStr + "\" at "
1093 + parser.getPositionDescription());
1094 XmlUtils.skipCurrentTag(parser);
1095 continue;
1096 }
1097 perm = perm.intern();
1098 HashSet<String> perms = mSystemPermissions.get(uid);
1099 if (perms == null) {
1100 perms = new HashSet<String>();
1101 mSystemPermissions.put(uid, perms);
1102 }
1103 perms.add(perm);
1104 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 } else if ("library".equals(name)) {
1107 String lname = parser.getAttributeValue(null, "name");
1108 String lfile = parser.getAttributeValue(null, "file");
1109 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001110 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 + parser.getPositionDescription());
1112 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001113 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 + parser.getPositionDescription());
1115 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001116 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001117 mSharedLibraries.put(lname, lfile);
1118 }
1119 XmlUtils.skipCurrentTag(parser);
1120 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001121
Dianne Hackborn49237342009-08-27 20:08:01 -07001122 } else if ("feature".equals(name)) {
1123 String fname = parser.getAttributeValue(null, "name");
1124 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001125 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001126 + parser.getPositionDescription());
1127 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001128 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001129 FeatureInfo fi = new FeatureInfo();
1130 fi.name = fname;
1131 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 }
1133 XmlUtils.skipCurrentTag(parser);
1134 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 } else {
1137 XmlUtils.skipCurrentTag(parser);
1138 continue;
1139 }
1140
1141 }
1142 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001143 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001145 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 }
1147 }
1148
1149 void readPermission(XmlPullParser parser, String name)
1150 throws IOException, XmlPullParserException {
1151
1152 name = name.intern();
1153
1154 BasePermission bp = mSettings.mPermissions.get(name);
1155 if (bp == null) {
1156 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1157 mSettings.mPermissions.put(name, bp);
1158 }
1159 int outerDepth = parser.getDepth();
1160 int type;
1161 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1162 && (type != XmlPullParser.END_TAG
1163 || parser.getDepth() > outerDepth)) {
1164 if (type == XmlPullParser.END_TAG
1165 || type == XmlPullParser.TEXT) {
1166 continue;
1167 }
1168
1169 String tagName = parser.getName();
1170 if ("group".equals(tagName)) {
1171 String gidStr = parser.getAttributeValue(null, "gid");
1172 if (gidStr != null) {
1173 int gid = Process.getGidForName(gidStr);
1174 bp.gids = appendInt(bp.gids, gid);
1175 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001176 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 + parser.getPositionDescription());
1178 }
1179 }
1180 XmlUtils.skipCurrentTag(parser);
1181 }
1182 }
1183
1184 static int[] appendInt(int[] cur, int val) {
1185 if (cur == null) {
1186 return new int[] { val };
1187 }
1188 final int N = cur.length;
1189 for (int i=0; i<N; i++) {
1190 if (cur[i] == val) {
1191 return cur;
1192 }
1193 }
1194 int[] ret = new int[N+1];
1195 System.arraycopy(cur, 0, ret, 0, N);
1196 ret[N] = val;
1197 return ret;
1198 }
1199
1200 static int[] appendInts(int[] cur, int[] add) {
1201 if (add == null) return cur;
1202 if (cur == null) return add;
1203 final int N = add.length;
1204 for (int i=0; i<N; i++) {
1205 cur = appendInt(cur, add[i]);
1206 }
1207 return cur;
1208 }
1209
1210 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001211 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1212 // The package has been uninstalled but has retained data and resources.
1213 return PackageParser.generatePackageInfo(p, null, flags);
1214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 final PackageSetting ps = (PackageSetting)p.mExtras;
1216 if (ps == null) {
1217 return null;
1218 }
1219 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1220 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1221 }
1222
1223 public PackageInfo getPackageInfo(String packageName, int flags) {
1224 synchronized (mPackages) {
1225 PackageParser.Package p = mPackages.get(packageName);
1226 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001227 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 + ": " + p);
1229 if (p != null) {
1230 return generatePackageInfo(p, flags);
1231 }
1232 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1233 return generatePackageInfoFromSettingsLP(packageName, flags);
1234 }
1235 }
1236 return null;
1237 }
1238
Dianne Hackborn47096932010-02-11 15:57:09 -08001239 public String[] currentToCanonicalPackageNames(String[] names) {
1240 String[] out = new String[names.length];
1241 synchronized (mPackages) {
1242 for (int i=names.length-1; i>=0; i--) {
1243 PackageSetting ps = mSettings.mPackages.get(names[i]);
1244 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1245 }
1246 }
1247 return out;
1248 }
1249
1250 public String[] canonicalToCurrentPackageNames(String[] names) {
1251 String[] out = new String[names.length];
1252 synchronized (mPackages) {
1253 for (int i=names.length-1; i>=0; i--) {
1254 String cur = mSettings.mRenamedPackages.get(names[i]);
1255 out[i] = cur != null ? cur : names[i];
1256 }
1257 }
1258 return out;
1259 }
1260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 public int getPackageUid(String packageName) {
1262 synchronized (mPackages) {
1263 PackageParser.Package p = mPackages.get(packageName);
1264 if(p != null) {
1265 return p.applicationInfo.uid;
1266 }
1267 PackageSetting ps = mSettings.mPackages.get(packageName);
1268 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1269 return -1;
1270 }
1271 p = ps.pkg;
1272 return p != null ? p.applicationInfo.uid : -1;
1273 }
1274 }
1275
1276 public int[] getPackageGids(String packageName) {
1277 synchronized (mPackages) {
1278 PackageParser.Package p = mPackages.get(packageName);
1279 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001280 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 + ": " + p);
1282 if (p != null) {
1283 final PackageSetting ps = (PackageSetting)p.mExtras;
1284 final SharedUserSetting suid = ps.sharedUser;
1285 return suid != null ? suid.gids : ps.gids;
1286 }
1287 }
1288 // stupid thing to indicate an error.
1289 return new int[0];
1290 }
1291
1292 public PermissionInfo getPermissionInfo(String name, int flags) {
1293 synchronized (mPackages) {
1294 final BasePermission p = mSettings.mPermissions.get(name);
1295 if (p != null && p.perm != null) {
1296 return PackageParser.generatePermissionInfo(p.perm, flags);
1297 }
1298 return null;
1299 }
1300 }
1301
1302 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1303 synchronized (mPackages) {
1304 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1305 for (BasePermission p : mSettings.mPermissions.values()) {
1306 if (group == null) {
1307 if (p.perm.info.group == null) {
1308 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1309 }
1310 } else {
1311 if (group.equals(p.perm.info.group)) {
1312 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1313 }
1314 }
1315 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 if (out.size() > 0) {
1318 return out;
1319 }
1320 return mPermissionGroups.containsKey(group) ? out : null;
1321 }
1322 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1325 synchronized (mPackages) {
1326 return PackageParser.generatePermissionGroupInfo(
1327 mPermissionGroups.get(name), flags);
1328 }
1329 }
1330
1331 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1332 synchronized (mPackages) {
1333 final int N = mPermissionGroups.size();
1334 ArrayList<PermissionGroupInfo> out
1335 = new ArrayList<PermissionGroupInfo>(N);
1336 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1337 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1338 }
1339 return out;
1340 }
1341 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1344 PackageSetting ps = mSettings.mPackages.get(packageName);
1345 if(ps != null) {
1346 if(ps.pkg == null) {
1347 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1348 if(pInfo != null) {
1349 return pInfo.applicationInfo;
1350 }
1351 return null;
1352 }
1353 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1354 }
1355 return null;
1356 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1359 PackageSetting ps = mSettings.mPackages.get(packageName);
1360 if(ps != null) {
1361 if(ps.pkg == null) {
1362 ps.pkg = new PackageParser.Package(packageName);
1363 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001364 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1365 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1366 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1367 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 }
1369 return generatePackageInfo(ps.pkg, flags);
1370 }
1371 return null;
1372 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1375 synchronized (mPackages) {
1376 PackageParser.Package p = mPackages.get(packageName);
1377 if (Config.LOGV) Log.v(
1378 TAG, "getApplicationInfo " + packageName
1379 + ": " + p);
1380 if (p != null) {
1381 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001382 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 }
1384 if ("android".equals(packageName)||"system".equals(packageName)) {
1385 return mAndroidApplication;
1386 }
1387 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1388 return generateApplicationInfoFromSettingsLP(packageName, flags);
1389 }
1390 }
1391 return null;
1392 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001393
1394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1396 mContext.enforceCallingOrSelfPermission(
1397 android.Manifest.permission.CLEAR_APP_CACHE, null);
1398 // Queue up an async operation since clearing cache may take a little while.
1399 mHandler.post(new Runnable() {
1400 public void run() {
1401 mHandler.removeCallbacks(this);
1402 int retCode = -1;
1403 if (mInstaller != null) {
1404 retCode = mInstaller.freeCache(freeStorageSize);
1405 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001406 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 }
1408 } //end if mInstaller
1409 if (observer != null) {
1410 try {
1411 observer.onRemoveCompleted(null, (retCode >= 0));
1412 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001413 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 }
1415 }
1416 }
1417 });
1418 }
1419
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001420 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001421 mContext.enforceCallingOrSelfPermission(
1422 android.Manifest.permission.CLEAR_APP_CACHE, null);
1423 // Queue up an async operation since clearing cache may take a little while.
1424 mHandler.post(new Runnable() {
1425 public void run() {
1426 mHandler.removeCallbacks(this);
1427 int retCode = -1;
1428 if (mInstaller != null) {
1429 retCode = mInstaller.freeCache(freeStorageSize);
1430 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001431 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001432 }
1433 }
1434 if(pi != null) {
1435 try {
1436 // Callback via pending intent
1437 int code = (retCode >= 0) ? 1 : 0;
1438 pi.sendIntent(null, code, null,
1439 null, null);
1440 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001441 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001442 }
1443 }
1444 }
1445 });
1446 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1449 synchronized (mPackages) {
1450 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001451
1452 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001454 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 }
1456 if (mResolveComponentName.equals(component)) {
1457 return mResolveActivity;
1458 }
1459 }
1460 return null;
1461 }
1462
1463 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1464 synchronized (mPackages) {
1465 PackageParser.Activity a = mReceivers.mActivities.get(component);
1466 if (Config.LOGV) Log.v(
1467 TAG, "getReceiverInfo " + component + ": " + a);
1468 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1469 return PackageParser.generateActivityInfo(a, flags);
1470 }
1471 }
1472 return null;
1473 }
1474
1475 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1476 synchronized (mPackages) {
1477 PackageParser.Service s = mServices.mServices.get(component);
1478 if (Config.LOGV) Log.v(
1479 TAG, "getServiceInfo " + component + ": " + s);
1480 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1481 return PackageParser.generateServiceInfo(s, flags);
1482 }
1483 }
1484 return null;
1485 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 public String[] getSystemSharedLibraryNames() {
1488 Set<String> libSet;
1489 synchronized (mPackages) {
1490 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001491 int size = libSet.size();
1492 if (size > 0) {
1493 String[] libs = new String[size];
1494 libSet.toArray(libs);
1495 return libs;
1496 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001498 return null;
1499 }
1500
1501 public FeatureInfo[] getSystemAvailableFeatures() {
1502 Collection<FeatureInfo> featSet;
1503 synchronized (mPackages) {
1504 featSet = mAvailableFeatures.values();
1505 int size = featSet.size();
1506 if (size > 0) {
1507 FeatureInfo[] features = new FeatureInfo[size+1];
1508 featSet.toArray(features);
1509 FeatureInfo fi = new FeatureInfo();
1510 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1511 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1512 features[size] = fi;
1513 return features;
1514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
1516 return null;
1517 }
1518
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001519 public boolean hasSystemFeature(String name) {
1520 synchronized (mPackages) {
1521 return mAvailableFeatures.containsKey(name);
1522 }
1523 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 public int checkPermission(String permName, String pkgName) {
1526 synchronized (mPackages) {
1527 PackageParser.Package p = mPackages.get(pkgName);
1528 if (p != null && p.mExtras != null) {
1529 PackageSetting ps = (PackageSetting)p.mExtras;
1530 if (ps.sharedUser != null) {
1531 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1532 return PackageManager.PERMISSION_GRANTED;
1533 }
1534 } else if (ps.grantedPermissions.contains(permName)) {
1535 return PackageManager.PERMISSION_GRANTED;
1536 }
1537 }
1538 }
1539 return PackageManager.PERMISSION_DENIED;
1540 }
1541
1542 public int checkUidPermission(String permName, int uid) {
1543 synchronized (mPackages) {
1544 Object obj = mSettings.getUserIdLP(uid);
1545 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001546 GrantedPermissions gp = (GrantedPermissions)obj;
1547 if (gp.grantedPermissions.contains(permName)) {
1548 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 }
1550 } else {
1551 HashSet<String> perms = mSystemPermissions.get(uid);
1552 if (perms != null && perms.contains(permName)) {
1553 return PackageManager.PERMISSION_GRANTED;
1554 }
1555 }
1556 }
1557 return PackageManager.PERMISSION_DENIED;
1558 }
1559
1560 private BasePermission findPermissionTreeLP(String permName) {
1561 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1562 if (permName.startsWith(bp.name) &&
1563 permName.length() > bp.name.length() &&
1564 permName.charAt(bp.name.length()) == '.') {
1565 return bp;
1566 }
1567 }
1568 return null;
1569 }
1570
1571 private BasePermission checkPermissionTreeLP(String permName) {
1572 if (permName != null) {
1573 BasePermission bp = findPermissionTreeLP(permName);
1574 if (bp != null) {
1575 if (bp.uid == Binder.getCallingUid()) {
1576 return bp;
1577 }
1578 throw new SecurityException("Calling uid "
1579 + Binder.getCallingUid()
1580 + " is not allowed to add to permission tree "
1581 + bp.name + " owned by uid " + bp.uid);
1582 }
1583 }
1584 throw new SecurityException("No permission tree found for " + permName);
1585 }
1586
1587 public boolean addPermission(PermissionInfo info) {
1588 synchronized (mPackages) {
1589 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1590 throw new SecurityException("Label must be specified in permission");
1591 }
1592 BasePermission tree = checkPermissionTreeLP(info.name);
1593 BasePermission bp = mSettings.mPermissions.get(info.name);
1594 boolean added = bp == null;
1595 if (added) {
1596 bp = new BasePermission(info.name, tree.sourcePackage,
1597 BasePermission.TYPE_DYNAMIC);
1598 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1599 throw new SecurityException(
1600 "Not allowed to modify non-dynamic permission "
1601 + info.name);
1602 }
1603 bp.perm = new PackageParser.Permission(tree.perm.owner,
1604 new PermissionInfo(info));
1605 bp.perm.info.packageName = tree.perm.info.packageName;
1606 bp.uid = tree.uid;
1607 if (added) {
1608 mSettings.mPermissions.put(info.name, bp);
1609 }
1610 mSettings.writeLP();
1611 return added;
1612 }
1613 }
1614
1615 public void removePermission(String name) {
1616 synchronized (mPackages) {
1617 checkPermissionTreeLP(name);
1618 BasePermission bp = mSettings.mPermissions.get(name);
1619 if (bp != null) {
1620 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1621 throw new SecurityException(
1622 "Not allowed to modify non-dynamic permission "
1623 + name);
1624 }
1625 mSettings.mPermissions.remove(name);
1626 mSettings.writeLP();
1627 }
1628 }
1629 }
1630
Dianne Hackborn854060af2009-07-09 18:14:31 -07001631 public boolean isProtectedBroadcast(String actionName) {
1632 synchronized (mPackages) {
1633 return mProtectedBroadcasts.contains(actionName);
1634 }
1635 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 public int checkSignatures(String pkg1, String pkg2) {
1638 synchronized (mPackages) {
1639 PackageParser.Package p1 = mPackages.get(pkg1);
1640 PackageParser.Package p2 = mPackages.get(pkg2);
1641 if (p1 == null || p1.mExtras == null
1642 || p2 == null || p2.mExtras == null) {
1643 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1644 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001645 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 }
1647 }
1648
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001649 public int checkUidSignatures(int uid1, int uid2) {
1650 synchronized (mPackages) {
1651 Signature[] s1;
1652 Signature[] s2;
1653 Object obj = mSettings.getUserIdLP(uid1);
1654 if (obj != null) {
1655 if (obj instanceof SharedUserSetting) {
1656 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1657 } else if (obj instanceof PackageSetting) {
1658 s1 = ((PackageSetting)obj).signatures.mSignatures;
1659 } else {
1660 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1661 }
1662 } else {
1663 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1664 }
1665 obj = mSettings.getUserIdLP(uid2);
1666 if (obj != null) {
1667 if (obj instanceof SharedUserSetting) {
1668 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1669 } else if (obj instanceof PackageSetting) {
1670 s2 = ((PackageSetting)obj).signatures.mSignatures;
1671 } else {
1672 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1673 }
1674 } else {
1675 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1676 }
1677 return checkSignaturesLP(s1, s2);
1678 }
1679 }
1680
1681 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1682 if (s1 == null) {
1683 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1685 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1686 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001687 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1689 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001690 final int N1 = s1.length;
1691 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 for (int i=0; i<N1; i++) {
1693 boolean match = false;
1694 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001695 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 match = true;
1697 break;
1698 }
1699 }
1700 if (!match) {
1701 return PackageManager.SIGNATURE_NO_MATCH;
1702 }
1703 }
1704 return PackageManager.SIGNATURE_MATCH;
1705 }
1706
1707 public String[] getPackagesForUid(int uid) {
1708 synchronized (mPackages) {
1709 Object obj = mSettings.getUserIdLP(uid);
1710 if (obj instanceof SharedUserSetting) {
1711 SharedUserSetting sus = (SharedUserSetting)obj;
1712 final int N = sus.packages.size();
1713 String[] res = new String[N];
1714 Iterator<PackageSetting> it = sus.packages.iterator();
1715 int i=0;
1716 while (it.hasNext()) {
1717 res[i++] = it.next().name;
1718 }
1719 return res;
1720 } else if (obj instanceof PackageSetting) {
1721 PackageSetting ps = (PackageSetting)obj;
1722 return new String[] { ps.name };
1723 }
1724 }
1725 return null;
1726 }
1727
1728 public String getNameForUid(int uid) {
1729 synchronized (mPackages) {
1730 Object obj = mSettings.getUserIdLP(uid);
1731 if (obj instanceof SharedUserSetting) {
1732 SharedUserSetting sus = (SharedUserSetting)obj;
1733 return sus.name + ":" + sus.userId;
1734 } else if (obj instanceof PackageSetting) {
1735 PackageSetting ps = (PackageSetting)obj;
1736 return ps.name;
1737 }
1738 }
1739 return null;
1740 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 public int getUidForSharedUser(String sharedUserName) {
1743 if(sharedUserName == null) {
1744 return -1;
1745 }
1746 synchronized (mPackages) {
1747 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1748 if(suid == null) {
1749 return -1;
1750 }
1751 return suid.userId;
1752 }
1753 }
1754
1755 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1756 int flags) {
1757 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001758 return chooseBestActivity(intent, resolvedType, flags, query);
1759 }
1760
Mihai Predaeae850c2009-05-13 10:13:48 +02001761 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1762 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 if (query != null) {
1764 final int N = query.size();
1765 if (N == 1) {
1766 return query.get(0);
1767 } else if (N > 1) {
1768 // If there is more than one activity with the same priority,
1769 // then let the user decide between them.
1770 ResolveInfo r0 = query.get(0);
1771 ResolveInfo r1 = query.get(1);
1772 if (false) {
1773 System.out.println(r0.activityInfo.name +
1774 "=" + r0.priority + " vs " +
1775 r1.activityInfo.name +
1776 "=" + r1.priority);
1777 }
1778 // If the first activity has a higher priority, or a different
1779 // default, then it is always desireable to pick it.
1780 if (r0.priority != r1.priority
1781 || r0.preferredOrder != r1.preferredOrder
1782 || r0.isDefault != r1.isDefault) {
1783 return query.get(0);
1784 }
1785 // If we have saved a preference for a preferred activity for
1786 // this Intent, use that.
1787 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1788 flags, query, r0.priority);
1789 if (ri != null) {
1790 return ri;
1791 }
1792 return mResolveInfo;
1793 }
1794 }
1795 return null;
1796 }
1797
1798 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1799 int flags, List<ResolveInfo> query, int priority) {
1800 synchronized (mPackages) {
1801 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1802 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001803 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1805 if (prefs != null && prefs.size() > 0) {
1806 // First figure out how good the original match set is.
1807 // We will only allow preferred activities that came
1808 // from the same match quality.
1809 int match = 0;
1810 final int N = query.size();
1811 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1812 for (int j=0; j<N; j++) {
1813 ResolveInfo ri = query.get(j);
1814 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1815 + ": 0x" + Integer.toHexString(match));
1816 if (ri.match > match) match = ri.match;
1817 }
1818 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1819 + Integer.toHexString(match));
1820 match &= IntentFilter.MATCH_CATEGORY_MASK;
1821 final int M = prefs.size();
1822 for (int i=0; i<M; i++) {
1823 PreferredActivity pa = prefs.get(i);
1824 if (pa.mMatch != match) {
1825 continue;
1826 }
1827 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1828 if (DEBUG_PREFERRED) {
1829 Log.v(TAG, "Got preferred activity:");
1830 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1831 }
1832 if (ai != null) {
1833 for (int j=0; j<N; j++) {
1834 ResolveInfo ri = query.get(j);
1835 if (!ri.activityInfo.applicationInfo.packageName
1836 .equals(ai.applicationInfo.packageName)) {
1837 continue;
1838 }
1839 if (!ri.activityInfo.name.equals(ai.name)) {
1840 continue;
1841 }
1842
1843 // Okay we found a previously set preferred app.
1844 // If the result set is different from when this
1845 // was created, we need to clear it and re-ask the
1846 // user their preference.
1847 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001848 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 + intent + " type " + resolvedType);
1850 mSettings.mPreferredActivities.removeFilter(pa);
1851 return null;
1852 }
1853
1854 // Yay!
1855 return ri;
1856 }
1857 }
1858 }
1859 }
1860 }
1861 return null;
1862 }
1863
1864 public List<ResolveInfo> queryIntentActivities(Intent intent,
1865 String resolvedType, int flags) {
1866 ComponentName comp = intent.getComponent();
1867 if (comp != null) {
1868 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1869 ActivityInfo ai = getActivityInfo(comp, flags);
1870 if (ai != null) {
1871 ResolveInfo ri = new ResolveInfo();
1872 ri.activityInfo = ai;
1873 list.add(ri);
1874 }
1875 return list;
1876 }
1877
1878 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001879 String pkgName = intent.getPackage();
1880 if (pkgName == null) {
1881 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1882 resolvedType, flags);
1883 }
1884 PackageParser.Package pkg = mPackages.get(pkgName);
1885 if (pkg != null) {
1886 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1887 resolvedType, flags, pkg.activities);
1888 }
1889 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 }
1891 }
1892
1893 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1894 Intent[] specifics, String[] specificTypes, Intent intent,
1895 String resolvedType, int flags) {
1896 final String resultsAction = intent.getAction();
1897
1898 List<ResolveInfo> results = queryIntentActivities(
1899 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1900 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1901
1902 int specificsPos = 0;
1903 int N;
1904
1905 // todo: note that the algorithm used here is O(N^2). This
1906 // isn't a problem in our current environment, but if we start running
1907 // into situations where we have more than 5 or 10 matches then this
1908 // should probably be changed to something smarter...
1909
1910 // First we go through and resolve each of the specific items
1911 // that were supplied, taking care of removing any corresponding
1912 // duplicate items in the generic resolve list.
1913 if (specifics != null) {
1914 for (int i=0; i<specifics.length; i++) {
1915 final Intent sintent = specifics[i];
1916 if (sintent == null) {
1917 continue;
1918 }
1919
1920 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1921 String action = sintent.getAction();
1922 if (resultsAction != null && resultsAction.equals(action)) {
1923 // If this action was explicitly requested, then don't
1924 // remove things that have it.
1925 action = null;
1926 }
1927 ComponentName comp = sintent.getComponent();
1928 ResolveInfo ri = null;
1929 ActivityInfo ai = null;
1930 if (comp == null) {
1931 ri = resolveIntent(
1932 sintent,
1933 specificTypes != null ? specificTypes[i] : null,
1934 flags);
1935 if (ri == null) {
1936 continue;
1937 }
1938 if (ri == mResolveInfo) {
1939 // ACK! Must do something better with this.
1940 }
1941 ai = ri.activityInfo;
1942 comp = new ComponentName(ai.applicationInfo.packageName,
1943 ai.name);
1944 } else {
1945 ai = getActivityInfo(comp, flags);
1946 if (ai == null) {
1947 continue;
1948 }
1949 }
1950
1951 // Look for any generic query activities that are duplicates
1952 // of this specific one, and remove them from the results.
1953 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1954 N = results.size();
1955 int j;
1956 for (j=specificsPos; j<N; j++) {
1957 ResolveInfo sri = results.get(j);
1958 if ((sri.activityInfo.name.equals(comp.getClassName())
1959 && sri.activityInfo.applicationInfo.packageName.equals(
1960 comp.getPackageName()))
1961 || (action != null && sri.filter.matchAction(action))) {
1962 results.remove(j);
1963 if (Config.LOGV) Log.v(
1964 TAG, "Removing duplicate item from " + j
1965 + " due to specific " + specificsPos);
1966 if (ri == null) {
1967 ri = sri;
1968 }
1969 j--;
1970 N--;
1971 }
1972 }
1973
1974 // Add this specific item to its proper place.
1975 if (ri == null) {
1976 ri = new ResolveInfo();
1977 ri.activityInfo = ai;
1978 }
1979 results.add(specificsPos, ri);
1980 ri.specificIndex = i;
1981 specificsPos++;
1982 }
1983 }
1984
1985 // Now we go through the remaining generic results and remove any
1986 // duplicate actions that are found here.
1987 N = results.size();
1988 for (int i=specificsPos; i<N-1; i++) {
1989 final ResolveInfo rii = results.get(i);
1990 if (rii.filter == null) {
1991 continue;
1992 }
1993
1994 // Iterate over all of the actions of this result's intent
1995 // filter... typically this should be just one.
1996 final Iterator<String> it = rii.filter.actionsIterator();
1997 if (it == null) {
1998 continue;
1999 }
2000 while (it.hasNext()) {
2001 final String action = it.next();
2002 if (resultsAction != null && resultsAction.equals(action)) {
2003 // If this action was explicitly requested, then don't
2004 // remove things that have it.
2005 continue;
2006 }
2007 for (int j=i+1; j<N; j++) {
2008 final ResolveInfo rij = results.get(j);
2009 if (rij.filter != null && rij.filter.hasAction(action)) {
2010 results.remove(j);
2011 if (Config.LOGV) Log.v(
2012 TAG, "Removing duplicate item from " + j
2013 + " due to action " + action + " at " + i);
2014 j--;
2015 N--;
2016 }
2017 }
2018 }
2019
2020 // If the caller didn't request filter information, drop it now
2021 // so we don't have to marshall/unmarshall it.
2022 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2023 rii.filter = null;
2024 }
2025 }
2026
2027 // Filter out the caller activity if so requested.
2028 if (caller != null) {
2029 N = results.size();
2030 for (int i=0; i<N; i++) {
2031 ActivityInfo ainfo = results.get(i).activityInfo;
2032 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2033 && caller.getClassName().equals(ainfo.name)) {
2034 results.remove(i);
2035 break;
2036 }
2037 }
2038 }
2039
2040 // If the caller didn't request filter information,
2041 // drop them now so we don't have to
2042 // marshall/unmarshall it.
2043 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2044 N = results.size();
2045 for (int i=0; i<N; i++) {
2046 results.get(i).filter = null;
2047 }
2048 }
2049
2050 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2051 return results;
2052 }
2053
2054 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2055 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002056 ComponentName comp = intent.getComponent();
2057 if (comp != null) {
2058 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2059 ActivityInfo ai = getReceiverInfo(comp, flags);
2060 if (ai != null) {
2061 ResolveInfo ri = new ResolveInfo();
2062 ri.activityInfo = ai;
2063 list.add(ri);
2064 }
2065 return list;
2066 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002069 String pkgName = intent.getPackage();
2070 if (pkgName == null) {
2071 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2072 resolvedType, flags);
2073 }
2074 PackageParser.Package pkg = mPackages.get(pkgName);
2075 if (pkg != null) {
2076 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2077 resolvedType, flags, pkg.receivers);
2078 }
2079 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 }
2081 }
2082
2083 public ResolveInfo resolveService(Intent intent, String resolvedType,
2084 int flags) {
2085 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2086 flags);
2087 if (query != null) {
2088 if (query.size() >= 1) {
2089 // If there is more than one service with the same priority,
2090 // just arbitrarily pick the first one.
2091 return query.get(0);
2092 }
2093 }
2094 return null;
2095 }
2096
2097 public List<ResolveInfo> queryIntentServices(Intent intent,
2098 String resolvedType, int flags) {
2099 ComponentName comp = intent.getComponent();
2100 if (comp != null) {
2101 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2102 ServiceInfo si = getServiceInfo(comp, flags);
2103 if (si != null) {
2104 ResolveInfo ri = new ResolveInfo();
2105 ri.serviceInfo = si;
2106 list.add(ri);
2107 }
2108 return list;
2109 }
2110
2111 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002112 String pkgName = intent.getPackage();
2113 if (pkgName == null) {
2114 return (List<ResolveInfo>)mServices.queryIntent(intent,
2115 resolvedType, flags);
2116 }
2117 PackageParser.Package pkg = mPackages.get(pkgName);
2118 if (pkg != null) {
2119 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2120 resolvedType, flags, pkg.services);
2121 }
2122 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 }
2124 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 public List<PackageInfo> getInstalledPackages(int flags) {
2127 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2128
2129 synchronized (mPackages) {
2130 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2131 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2132 while (i.hasNext()) {
2133 final PackageSetting ps = i.next();
2134 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2135 if(psPkg != null) {
2136 finalList.add(psPkg);
2137 }
2138 }
2139 }
2140 else {
2141 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2142 while (i.hasNext()) {
2143 final PackageParser.Package p = i.next();
2144 if (p.applicationInfo != null) {
2145 PackageInfo pi = generatePackageInfo(p, flags);
2146 if(pi != null) {
2147 finalList.add(pi);
2148 }
2149 }
2150 }
2151 }
2152 }
2153 return finalList;
2154 }
2155
2156 public List<ApplicationInfo> getInstalledApplications(int flags) {
2157 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2158 synchronized(mPackages) {
2159 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2160 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2161 while (i.hasNext()) {
2162 final PackageSetting ps = i.next();
2163 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2164 if(ai != null) {
2165 finalList.add(ai);
2166 }
2167 }
2168 }
2169 else {
2170 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2171 while (i.hasNext()) {
2172 final PackageParser.Package p = i.next();
2173 if (p.applicationInfo != null) {
2174 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2175 if(ai != null) {
2176 finalList.add(ai);
2177 }
2178 }
2179 }
2180 }
2181 }
2182 return finalList;
2183 }
2184
2185 public List<ApplicationInfo> getPersistentApplications(int flags) {
2186 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2187
2188 synchronized (mPackages) {
2189 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2190 while (i.hasNext()) {
2191 PackageParser.Package p = i.next();
2192 if (p.applicationInfo != null
2193 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2194 && (!mSafeMode || (p.applicationInfo.flags
2195 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2196 finalList.add(p.applicationInfo);
2197 }
2198 }
2199 }
2200
2201 return finalList;
2202 }
2203
2204 public ProviderInfo resolveContentProvider(String name, int flags) {
2205 synchronized (mPackages) {
2206 final PackageParser.Provider provider = mProviders.get(name);
2207 return provider != null
2208 && mSettings.isEnabledLP(provider.info, flags)
2209 && (!mSafeMode || (provider.info.applicationInfo.flags
2210 &ApplicationInfo.FLAG_SYSTEM) != 0)
2211 ? PackageParser.generateProviderInfo(provider, flags)
2212 : null;
2213 }
2214 }
2215
Fred Quintana718d8a22009-04-29 17:53:20 -07002216 /**
2217 * @deprecated
2218 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002219 public void querySyncProviders(List outNames, List outInfo) {
2220 synchronized (mPackages) {
2221 Iterator<Map.Entry<String, PackageParser.Provider>> i
2222 = mProviders.entrySet().iterator();
2223
2224 while (i.hasNext()) {
2225 Map.Entry<String, PackageParser.Provider> entry = i.next();
2226 PackageParser.Provider p = entry.getValue();
2227
2228 if (p.syncable
2229 && (!mSafeMode || (p.info.applicationInfo.flags
2230 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2231 outNames.add(entry.getKey());
2232 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2233 }
2234 }
2235 }
2236 }
2237
2238 public List<ProviderInfo> queryContentProviders(String processName,
2239 int uid, int flags) {
2240 ArrayList<ProviderInfo> finalList = null;
2241
2242 synchronized (mPackages) {
2243 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2244 while (i.hasNext()) {
2245 PackageParser.Provider p = i.next();
2246 if (p.info.authority != null
2247 && (processName == null ||
2248 (p.info.processName.equals(processName)
2249 && p.info.applicationInfo.uid == uid))
2250 && mSettings.isEnabledLP(p.info, flags)
2251 && (!mSafeMode || (p.info.applicationInfo.flags
2252 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2253 if (finalList == null) {
2254 finalList = new ArrayList<ProviderInfo>(3);
2255 }
2256 finalList.add(PackageParser.generateProviderInfo(p,
2257 flags));
2258 }
2259 }
2260 }
2261
2262 if (finalList != null) {
2263 Collections.sort(finalList, mProviderInitOrderSorter);
2264 }
2265
2266 return finalList;
2267 }
2268
2269 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2270 int flags) {
2271 synchronized (mPackages) {
2272 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2273 return PackageParser.generateInstrumentationInfo(i, flags);
2274 }
2275 }
2276
2277 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2278 int flags) {
2279 ArrayList<InstrumentationInfo> finalList =
2280 new ArrayList<InstrumentationInfo>();
2281
2282 synchronized (mPackages) {
2283 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2284 while (i.hasNext()) {
2285 PackageParser.Instrumentation p = i.next();
2286 if (targetPackage == null
2287 || targetPackage.equals(p.info.targetPackage)) {
2288 finalList.add(PackageParser.generateInstrumentationInfo(p,
2289 flags));
2290 }
2291 }
2292 }
2293
2294 return finalList;
2295 }
2296
2297 private void scanDirLI(File dir, int flags, int scanMode) {
2298 Log.d(TAG, "Scanning app dir " + dir);
2299
2300 String[] files = dir.list();
2301
2302 int i;
2303 for (i=0; i<files.length; i++) {
2304 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002305 if (!isPackageFilename(files[i])) {
2306 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002307 continue;
2308 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002309 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002311 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002312 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2313 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002314 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002315 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002316 file.delete();
2317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 }
2319 }
2320
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002321 private static File getSettingsProblemFile() {
2322 File dataDir = Environment.getDataDirectory();
2323 File systemDir = new File(dataDir, "system");
2324 File fname = new File(systemDir, "uiderrors.txt");
2325 return fname;
2326 }
2327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328 private static void reportSettingsProblem(int priority, String msg) {
2329 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002330 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331 FileOutputStream out = new FileOutputStream(fname, true);
2332 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002333 SimpleDateFormat formatter = new SimpleDateFormat();
2334 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2335 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336 pw.close();
2337 FileUtils.setPermissions(
2338 fname.toString(),
2339 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2340 -1, -1);
2341 } catch (java.io.IOException e) {
2342 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002343 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002344 }
2345
2346 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2347 PackageParser.Package pkg, File srcFile, int parseFlags) {
2348 if (GET_CERTIFICATES) {
2349 if (ps == null || !ps.codePath.equals(srcFile)
2350 || ps.getTimeStamp() != srcFile.lastModified()) {
2351 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2352 if (!pp.collectCertificates(pkg, parseFlags)) {
2353 mLastScanError = pp.getParseError();
2354 return false;
2355 }
2356 }
2357 }
2358 return true;
2359 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 /*
2362 * Scan a package and return the newly parsed package.
2363 * Returns null in case of errors and the error code is stored in mLastScanError
2364 */
2365 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002366 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002368 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002370 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002372 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002373 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374 if (pkg == null) {
2375 mLastScanError = pp.getParseError();
2376 return null;
2377 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002378 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 PackageSetting updatedPkg;
2380 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002381 // Look to see if we already know about this package.
2382 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002383 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002384 // This package has been renamed to its original name. Let's
2385 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002386 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002387 }
2388 // If there was no original package, see one for the real package name.
2389 if (ps == null) {
2390 ps = mSettings.peekPackageLP(pkg.packageName);
2391 }
2392 // Check to see if this package could be hiding/updating a system
2393 // package. Must look for it either under the original or real
2394 // package name depending on our state.
2395 updatedPkg = mSettings.mDisabledSysPackages.get(
2396 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002398 // First check if this is a system package that may involve an update
2399 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2400 if (!ps.codePath.equals(scanFile)) {
2401 // The path has changed from what was last scanned... check the
2402 // version of the new path against what we have stored to determine
2403 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002404 if (pkg.mVersionCode < ps.versionCode) {
2405 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002406 // Ignore entry. Skip it.
2407 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2408 + "ignored: updated version " + ps.versionCode
2409 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002410 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2411 return null;
2412 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002413 // The current app on the system partion is better than
2414 // what we have updated to on the data partition; switch
2415 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002416 // At this point, its safely assumed that package installation for
2417 // apps in system partition will go through. If not there won't be a working
2418 // version of the app
2419 synchronized (mPackages) {
2420 // Just remove the loaded entries from package lists.
2421 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002422 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002423 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002424 + "reverting from " + ps.codePathString
2425 + ": new version " + pkg.mVersionCode
2426 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002427 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2428 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002429 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002430 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002431 }
2432 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002433 if (updatedPkg != null) {
2434 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2435 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2436 }
2437 // Verify certificates against what was last scanned
2438 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002439 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002440 return null;
2441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 // The apk is forward locked (not public) if its code and resources
2443 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002444 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002445 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002446 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002447 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002448
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002449 String codePath = null;
2450 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002451 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2452 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002453 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002454 } else {
2455 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002456 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002457 }
2458 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002459 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002460 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002461 codePath = pkg.mScanPath;
2462 // Set application objects path explicitly.
2463 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002464 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002465 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002466 }
2467
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002468 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2469 String destCodePath, String destResPath) {
2470 pkg.mPath = pkg.mScanPath = destCodePath;
2471 pkg.applicationInfo.sourceDir = destCodePath;
2472 pkg.applicationInfo.publicSourceDir = destResPath;
2473 }
2474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002475 private static String fixProcessName(String defProcessName,
2476 String processName, int uid) {
2477 if (processName == null) {
2478 return defProcessName;
2479 }
2480 return processName;
2481 }
2482
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002483 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2485 if (pkg.mSignatures != null) {
2486 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2487 updateSignature)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002488 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 + " signatures do not match the previously installed version; ignoring!");
2490 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2491 return false;
2492 }
2493
2494 if (pkgSetting.sharedUser != null) {
2495 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2496 pkg.mSignatures, updateSignature)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002497 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 + " has no signatures that match those in shared user "
2499 + pkgSetting.sharedUser.name + "; ignoring!");
2500 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2501 return false;
2502 }
2503 }
2504 } else {
2505 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2506 }
2507 return true;
2508 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002509
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002510 public boolean performDexOpt(String packageName) {
2511 if (!mNoDexOpt) {
2512 return false;
2513 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002514
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002515 PackageParser.Package p;
2516 synchronized (mPackages) {
2517 p = mPackages.get(packageName);
2518 if (p == null || p.mDidDexOpt) {
2519 return false;
2520 }
2521 }
2522 synchronized (mInstallLock) {
2523 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2524 }
2525 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002526
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002527 static final int DEX_OPT_SKIPPED = 0;
2528 static final int DEX_OPT_PERFORMED = 1;
2529 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002530
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002531 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2532 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002533 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002534 String path = pkg.mScanPath;
2535 int ret = 0;
2536 try {
2537 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002538 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002539 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002540 pkg.mDidDexOpt = true;
2541 performed = true;
2542 }
2543 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002544 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002545 ret = -1;
2546 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002547 Slog.w(TAG, "Exception reading apk: " + path, e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002548 ret = -1;
2549 }
2550 if (ret < 0) {
2551 //error from installer
2552 return DEX_OPT_FAILED;
2553 }
2554 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002555
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002556 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2557 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002558
2559 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2560 return Environment.isEncryptedFilesystemEnabled() &&
2561 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2562 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002563
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002564 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2565 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002566 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002567 + " to " + newPkg.packageName
2568 + ": old package not in system partition");
2569 return false;
2570 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002571 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002572 + " to " + newPkg.packageName
2573 + ": old package still exists");
2574 return false;
2575 }
2576 return true;
2577 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002578
2579 private File getDataPathForPackage(PackageParser.Package pkg) {
2580 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2581 File dataPath;
2582 if (useEncryptedFSDir) {
2583 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2584 } else {
2585 dataPath = new File(mAppDataDir, pkg.packageName);
2586 }
2587 return dataPath;
2588 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002589
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002590 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2591 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002592 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002593 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2594 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002595 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002596 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002597 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2598 return null;
2599 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 mScanningPath = scanFile;
2601 if (pkg == null) {
2602 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2603 return null;
2604 }
2605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2607 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2608 }
2609
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002610 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 synchronized (mPackages) {
2612 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002613 Slog.w(TAG, "*************************************************");
2614 Slog.w(TAG, "Core android package being redefined. Skipping.");
2615 Slog.w(TAG, " file=" + mScanningPath);
2616 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2618 return null;
2619 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 // Set up information for our fall-back user intent resolution
2622 // activity.
2623 mPlatformPackage = pkg;
2624 pkg.mVersionCode = mSdkVersion;
2625 mAndroidApplication = pkg.applicationInfo;
2626 mResolveActivity.applicationInfo = mAndroidApplication;
2627 mResolveActivity.name = ResolverActivity.class.getName();
2628 mResolveActivity.packageName = mAndroidApplication.packageName;
2629 mResolveActivity.processName = mAndroidApplication.processName;
2630 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2631 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2632 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2633 mResolveActivity.exported = true;
2634 mResolveActivity.enabled = true;
2635 mResolveInfo.activityInfo = mResolveActivity;
2636 mResolveInfo.priority = 0;
2637 mResolveInfo.preferredOrder = 0;
2638 mResolveInfo.match = 0;
2639 mResolveComponentName = new ComponentName(
2640 mAndroidApplication.packageName, mResolveActivity.name);
2641 }
2642 }
2643
2644 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002645 TAG, "Scanning package " + pkg.packageName);
2646 if (mPackages.containsKey(pkg.packageName)
2647 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002648 Slog.w(TAG, "*************************************************");
2649 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002651 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2653 return null;
2654 }
2655
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002656 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002657 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2658 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 SharedUserSetting suid = null;
2661 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002664
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002665 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2666 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002667 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002668 pkg.mRealPackage = null;
2669 pkg.mAdoptPermissions = null;
2670 }
2671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 synchronized (mPackages) {
2673 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002674 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2675 if (mTmpSharedLibraries == null ||
2676 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2677 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2678 }
2679 int num = 0;
2680 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2681 for (int i=0; i<N; i++) {
2682 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002684 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002686 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2688 return null;
2689 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002690 mTmpSharedLibraries[num] = file;
2691 num++;
2692 }
2693 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2694 for (int i=0; i<N; i++) {
2695 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2696 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002697 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002698 + " desires unavailable shared library "
2699 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2700 } else {
2701 mTmpSharedLibraries[num] = file;
2702 num++;
2703 }
2704 }
2705 if (num > 0) {
2706 pkg.usesLibraryFiles = new String[num];
2707 System.arraycopy(mTmpSharedLibraries, 0,
2708 pkg.usesLibraryFiles, 0, num);
2709 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002710
Dianne Hackborn49237342009-08-27 20:08:01 -07002711 if (pkg.reqFeatures != null) {
2712 N = pkg.reqFeatures.size();
2713 for (int i=0; i<N; i++) {
2714 FeatureInfo fi = pkg.reqFeatures.get(i);
2715 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2716 // Don't care.
2717 continue;
2718 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002719
Dianne Hackborn49237342009-08-27 20:08:01 -07002720 if (fi.name != null) {
2721 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002722 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002723 + " requires unavailable feature "
2724 + fi.name + "; failing!");
2725 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2726 return null;
2727 }
2728 }
2729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730 }
2731 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 if (pkg.mSharedUserId != null) {
2734 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2735 pkg.applicationInfo.flags, true);
2736 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002737 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738 + " for shared user failed");
2739 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2740 return null;
2741 }
2742 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2743 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2744 + suid.userId + "): packages=" + suid.packages);
2745 }
2746 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002747
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002748 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002749 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002750 Log.w(TAG, "WAITING FOR DEBUGGER");
2751 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002752 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2753 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002754 }
2755 }
2756
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002757 // Check if we are renaming from an original package name.
2758 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002759 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002760 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002761 // This package may need to be renamed to a previously
2762 // installed name. Let's check on that...
2763 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002764 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002765 // This package had originally been installed as the
2766 // original name, and we have already taken care of
2767 // transitioning to the new one. Just update the new
2768 // one to continue using the old name.
2769 realName = pkg.mRealPackage;
2770 if (!pkg.packageName.equals(renamed)) {
2771 // Callers into this function may have already taken
2772 // care of renaming the package; only do it here if
2773 // it is not already done.
2774 pkg.setPackageName(renamed);
2775 }
2776
Dianne Hackbornc1552392010-03-03 16:19:01 -08002777 } else {
2778 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2779 if ((origPackage=mSettings.peekPackageLP(
2780 pkg.mOriginalPackages.get(i))) != null) {
2781 // We do have the package already installed under its
2782 // original name... should we use it?
2783 if (!verifyPackageUpdate(origPackage, pkg)) {
2784 // New package is not compatible with original.
2785 origPackage = null;
2786 continue;
2787 } else if (origPackage.sharedUser != null) {
2788 // Make sure uid is compatible between packages.
2789 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002790 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002791 + " to " + pkg.packageName + ": old uid "
2792 + origPackage.sharedUser.name
2793 + " differs from " + pkg.mSharedUserId);
2794 origPackage = null;
2795 continue;
2796 }
2797 } else {
2798 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2799 + pkg.packageName + " to old name " + origPackage.name);
2800 }
2801 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002802 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002803 }
2804 }
2805 }
2806
2807 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002808 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002809 + " was transferred to another, but its .apk remains");
2810 }
2811
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002812 // Just create the setting, don't add it yet. For already existing packages
2813 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002814 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 destResourceFile, pkg.applicationInfo.flags, true, false);
2816 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002817 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2819 return null;
2820 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002821
2822 if (pkgSetting.origPackage != null) {
2823 // If we are first transitioning from an original package,
2824 // fix up the new package's name now. We need to do this after
2825 // looking up the package under its new name, so getPackageLP
2826 // can take care of fiddling things correctly.
2827 pkg.setPackageName(origPackage.name);
2828
2829 // File a report about this.
2830 String msg = "New package " + pkgSetting.realName
2831 + " renamed to replace old package " + pkgSetting.name;
2832 reportSettingsProblem(Log.WARN, msg);
2833
2834 // Make a note of it.
2835 mTransferedPackages.add(origPackage.name);
2836
2837 // No longer need to retain this.
2838 pkgSetting.origPackage = null;
2839 }
2840
2841 if (realName != null) {
2842 // Make a note of it.
2843 mTransferedPackages.add(pkg.packageName);
2844 }
2845
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002846 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002847 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2848 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 pkg.applicationInfo.uid = pkgSetting.userId;
2851 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002852
2853 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002854 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2855 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2856 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2857 return null;
2858 }
2859 // The signature has changed, but this package is in the system
2860 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002861 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 // However... if this package is part of a shared user, but it
2863 // doesn't match the signature of the shared user, let's fail.
2864 // What this means is that you can't change the signatures
2865 // associated with an overall shared user, which doesn't seem all
2866 // that unreasonable.
2867 if (pkgSetting.sharedUser != null) {
2868 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2869 pkg.mSignatures, false)) {
2870 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2871 return null;
2872 }
2873 }
2874 removeExisting = true;
2875 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002876
The Android Open Source Project10592532009-03-18 17:39:46 -07002877 // Verify that this new package doesn't have any content providers
2878 // that conflict with existing packages. Only do this if the
2879 // package isn't already installed, since we don't want to break
2880 // things that are installed.
2881 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2882 int N = pkg.providers.size();
2883 int i;
2884 for (i=0; i<N; i++) {
2885 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08002886 if (p.info.authority != null) {
2887 String names[] = p.info.authority.split(";");
2888 for (int j = 0; j < names.length; j++) {
2889 if (mProviders.containsKey(names[j])) {
2890 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002891 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08002892 " (in package " + pkg.applicationInfo.packageName +
2893 ") is already used by "
2894 + ((other != null && other.getComponentName() != null)
2895 ? other.getComponentName().getPackageName() : "?"));
2896 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2897 return null;
2898 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002899 }
2900 }
2901 }
2902 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 }
2904
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002905 final String pkgName = pkg.packageName;
2906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002908 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002910 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002911 if (ret != 0) {
2912 String msg = "System package " + pkg.packageName
2913 + " could not have data directory erased after signature change.";
2914 reportSettingsProblem(Log.WARN, msg);
2915 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2916 return null;
2917 }
2918 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002919 Slog.w(TAG, "System package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002920 + " signature changed: existing data removed.");
2921 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2922 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002923
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002924 if (pkg.mAdoptPermissions != null) {
2925 // This package wants to adopt ownership of permissions from
2926 // another package.
2927 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2928 String origName = pkg.mAdoptPermissions.get(i);
2929 PackageSetting orig = mSettings.peekPackageLP(origName);
2930 if (orig != null) {
2931 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002932 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002933 + origName + " to " + pkg.packageName);
2934 mSettings.transferPermissions(origName, pkg.packageName);
2935 }
2936 }
2937 }
2938 }
2939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 long scanFileTime = scanFile.lastModified();
2941 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2942 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2943 pkg.applicationInfo.processName = fixProcessName(
2944 pkg.applicationInfo.packageName,
2945 pkg.applicationInfo.processName,
2946 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947
2948 File dataPath;
2949 if (mPlatformPackage == pkg) {
2950 // The system package is special.
2951 dataPath = new File (Environment.getDataDirectory(), "system");
2952 pkg.applicationInfo.dataDir = dataPath.getPath();
2953 } else {
2954 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002955 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002956 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002957
2958 boolean uidError = false;
2959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 if (dataPath.exists()) {
2961 mOutPermissions[1] = 0;
2962 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2963 if (mOutPermissions[1] == pkg.applicationInfo.uid
2964 || !Process.supportsProcesses()) {
2965 pkg.applicationInfo.dataDir = dataPath.getPath();
2966 } else {
2967 boolean recovered = false;
2968 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2969 // If this is a system app, we can at least delete its
2970 // current data so the application will still work.
2971 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002972 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002973 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 // Old data gone!
2975 String msg = "System package " + pkg.packageName
2976 + " has changed from uid: "
2977 + mOutPermissions[1] + " to "
2978 + pkg.applicationInfo.uid + "; old data erased";
2979 reportSettingsProblem(Log.WARN, msg);
2980 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002983 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984 pkg.applicationInfo.uid);
2985 if (ret == -1) {
2986 // Ack should not happen!
2987 msg = "System package " + pkg.packageName
2988 + " could not have data directory re-created after delete.";
2989 reportSettingsProblem(Log.WARN, msg);
2990 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2991 return null;
2992 }
2993 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002994 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002995 if (!recovered) {
2996 mHasSystemUidErrors = true;
2997 }
2998 }
2999 if (!recovered) {
3000 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3001 + pkg.applicationInfo.uid + "/fs_"
3002 + mOutPermissions[1];
3003 String msg = "Package " + pkg.packageName
3004 + " has mismatched uid: "
3005 + mOutPermissions[1] + " on disk, "
3006 + pkg.applicationInfo.uid + " in settings";
3007 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003008 mSettings.mReadMessages.append(msg);
3009 mSettings.mReadMessages.append('\n');
3010 uidError = true;
3011 if (!pkgSetting.uidError) {
3012 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003013 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003014 }
3015 }
3016 }
3017 pkg.applicationInfo.dataDir = dataPath.getPath();
3018 } else {
3019 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3020 Log.v(TAG, "Want this data dir: " + dataPath);
3021 //invoke installer to do the actual installation
3022 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003023 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003024 pkg.applicationInfo.uid);
3025 if(ret < 0) {
3026 // Error from installer
3027 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3028 return null;
3029 }
3030 } else {
3031 dataPath.mkdirs();
3032 if (dataPath.exists()) {
3033 FileUtils.setPermissions(
3034 dataPath.toString(),
3035 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3036 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3037 }
3038 }
3039 if (dataPath.exists()) {
3040 pkg.applicationInfo.dataDir = dataPath.getPath();
3041 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003042 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003043 pkg.applicationInfo.dataDir = null;
3044 }
3045 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003046
3047 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 }
3049
3050 // Perform shared library installation and dex validation and
3051 // optimization, if this is not a system app.
3052 if (mInstaller != null) {
3053 String path = scanFile.getPath();
3054 if (scanFileNewer) {
3055 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003056 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3057 if (err != PackageManager.INSTALL_SUCCEEDED) {
3058 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003059 return null;
3060 }
3061 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003062 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003063
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003064 if ((scanMode&SCAN_NO_DEX) == 0) {
3065 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003066 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3067 return null;
3068 }
3069 }
3070 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003072 if (mFactoryTest && pkg.requestedPermissions.contains(
3073 android.Manifest.permission.FACTORY_TEST)) {
3074 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3075 }
3076
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003077 // Request the ActivityManager to kill the process(only for existing packages)
3078 // so that we do not end up in a confused state while the user is still using the older
3079 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003080 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003081 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003082 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003083 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003085 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003086 // We don't expect installation to fail beyond this point,
3087 if ((scanMode&SCAN_MONITOR) != 0) {
3088 mAppDirs.put(pkg.mPath, pkg);
3089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003091 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003093 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003094 // Make sure we don't accidentally delete its data.
3095 mSettings.mPackagesToBeCleaned.remove(pkgName);
3096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 int N = pkg.providers.size();
3098 StringBuilder r = null;
3099 int i;
3100 for (i=0; i<N; i++) {
3101 PackageParser.Provider p = pkg.providers.get(i);
3102 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3103 p.info.processName, pkg.applicationInfo.uid);
3104 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3105 p.info.name), p);
3106 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003107 if (p.info.authority != null) {
3108 String names[] = p.info.authority.split(";");
3109 p.info.authority = null;
3110 for (int j = 0; j < names.length; j++) {
3111 if (j == 1 && p.syncable) {
3112 // We only want the first authority for a provider to possibly be
3113 // syncable, so if we already added this provider using a different
3114 // authority clear the syncable flag. We copy the provider before
3115 // changing it because the mProviders object contains a reference
3116 // to a provider that we don't want to change.
3117 // Only do this for the second authority since the resulting provider
3118 // object can be the same for all future authorities for this provider.
3119 p = new PackageParser.Provider(p);
3120 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003121 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003122 if (!mProviders.containsKey(names[j])) {
3123 mProviders.put(names[j], p);
3124 if (p.info.authority == null) {
3125 p.info.authority = names[j];
3126 } else {
3127 p.info.authority = p.info.authority + ";" + names[j];
3128 }
3129 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3130 Log.d(TAG, "Registered content provider: " + names[j] +
3131 ", className = " + p.info.name +
3132 ", isSyncable = " + p.info.isSyncable);
3133 } else {
3134 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003135 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003136 " (in package " + pkg.applicationInfo.packageName +
3137 "): name already used by "
3138 + ((other != null && other.getComponentName() != null)
3139 ? other.getComponentName().getPackageName() : "?"));
3140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 }
3142 }
3143 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3144 if (r == null) {
3145 r = new StringBuilder(256);
3146 } else {
3147 r.append(' ');
3148 }
3149 r.append(p.info.name);
3150 }
3151 }
3152 if (r != null) {
3153 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3154 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 N = pkg.services.size();
3157 r = null;
3158 for (i=0; i<N; i++) {
3159 PackageParser.Service s = pkg.services.get(i);
3160 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3161 s.info.processName, pkg.applicationInfo.uid);
3162 mServices.addService(s);
3163 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3164 if (r == null) {
3165 r = new StringBuilder(256);
3166 } else {
3167 r.append(' ');
3168 }
3169 r.append(s.info.name);
3170 }
3171 }
3172 if (r != null) {
3173 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3174 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003176 N = pkg.receivers.size();
3177 r = null;
3178 for (i=0; i<N; i++) {
3179 PackageParser.Activity a = pkg.receivers.get(i);
3180 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3181 a.info.processName, pkg.applicationInfo.uid);
3182 mReceivers.addActivity(a, "receiver");
3183 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3184 if (r == null) {
3185 r = new StringBuilder(256);
3186 } else {
3187 r.append(' ');
3188 }
3189 r.append(a.info.name);
3190 }
3191 }
3192 if (r != null) {
3193 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3194 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196 N = pkg.activities.size();
3197 r = null;
3198 for (i=0; i<N; i++) {
3199 PackageParser.Activity a = pkg.activities.get(i);
3200 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3201 a.info.processName, pkg.applicationInfo.uid);
3202 mActivities.addActivity(a, "activity");
3203 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3204 if (r == null) {
3205 r = new StringBuilder(256);
3206 } else {
3207 r.append(' ');
3208 }
3209 r.append(a.info.name);
3210 }
3211 }
3212 if (r != null) {
3213 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3214 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003216 N = pkg.permissionGroups.size();
3217 r = null;
3218 for (i=0; i<N; i++) {
3219 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3220 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3221 if (cur == null) {
3222 mPermissionGroups.put(pg.info.name, pg);
3223 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3224 if (r == null) {
3225 r = new StringBuilder(256);
3226 } else {
3227 r.append(' ');
3228 }
3229 r.append(pg.info.name);
3230 }
3231 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003232 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003233 + pg.info.packageName + " ignored: original from "
3234 + cur.info.packageName);
3235 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3236 if (r == null) {
3237 r = new StringBuilder(256);
3238 } else {
3239 r.append(' ');
3240 }
3241 r.append("DUP:");
3242 r.append(pg.info.name);
3243 }
3244 }
3245 }
3246 if (r != null) {
3247 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3248 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250 N = pkg.permissions.size();
3251 r = null;
3252 for (i=0; i<N; i++) {
3253 PackageParser.Permission p = pkg.permissions.get(i);
3254 HashMap<String, BasePermission> permissionMap =
3255 p.tree ? mSettings.mPermissionTrees
3256 : mSettings.mPermissions;
3257 p.group = mPermissionGroups.get(p.info.group);
3258 if (p.info.group == null || p.group != null) {
3259 BasePermission bp = permissionMap.get(p.info.name);
3260 if (bp == null) {
3261 bp = new BasePermission(p.info.name, p.info.packageName,
3262 BasePermission.TYPE_NORMAL);
3263 permissionMap.put(p.info.name, bp);
3264 }
3265 if (bp.perm == null) {
3266 if (bp.sourcePackage == null
3267 || bp.sourcePackage.equals(p.info.packageName)) {
3268 BasePermission tree = findPermissionTreeLP(p.info.name);
3269 if (tree == null
3270 || tree.sourcePackage.equals(p.info.packageName)) {
3271 bp.perm = p;
3272 bp.uid = pkg.applicationInfo.uid;
3273 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3274 if (r == null) {
3275 r = new StringBuilder(256);
3276 } else {
3277 r.append(' ');
3278 }
3279 r.append(p.info.name);
3280 }
3281 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003282 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003283 + p.info.packageName + " ignored: base tree "
3284 + tree.name + " is from package "
3285 + tree.sourcePackage);
3286 }
3287 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003288 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 + p.info.packageName + " ignored: original from "
3290 + bp.sourcePackage);
3291 }
3292 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3293 if (r == null) {
3294 r = new StringBuilder(256);
3295 } else {
3296 r.append(' ');
3297 }
3298 r.append("DUP:");
3299 r.append(p.info.name);
3300 }
3301 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003302 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 + p.info.packageName + " ignored: no group "
3304 + p.group);
3305 }
3306 }
3307 if (r != null) {
3308 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3309 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311 N = pkg.instrumentation.size();
3312 r = null;
3313 for (i=0; i<N; i++) {
3314 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3315 a.info.packageName = pkg.applicationInfo.packageName;
3316 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3317 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3318 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003319 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3321 if (r == null) {
3322 r = new StringBuilder(256);
3323 } else {
3324 r.append(' ');
3325 }
3326 r.append(a.info.name);
3327 }
3328 }
3329 if (r != null) {
3330 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3331 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003332
Dianne Hackborn854060af2009-07-09 18:14:31 -07003333 if (pkg.protectedBroadcasts != null) {
3334 N = pkg.protectedBroadcasts.size();
3335 for (i=0; i<N; i++) {
3336 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3337 }
3338 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003340 pkgSetting.setTimeStamp(scanFileTime);
3341 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 return pkg;
3344 }
3345
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003346 private void killApplication(String pkgName, int uid) {
3347 // Request the ActivityManager to kill the process(only for existing packages)
3348 // so that we do not end up in a confused state while the user is still using the older
3349 // version of the application while the new one gets installed.
3350 IActivityManager am = ActivityManagerNative.getDefault();
3351 if (am != null) {
3352 try {
3353 am.killApplicationWithUid(pkgName, uid);
3354 } catch (RemoteException e) {
3355 }
3356 }
3357 }
3358
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003359 // The following constants are returned by cachePackageSharedLibsForAbiLI
3360 // to indicate if native shared libraries were found in the package.
3361 // Values are:
3362 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3363 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3364 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3365 // in package (and not installed)
3366 //
3367 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3368 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3369 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003371 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3372 // and automatically copy them to /data/data/<appname>/lib if present.
3373 //
3374 // NOTE: this method may throw an IOException if the library cannot
3375 // be copied to its final destination, e.g. if there isn't enough
3376 // room left on the data partition, or a ZipException if the package
3377 // file is malformed.
3378 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003379 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3380 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003381 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3382 final String apkLib = "lib/";
3383 final int apkLibLen = apkLib.length();
3384 final int cpuAbiLen = cpuAbi.length();
3385 final String libPrefix = "lib";
3386 final int libPrefixLen = libPrefix.length();
3387 final String libSuffix = ".so";
3388 final int libSuffixLen = libSuffix.length();
3389 boolean hasNativeLibraries = false;
3390 boolean installedNativeLibraries = false;
3391
3392 // the minimum length of a valid native shared library of the form
3393 // lib/<something>/lib<name>.so.
3394 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3395
3396 ZipFile zipFile = new ZipFile(scanFile);
3397 Enumeration<ZipEntry> entries =
3398 (Enumeration<ZipEntry>) zipFile.entries();
3399
3400 while (entries.hasMoreElements()) {
3401 ZipEntry entry = entries.nextElement();
3402 // skip directories
3403 if (entry.isDirectory()) {
3404 continue;
3405 }
3406 String entryName = entry.getName();
3407
3408 // check that the entry looks like lib/<something>/lib<name>.so
3409 // here, but don't check the ABI just yet.
3410 //
3411 // - must be sufficiently long
3412 // - must end with libSuffix, i.e. ".so"
3413 // - must start with apkLib, i.e. "lib/"
3414 if (entryName.length() < minEntryLen ||
3415 !entryName.endsWith(libSuffix) ||
3416 !entryName.startsWith(apkLib) ) {
3417 continue;
3418 }
3419
3420 // file name must start with libPrefix, i.e. "lib"
3421 int lastSlash = entryName.lastIndexOf('/');
3422
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003423 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003424 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3425 continue;
3426 }
3427
3428 hasNativeLibraries = true;
3429
3430 // check the cpuAbi now, between lib/ and /lib<name>.so
3431 //
3432 if (lastSlash != apkLibLen + cpuAbiLen ||
3433 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3434 continue;
3435
3436 // extract the library file name, ensure it doesn't contain
3437 // weird characters. we're guaranteed here that it doesn't contain
3438 // a directory separator though.
3439 String libFileName = entryName.substring(lastSlash+1);
3440 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3441 continue;
3442 }
3443
3444 installedNativeLibraries = true;
3445
3446 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3447 File.separator + libFileName;
3448 File sharedLibraryFile = new File(sharedLibraryFilePath);
3449 if (! sharedLibraryFile.exists() ||
3450 sharedLibraryFile.length() != entry.getSize() ||
3451 sharedLibraryFile.lastModified() != entry.getTime()) {
3452 if (Config.LOGD) {
3453 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003454 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003455 if (mInstaller == null) {
3456 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003457 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003458 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003459 sharedLibraryFile);
3460 }
3461 }
3462 if (!hasNativeLibraries)
3463 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3464
3465 if (!installedNativeLibraries)
3466 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3467
3468 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3469 }
3470
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003471 // Find the gdbserver executable program in a package at
3472 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3473 //
3474 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3475 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3476 //
3477 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3478 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3479 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3480 final String GDBSERVER = "gdbserver";
3481 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3482
3483 ZipFile zipFile = new ZipFile(scanFile);
3484 Enumeration<ZipEntry> entries =
3485 (Enumeration<ZipEntry>) zipFile.entries();
3486
3487 while (entries.hasMoreElements()) {
3488 ZipEntry entry = entries.nextElement();
3489 // skip directories
3490 if (entry.isDirectory()) {
3491 continue;
3492 }
3493 String entryName = entry.getName();
3494
3495 if (!entryName.equals(apkGdbServerPath)) {
3496 continue;
3497 }
3498
3499 String installGdbServerPath = installGdbServerDir.getPath() +
3500 "/" + GDBSERVER;
3501 File installGdbServerFile = new File(installGdbServerPath);
3502 if (! installGdbServerFile.exists() ||
3503 installGdbServerFile.length() != entry.getSize() ||
3504 installGdbServerFile.lastModified() != entry.getTime()) {
3505 if (Config.LOGD) {
3506 Log.d(TAG, "Caching gdbserver " + entry.getName());
3507 }
3508 if (mInstaller == null) {
3509 installGdbServerDir.mkdir();
3510 }
3511 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3512 installGdbServerFile);
3513 }
3514 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3515 }
3516 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3517 }
3518
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003519 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3520 // and copy them to /data/data/<appname>/lib.
3521 //
3522 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3523 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3524 // one if ro.product.cpu.abi2 is defined.
3525 //
3526 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3527 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003528 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003529 try {
3530 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3531
3532 // some architectures are capable of supporting several CPU ABIs
3533 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3534 // this is indicated by the definition of the ro.product.cpu.abi2
3535 // system property.
3536 //
3537 // only scan the package twice in case of ABI mismatch
3538 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003539 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003540 if (cpuAbi2 != null) {
3541 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003542 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003543
3544 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003545 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003546 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003547 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003548
3549 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3550 cpuAbi = cpuAbi2;
3551 }
3552 }
3553
3554 // for debuggable packages, also extract gdbserver from lib/<abi>
3555 // into /data/data/<appname>/lib too.
3556 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3557 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3558 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3559 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3560 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3561 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003562 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003563 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003564 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003565 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003567 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003568 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003569 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003570 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571 }
3572
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003573 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003575 File binaryDir,
3576 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 InputStream inputStream = zipFile.getInputStream(entry);
3578 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003579 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003580 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003581 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003582 // now need to be left as world readable and owned by the system.
3583 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3584 ! tempFile.setLastModified(entry.getTime()) ||
3585 FileUtils.setPermissions(tempFilePath,
3586 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003587 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003588 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003589 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003590 // Failed to properly write file.
3591 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003592 throw new IOException("Couldn't create cached binary "
3593 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003594 }
3595 } finally {
3596 inputStream.close();
3597 }
3598 }
3599
3600 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3601 if (chatty && Config.LOGD) Log.d(
3602 TAG, "Removing package " + pkg.applicationInfo.packageName );
3603
3604 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003605 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003607 mPackages.remove(pkg.applicationInfo.packageName);
3608 if (pkg.mPath != null) {
3609 mAppDirs.remove(pkg.mPath);
3610 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003612 PackageSetting ps = (PackageSetting)pkg.mExtras;
3613 if (ps != null && ps.sharedUser != null) {
3614 // XXX don't do this until the data is removed.
3615 if (false) {
3616 ps.sharedUser.packages.remove(ps);
3617 if (ps.sharedUser.packages.size() == 0) {
3618 // Remove.
3619 }
3620 }
3621 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003623 int N = pkg.providers.size();
3624 StringBuilder r = null;
3625 int i;
3626 for (i=0; i<N; i++) {
3627 PackageParser.Provider p = pkg.providers.get(i);
3628 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3629 p.info.name));
3630 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003632 /* The is another ContentProvider with this authority when
3633 * this app was installed so this authority is null,
3634 * Ignore it as we don't have to unregister the provider.
3635 */
3636 continue;
3637 }
3638 String names[] = p.info.authority.split(";");
3639 for (int j = 0; j < names.length; j++) {
3640 if (mProviders.get(names[j]) == p) {
3641 mProviders.remove(names[j]);
3642 if (chatty && Config.LOGD) Log.d(
3643 TAG, "Unregistered content provider: " + names[j] +
3644 ", className = " + p.info.name +
3645 ", isSyncable = " + p.info.isSyncable);
3646 }
3647 }
3648 if (chatty) {
3649 if (r == null) {
3650 r = new StringBuilder(256);
3651 } else {
3652 r.append(' ');
3653 }
3654 r.append(p.info.name);
3655 }
3656 }
3657 if (r != null) {
3658 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3659 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 N = pkg.services.size();
3662 r = null;
3663 for (i=0; i<N; i++) {
3664 PackageParser.Service s = pkg.services.get(i);
3665 mServices.removeService(s);
3666 if (chatty) {
3667 if (r == null) {
3668 r = new StringBuilder(256);
3669 } else {
3670 r.append(' ');
3671 }
3672 r.append(s.info.name);
3673 }
3674 }
3675 if (r != null) {
3676 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3677 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 N = pkg.receivers.size();
3680 r = null;
3681 for (i=0; i<N; i++) {
3682 PackageParser.Activity a = pkg.receivers.get(i);
3683 mReceivers.removeActivity(a, "receiver");
3684 if (chatty) {
3685 if (r == null) {
3686 r = new StringBuilder(256);
3687 } else {
3688 r.append(' ');
3689 }
3690 r.append(a.info.name);
3691 }
3692 }
3693 if (r != null) {
3694 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3695 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003697 N = pkg.activities.size();
3698 r = null;
3699 for (i=0; i<N; i++) {
3700 PackageParser.Activity a = pkg.activities.get(i);
3701 mActivities.removeActivity(a, "activity");
3702 if (chatty) {
3703 if (r == null) {
3704 r = new StringBuilder(256);
3705 } else {
3706 r.append(' ');
3707 }
3708 r.append(a.info.name);
3709 }
3710 }
3711 if (r != null) {
3712 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3713 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 N = pkg.permissions.size();
3716 r = null;
3717 for (i=0; i<N; i++) {
3718 PackageParser.Permission p = pkg.permissions.get(i);
3719 boolean tree = false;
3720 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3721 if (bp == null) {
3722 tree = true;
3723 bp = mSettings.mPermissionTrees.get(p.info.name);
3724 }
3725 if (bp != null && bp.perm == p) {
3726 if (bp.type != BasePermission.TYPE_BUILTIN) {
3727 if (tree) {
3728 mSettings.mPermissionTrees.remove(p.info.name);
3729 } else {
3730 mSettings.mPermissions.remove(p.info.name);
3731 }
3732 } else {
3733 bp.perm = null;
3734 }
3735 if (chatty) {
3736 if (r == null) {
3737 r = new StringBuilder(256);
3738 } else {
3739 r.append(' ');
3740 }
3741 r.append(p.info.name);
3742 }
3743 }
3744 }
3745 if (r != null) {
3746 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3747 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749 N = pkg.instrumentation.size();
3750 r = null;
3751 for (i=0; i<N; i++) {
3752 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003753 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003754 if (chatty) {
3755 if (r == null) {
3756 r = new StringBuilder(256);
3757 } else {
3758 r.append(' ');
3759 }
3760 r.append(a.info.name);
3761 }
3762 }
3763 if (r != null) {
3764 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3765 }
3766 }
3767 }
3768
3769 private static final boolean isPackageFilename(String name) {
3770 return name != null && name.endsWith(".apk");
3771 }
3772
3773 private void updatePermissionsLP() {
3774 // Make sure there are no dangling permission trees.
3775 Iterator<BasePermission> it = mSettings.mPermissionTrees
3776 .values().iterator();
3777 while (it.hasNext()) {
3778 BasePermission bp = it.next();
3779 if (bp.perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003780 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003781 + " from package " + bp.sourcePackage);
3782 it.remove();
3783 }
3784 }
3785
3786 // Make sure all dynamic permissions have been assigned to a package,
3787 // and make sure there are no dangling permissions.
3788 it = mSettings.mPermissions.values().iterator();
3789 while (it.hasNext()) {
3790 BasePermission bp = it.next();
3791 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3792 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3793 + bp.name + " pkg=" + bp.sourcePackage
3794 + " info=" + bp.pendingInfo);
3795 if (bp.perm == null && bp.pendingInfo != null) {
3796 BasePermission tree = findPermissionTreeLP(bp.name);
3797 if (tree != null) {
3798 bp.perm = new PackageParser.Permission(tree.perm.owner,
3799 new PermissionInfo(bp.pendingInfo));
3800 bp.perm.info.packageName = tree.perm.info.packageName;
3801 bp.perm.info.name = bp.name;
3802 bp.uid = tree.uid;
3803 }
3804 }
3805 }
3806 if (bp.perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003807 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003808 + " from package " + bp.sourcePackage);
3809 it.remove();
3810 }
3811 }
3812
3813 // Now update the permissions for all packages, in particular
3814 // replace the granted permissions of the system packages.
3815 for (PackageParser.Package pkg : mPackages.values()) {
3816 grantPermissionsLP(pkg, false);
3817 }
3818 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3821 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3822 if (ps == null) {
3823 return;
3824 }
3825 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3826 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003828 if (replace) {
3829 ps.permissionsFixed = false;
3830 if (gp == ps) {
3831 gp.grantedPermissions.clear();
3832 gp.gids = mGlobalGids;
3833 }
3834 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836 if (gp.gids == null) {
3837 gp.gids = mGlobalGids;
3838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003840 final int N = pkg.requestedPermissions.size();
3841 for (int i=0; i<N; i++) {
3842 String name = pkg.requestedPermissions.get(i);
3843 BasePermission bp = mSettings.mPermissions.get(name);
3844 PackageParser.Permission p = bp != null ? bp.perm : null;
3845 if (false) {
3846 if (gp != ps) {
3847 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3848 + ": " + p);
3849 }
3850 }
3851 if (p != null) {
3852 final String perm = p.info.name;
3853 boolean allowed;
3854 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3855 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3856 allowed = true;
3857 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3858 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003859 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003860 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003861 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003862 == PackageManager.SIGNATURE_MATCH);
3863 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3864 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3865 // For updated system applications, the signatureOrSystem permission
3866 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003867 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3869 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3870 if(sysPs.grantedPermissions.contains(perm)) {
3871 allowed = true;
3872 } else {
3873 allowed = false;
3874 }
3875 } else {
3876 allowed = true;
3877 }
3878 }
3879 }
3880 } else {
3881 allowed = false;
3882 }
3883 if (false) {
3884 if (gp != ps) {
3885 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3886 }
3887 }
3888 if (allowed) {
3889 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3890 && ps.permissionsFixed) {
3891 // If this is an existing, non-system package, then
3892 // we can't add any new permissions to it.
3893 if (!gp.loadedPermissions.contains(perm)) {
3894 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003895 // Except... if this is a permission that was added
3896 // to the platform (note: need to only do this when
3897 // updating the platform).
3898 final int NP = PackageParser.NEW_PERMISSIONS.length;
3899 for (int ip=0; ip<NP; ip++) {
3900 final PackageParser.NewPermissionInfo npi
3901 = PackageParser.NEW_PERMISSIONS[ip];
3902 if (npi.name.equals(perm)
3903 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3904 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003905 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003906 + pkg.packageName);
3907 break;
3908 }
3909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 }
3911 }
3912 if (allowed) {
3913 if (!gp.grantedPermissions.contains(perm)) {
3914 addedPermission = true;
3915 gp.grantedPermissions.add(perm);
3916 gp.gids = appendInts(gp.gids, bp.gids);
3917 }
3918 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003919 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 + " to package " + pkg.packageName
3921 + " because it was previously installed without");
3922 }
3923 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003924 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 + " to package " + pkg.packageName
3926 + " (protectionLevel=" + p.info.protectionLevel
3927 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3928 + ")");
3929 }
3930 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003931 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003932 + " in package " + pkg.packageName);
3933 }
3934 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003937 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3938 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003939 // This is the first that we have heard about this package, so the
3940 // permissions we have now selected are fixed until explicitly
3941 // changed.
3942 ps.permissionsFixed = true;
3943 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3944 }
3945 }
3946
3947 private final class ActivityIntentResolver
3948 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003949 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003951 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 }
3953
Mihai Preda074edef2009-05-18 17:13:31 +02003954 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003956 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3958 }
3959
Mihai Predaeae850c2009-05-13 10:13:48 +02003960 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3961 ArrayList<PackageParser.Activity> packageActivities) {
3962 if (packageActivities == null) {
3963 return null;
3964 }
3965 mFlags = flags;
3966 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3967 int N = packageActivities.size();
3968 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3969 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003970
3971 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003972 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003973 intentFilters = packageActivities.get(i).intents;
3974 if (intentFilters != null && intentFilters.size() > 0) {
3975 listCut.add(intentFilters);
3976 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003977 }
3978 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3979 }
3980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003981 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003982 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003983 if (SHOW_INFO || Config.LOGV) Log.v(
3984 TAG, " " + type + " " +
3985 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3986 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3987 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003988 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003989 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3990 if (SHOW_INFO || Config.LOGV) {
3991 Log.v(TAG, " IntentFilter:");
3992 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3993 }
3994 if (!intent.debugCheck()) {
3995 Log.w(TAG, "==> For Activity " + a.info.name);
3996 }
3997 addFilter(intent);
3998 }
3999 }
4000
4001 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004002 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 if (SHOW_INFO || Config.LOGV) Log.v(
4004 TAG, " " + type + " " +
4005 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4006 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4007 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004008 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4010 if (SHOW_INFO || Config.LOGV) {
4011 Log.v(TAG, " IntentFilter:");
4012 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4013 }
4014 removeFilter(intent);
4015 }
4016 }
4017
4018 @Override
4019 protected boolean allowFilterResult(
4020 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4021 ActivityInfo filterAi = filter.activity.info;
4022 for (int i=dest.size()-1; i>=0; i--) {
4023 ActivityInfo destAi = dest.get(i).activityInfo;
4024 if (destAi.name == filterAi.name
4025 && destAi.packageName == filterAi.packageName) {
4026 return false;
4027 }
4028 }
4029 return true;
4030 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032 @Override
4033 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4034 int match) {
4035 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4036 return null;
4037 }
4038 final PackageParser.Activity activity = info.activity;
4039 if (mSafeMode && (activity.info.applicationInfo.flags
4040 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4041 return null;
4042 }
4043 final ResolveInfo res = new ResolveInfo();
4044 res.activityInfo = PackageParser.generateActivityInfo(activity,
4045 mFlags);
4046 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4047 res.filter = info;
4048 }
4049 res.priority = info.getPriority();
4050 res.preferredOrder = activity.owner.mPreferredOrder;
4051 //System.out.println("Result: " + res.activityInfo.className +
4052 // " = " + res.priority);
4053 res.match = match;
4054 res.isDefault = info.hasDefault;
4055 res.labelRes = info.labelRes;
4056 res.nonLocalizedLabel = info.nonLocalizedLabel;
4057 res.icon = info.icon;
4058 return res;
4059 }
4060
4061 @Override
4062 protected void sortResults(List<ResolveInfo> results) {
4063 Collections.sort(results, mResolvePrioritySorter);
4064 }
4065
4066 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004067 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004068 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004069 out.print(prefix); out.print(
4070 Integer.toHexString(System.identityHashCode(filter.activity)));
4071 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004072 out.println(filter.activity.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004073 }
4074
4075// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4076// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4077// final List<ResolveInfo> retList = Lists.newArrayList();
4078// while (i.hasNext()) {
4079// final ResolveInfo resolveInfo = i.next();
4080// if (isEnabledLP(resolveInfo.activityInfo)) {
4081// retList.add(resolveInfo);
4082// }
4083// }
4084// return retList;
4085// }
4086
4087 // Keys are String (activity class name), values are Activity.
4088 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4089 = new HashMap<ComponentName, PackageParser.Activity>();
4090 private int mFlags;
4091 }
4092
4093 private final class ServiceIntentResolver
4094 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004095 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004096 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004097 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 }
4099
Mihai Preda074edef2009-05-18 17:13:31 +02004100 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004102 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004103 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4104 }
4105
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004106 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4107 ArrayList<PackageParser.Service> packageServices) {
4108 if (packageServices == null) {
4109 return null;
4110 }
4111 mFlags = flags;
4112 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4113 int N = packageServices.size();
4114 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4115 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4116
4117 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4118 for (int i = 0; i < N; ++i) {
4119 intentFilters = packageServices.get(i).intents;
4120 if (intentFilters != null && intentFilters.size() > 0) {
4121 listCut.add(intentFilters);
4122 }
4123 }
4124 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4125 }
4126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004127 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004128 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004129 if (SHOW_INFO || Config.LOGV) Log.v(
4130 TAG, " " + (s.info.nonLocalizedLabel != null
4131 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4132 if (SHOW_INFO || Config.LOGV) Log.v(
4133 TAG, " Class=" + s.info.name);
4134 int NI = s.intents.size();
4135 int j;
4136 for (j=0; j<NI; j++) {
4137 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4138 if (SHOW_INFO || Config.LOGV) {
4139 Log.v(TAG, " IntentFilter:");
4140 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4141 }
4142 if (!intent.debugCheck()) {
4143 Log.w(TAG, "==> For Service " + s.info.name);
4144 }
4145 addFilter(intent);
4146 }
4147 }
4148
4149 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004150 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004151 if (SHOW_INFO || Config.LOGV) Log.v(
4152 TAG, " " + (s.info.nonLocalizedLabel != null
4153 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4154 if (SHOW_INFO || Config.LOGV) Log.v(
4155 TAG, " Class=" + s.info.name);
4156 int NI = s.intents.size();
4157 int j;
4158 for (j=0; j<NI; j++) {
4159 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4160 if (SHOW_INFO || Config.LOGV) {
4161 Log.v(TAG, " IntentFilter:");
4162 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4163 }
4164 removeFilter(intent);
4165 }
4166 }
4167
4168 @Override
4169 protected boolean allowFilterResult(
4170 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4171 ServiceInfo filterSi = filter.service.info;
4172 for (int i=dest.size()-1; i>=0; i--) {
4173 ServiceInfo destAi = dest.get(i).serviceInfo;
4174 if (destAi.name == filterSi.name
4175 && destAi.packageName == filterSi.packageName) {
4176 return false;
4177 }
4178 }
4179 return true;
4180 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004182 @Override
4183 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4184 int match) {
4185 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4186 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4187 return null;
4188 }
4189 final PackageParser.Service service = info.service;
4190 if (mSafeMode && (service.info.applicationInfo.flags
4191 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4192 return null;
4193 }
4194 final ResolveInfo res = new ResolveInfo();
4195 res.serviceInfo = PackageParser.generateServiceInfo(service,
4196 mFlags);
4197 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4198 res.filter = filter;
4199 }
4200 res.priority = info.getPriority();
4201 res.preferredOrder = service.owner.mPreferredOrder;
4202 //System.out.println("Result: " + res.activityInfo.className +
4203 // " = " + res.priority);
4204 res.match = match;
4205 res.isDefault = info.hasDefault;
4206 res.labelRes = info.labelRes;
4207 res.nonLocalizedLabel = info.nonLocalizedLabel;
4208 res.icon = info.icon;
4209 return res;
4210 }
4211
4212 @Override
4213 protected void sortResults(List<ResolveInfo> results) {
4214 Collections.sort(results, mResolvePrioritySorter);
4215 }
4216
4217 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004218 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004219 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004220 out.print(prefix); out.print(
4221 Integer.toHexString(System.identityHashCode(filter.service)));
4222 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004223 out.println(filter.service.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004224 }
4225
4226// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4227// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4228// final List<ResolveInfo> retList = Lists.newArrayList();
4229// while (i.hasNext()) {
4230// final ResolveInfo resolveInfo = (ResolveInfo) i;
4231// if (isEnabledLP(resolveInfo.serviceInfo)) {
4232// retList.add(resolveInfo);
4233// }
4234// }
4235// return retList;
4236// }
4237
4238 // Keys are String (activity class name), values are Activity.
4239 private final HashMap<ComponentName, PackageParser.Service> mServices
4240 = new HashMap<ComponentName, PackageParser.Service>();
4241 private int mFlags;
4242 };
4243
4244 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4245 new Comparator<ResolveInfo>() {
4246 public int compare(ResolveInfo r1, ResolveInfo r2) {
4247 int v1 = r1.priority;
4248 int v2 = r2.priority;
4249 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4250 if (v1 != v2) {
4251 return (v1 > v2) ? -1 : 1;
4252 }
4253 v1 = r1.preferredOrder;
4254 v2 = r2.preferredOrder;
4255 if (v1 != v2) {
4256 return (v1 > v2) ? -1 : 1;
4257 }
4258 if (r1.isDefault != r2.isDefault) {
4259 return r1.isDefault ? -1 : 1;
4260 }
4261 v1 = r1.match;
4262 v2 = r2.match;
4263 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4264 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4265 }
4266 };
4267
4268 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4269 new Comparator<ProviderInfo>() {
4270 public int compare(ProviderInfo p1, ProviderInfo p2) {
4271 final int v1 = p1.initOrder;
4272 final int v2 = p2.initOrder;
4273 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4274 }
4275 };
4276
4277 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4278 IActivityManager am = ActivityManagerNative.getDefault();
4279 if (am != null) {
4280 try {
4281 final Intent intent = new Intent(action,
4282 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4283 if (extras != null) {
4284 intent.putExtras(extras);
4285 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004286 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004287 am.broadcastIntent(
4288 null, intent,
4289 null, null, 0, null, null, null, false, false);
4290 } catch (RemoteException ex) {
4291 }
4292 }
4293 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004294
4295 public String nextPackageToClean(String lastPackage) {
4296 synchronized (mPackages) {
4297 if (!mMediaMounted) {
4298 // If the external storage is no longer mounted at this point,
4299 // the caller may not have been able to delete all of this
4300 // packages files and can not delete any more. Bail.
4301 return null;
4302 }
4303 if (lastPackage != null) {
4304 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4305 }
4306 return mSettings.mPackagesToBeCleaned.size() > 0
4307 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4308 }
4309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004310
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004311 void schedulePackageCleaning(String packageName) {
4312 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4313 }
4314
4315 void startCleaningPackages() {
4316 synchronized (mPackages) {
4317 if (!mMediaMounted) {
4318 return;
4319 }
4320 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4321 return;
4322 }
4323 }
4324 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4325 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4326 IActivityManager am = ActivityManagerNative.getDefault();
4327 if (am != null) {
4328 try {
4329 am.startService(null, intent, null);
4330 } catch (RemoteException e) {
4331 }
4332 }
4333 }
4334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004335 private final class AppDirObserver extends FileObserver {
4336 public AppDirObserver(String path, int mask, boolean isrom) {
4337 super(path, mask);
4338 mRootDir = path;
4339 mIsRom = isrom;
4340 }
4341
4342 public void onEvent(int event, String path) {
4343 String removedPackage = null;
4344 int removedUid = -1;
4345 String addedPackage = null;
4346 int addedUid = -1;
4347
4348 synchronized (mInstallLock) {
4349 String fullPathStr = null;
4350 File fullPath = null;
4351 if (path != null) {
4352 fullPath = new File(mRootDir, path);
4353 fullPathStr = fullPath.getPath();
4354 }
4355
4356 if (Config.LOGV) Log.v(
4357 TAG, "File " + fullPathStr + " changed: "
4358 + Integer.toHexString(event));
4359
4360 if (!isPackageFilename(path)) {
4361 if (Config.LOGV) Log.v(
4362 TAG, "Ignoring change of non-package file: " + fullPathStr);
4363 return;
4364 }
4365
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004366 // Ignore packages that are being installed or
4367 // have just been installed.
4368 if (ignoreCodePath(fullPathStr)) {
4369 return;
4370 }
4371 PackageParser.Package p = null;
4372 synchronized (mPackages) {
4373 p = mAppDirs.get(fullPathStr);
4374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004375 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004376 if (p != null) {
4377 removePackageLI(p, true);
4378 removedPackage = p.applicationInfo.packageName;
4379 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004380 }
4381 }
4382
4383 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004384 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004385 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004386 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
4387 PackageParser.PARSE_CHATTY |
4388 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004389 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004390 if (p != null) {
4391 synchronized (mPackages) {
4392 grantPermissionsLP(p, false);
4393 }
4394 addedPackage = p.applicationInfo.packageName;
4395 addedUid = p.applicationInfo.uid;
4396 }
4397 }
4398 }
4399
4400 synchronized (mPackages) {
4401 mSettings.writeLP();
4402 }
4403 }
4404
4405 if (removedPackage != null) {
4406 Bundle extras = new Bundle(1);
4407 extras.putInt(Intent.EXTRA_UID, removedUid);
4408 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4409 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4410 }
4411 if (addedPackage != null) {
4412 Bundle extras = new Bundle(1);
4413 extras.putInt(Intent.EXTRA_UID, addedUid);
4414 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4415 }
4416 }
4417
4418 private final String mRootDir;
4419 private final boolean mIsRom;
4420 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004422 /* Called when a downloaded package installation has been confirmed by the user */
4423 public void installPackage(
4424 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004425 installPackage(packageURI, observer, flags, null);
4426 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004427
Jacek Surazski65e13172009-04-28 15:26:38 +02004428 /* Called when a downloaded package installation has been confirmed by the user */
4429 public void installPackage(
4430 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4431 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004432 mContext.enforceCallingOrSelfPermission(
4433 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004434
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004435 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004436 msg.obj = new InstallParams(packageURI, observer, flags,
4437 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004438 mHandler.sendMessage(msg);
4439 }
4440
Christopher Tate1bb69062010-02-19 17:02:12 -08004441 public void finishPackageInstall(int token) {
4442 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4443 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4444 mHandler.sendMessage(msg);
4445 }
4446
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004447 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004448 // Queue up an async operation since the package installation may take a little while.
4449 mHandler.post(new Runnable() {
4450 public void run() {
4451 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004452 // Result object to be returned
4453 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004454 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004455 res.uid = -1;
4456 res.pkg = null;
4457 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004458 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004459 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004460 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004461 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004462 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004463 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004464 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004465
4466 // A restore should be performed at this point if (a) the install
4467 // succeeded, (b) the operation is not an update, and (c) the new
4468 // package has a backupAgent defined.
4469 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004470 boolean doRestore = (!update
4471 && res.pkg != null
4472 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004473
4474 // Set up the post-install work request bookkeeping. This will be used
4475 // and cleaned up by the post-install event handling regardless of whether
4476 // there's a restore pass performed. Token values are >= 1.
4477 int token;
4478 if (mNextInstallToken < 0) mNextInstallToken = 1;
4479 token = mNextInstallToken++;
4480
4481 PostInstallData data = new PostInstallData(args, res);
4482 mRunningInstalls.put(token, data);
4483 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4484
4485 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4486 // Pass responsibility to the Backup Manager. It will perform a
4487 // restore if appropriate, then pass responsibility back to the
4488 // Package Manager to run the post-install observer callbacks
4489 // and broadcasts.
4490 IBackupManager bm = IBackupManager.Stub.asInterface(
4491 ServiceManager.getService(Context.BACKUP_SERVICE));
4492 if (bm != null) {
4493 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4494 + " to BM for possible restore");
4495 try {
4496 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4497 } catch (RemoteException e) {
4498 // can't happen; the backup manager is local
4499 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004500 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004501 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004502 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004503 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004504 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004505 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004507 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004508
4509 if (!doRestore) {
4510 // No restore possible, or the Backup Manager was mysteriously not
4511 // available -- just fire the post-install work request directly.
4512 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4513 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4514 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004516 }
4517 });
4518 }
4519
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004520 abstract class HandlerParams {
4521 final static int MAX_RETRIES = 4;
4522 int retry = 0;
4523 final void startCopy() {
4524 try {
4525 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4526 retry++;
4527 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004528 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004529 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4530 handleServiceError();
4531 return;
4532 } else {
4533 handleStartCopy();
4534 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4535 mHandler.sendEmptyMessage(MCS_UNBIND);
4536 }
4537 } catch (RemoteException e) {
4538 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4539 mHandler.sendEmptyMessage(MCS_RECONNECT);
4540 }
4541 handleReturnCode();
4542 }
4543
4544 final void serviceError() {
4545 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4546 handleServiceError();
4547 handleReturnCode();
4548 }
4549 abstract void handleStartCopy() throws RemoteException;
4550 abstract void handleServiceError();
4551 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004552 }
4553
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004554 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004555 final IPackageInstallObserver observer;
4556 int flags;
4557 final Uri packageURI;
4558 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004559 private InstallArgs mArgs;
4560 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004561 InstallParams(Uri packageURI,
4562 IPackageInstallObserver observer, int flags,
4563 String installerPackageName) {
4564 this.packageURI = packageURI;
4565 this.flags = flags;
4566 this.observer = observer;
4567 this.installerPackageName = installerPackageName;
4568 }
4569
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004570 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4571 String packageName = pkgLite.packageName;
4572 int installLocation = pkgLite.installLocation;
4573 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4574 synchronized (mPackages) {
4575 PackageParser.Package pkg = mPackages.get(packageName);
4576 if (pkg != null) {
4577 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4578 // Check for updated system application.
4579 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4580 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004581 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004582 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4583 }
4584 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4585 } else {
4586 // When replacing apps make sure we honour
4587 // the existing app location if not overwritten by other options
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08004588 boolean prevOnSd = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004589 if (onSd) {
4590 // Install flag overrides everything.
4591 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4592 }
4593 // If current upgrade does not specify install location.
4594 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4595 // Application explicitly specified internal.
4596 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4597 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4598 // App explictly prefers external. Let policy decide
4599 } else if (installLocation == PackageInfo.INSTALL_LOCATION_AUTO) {
4600 // Prefer previous location
4601 return prevOnSd ? PackageHelper.RECOMMEND_INSTALL_EXTERNAL:
4602 PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4603 }
4604 }
4605 } else {
4606 // Invalid install. Return error code
4607 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4608 }
4609 }
4610 }
4611 // All the special cases have been taken care of.
4612 // Return result based on recommended install location.
4613 if (onSd) {
4614 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4615 }
4616 return pkgLite.recommendedInstallLocation;
4617 }
4618
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004619 /*
4620 * Invoke remote method to get package information and install
4621 * location values. Override install location based on default
4622 * policy if needed and then create install arguments based
4623 * on the install location.
4624 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004625 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004626 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004627 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4628 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004629 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4630 if (onInt && onSd) {
4631 // Check if both bits are set.
4632 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4633 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4634 } else if (fwdLocked && onSd) {
4635 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004636 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004637 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004638 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004639 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004640 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004641 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004642 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4643 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4644 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4645 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4646 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004647 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4648 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4649 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004650 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4651 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004652 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004653 // Override with defaults if needed.
4654 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004655 if (!onSd && !onInt) {
4656 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004657 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4658 // Set the flag to install on external media.
4659 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004660 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004661 } else {
4662 // Make sure the flag for installing on external
4663 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004664 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004665 flags &= ~PackageManager.INSTALL_EXTERNAL;
4666 }
4667 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004668 }
4669 }
4670 // Create the file args now.
4671 mArgs = createInstallArgs(this);
4672 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4673 // Create copy only if we are not in an erroneous state.
4674 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004675 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004676 }
4677 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004678 }
4679
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004680 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004681 void handleReturnCode() {
4682 processPendingInstall(mArgs, mRet);
4683 }
4684
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004685 @Override
4686 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004687 mArgs = createInstallArgs(this);
4688 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004689 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004690 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004691
4692 /*
4693 * Utility class used in movePackage api.
4694 * srcArgs and targetArgs are not set for invalid flags and make
4695 * sure to do null checks when invoking methods on them.
4696 * We probably want to return ErrorPrams for both failed installs
4697 * and moves.
4698 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004699 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004700 final IPackageMoveObserver observer;
4701 final int flags;
4702 final String packageName;
4703 final InstallArgs srcArgs;
4704 final InstallArgs targetArgs;
4705 int mRet;
4706 MoveParams(InstallArgs srcArgs,
4707 IPackageMoveObserver observer,
4708 int flags, String packageName) {
4709 this.srcArgs = srcArgs;
4710 this.observer = observer;
4711 this.flags = flags;
4712 this.packageName = packageName;
4713 if (srcArgs != null) {
4714 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4715 targetArgs = createInstallArgs(packageUri, flags, packageName);
4716 } else {
4717 targetArgs = null;
4718 }
4719 }
4720
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004721 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004722 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4723 // Check for storage space on target medium
4724 if (!targetArgs.checkFreeStorage(mContainerService)) {
4725 Log.w(TAG, "Insufficient storage to install");
4726 return;
4727 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004728 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004729 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004730 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004731 if (DEBUG_SD_INSTALL) {
4732 StringBuilder builder = new StringBuilder();
4733 if (srcArgs != null) {
4734 builder.append("src: ");
4735 builder.append(srcArgs.getCodePath());
4736 }
4737 if (targetArgs != null) {
4738 builder.append(" target : ");
4739 builder.append(targetArgs.getCodePath());
4740 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004741 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004742 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004743 }
4744
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004745 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004746 void handleReturnCode() {
4747 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004748 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4749 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4750 currentStatus = PackageManager.MOVE_SUCCEEDED;
4751 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4752 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4753 }
4754 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004755 }
4756
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004757 @Override
4758 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004759 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004760 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004761 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004762
4763 private InstallArgs createInstallArgs(InstallParams params) {
4764 if (installOnSd(params.flags)) {
4765 return new SdInstallArgs(params);
4766 } else {
4767 return new FileInstallArgs(params);
4768 }
4769 }
4770
4771 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4772 if (installOnSd(flags)) {
4773 return new SdInstallArgs(fullCodePath, fullResourcePath);
4774 } else {
4775 return new FileInstallArgs(fullCodePath, fullResourcePath);
4776 }
4777 }
4778
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004779 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4780 if (installOnSd(flags)) {
4781 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4782 return new SdInstallArgs(packageURI, cid);
4783 } else {
4784 return new FileInstallArgs(packageURI, pkgName);
4785 }
4786 }
4787
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004788 static abstract class InstallArgs {
4789 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004790 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004791 final int flags;
4792 final Uri packageURI;
4793 final String installerPackageName;
4794
4795 InstallArgs(Uri packageURI,
4796 IPackageInstallObserver observer, int flags,
4797 String installerPackageName) {
4798 this.packageURI = packageURI;
4799 this.flags = flags;
4800 this.observer = observer;
4801 this.installerPackageName = installerPackageName;
4802 }
4803
4804 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004805 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004806 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004807 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004808 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004809 abstract String getCodePath();
4810 abstract String getResourcePath();
4811 // Need installer lock especially for dex file removal.
4812 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004813 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004814 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004815 }
4816
4817 class FileInstallArgs extends InstallArgs {
4818 File installDir;
4819 String codeFileName;
4820 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004821 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004822
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004823 FileInstallArgs(InstallParams params) {
4824 super(params.packageURI, params.observer,
4825 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004826 }
4827
4828 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4829 super(null, null, 0, null);
4830 File codeFile = new File(fullCodePath);
4831 installDir = codeFile.getParentFile();
4832 codeFileName = fullCodePath;
4833 resourceFileName = fullResourcePath;
4834 }
4835
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004836 FileInstallArgs(Uri packageURI, String pkgName) {
4837 super(packageURI, null, 0, null);
4838 boolean fwdLocked = isFwdLocked(flags);
4839 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4840 String apkName = getNextCodePath(null, pkgName, ".apk");
4841 codeFileName = new File(installDir, apkName + ".apk").getPath();
4842 resourceFileName = getResourcePathFromCodePath();
4843 }
4844
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004845 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4846 return imcs.checkFreeStorage(false, packageURI);
4847 }
4848
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004849 String getCodePath() {
4850 return codeFileName;
4851 }
4852
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004853 void createCopyFile() {
4854 boolean fwdLocked = isFwdLocked(flags);
4855 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4856 codeFileName = createTempPackageFile(installDir).getPath();
4857 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004858 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004859 }
4860
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004861 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004862 if (temp) {
4863 // Generate temp file name
4864 createCopyFile();
4865 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004866 // Get a ParcelFileDescriptor to write to the output file
4867 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004868 if (!created) {
4869 try {
4870 codeFile.createNewFile();
4871 // Set permissions
4872 if (!setPermissions()) {
4873 // Failed setting permissions.
4874 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4875 }
4876 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004877 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004878 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4879 }
4880 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004881 ParcelFileDescriptor out = null;
4882 try {
4883 out = ParcelFileDescriptor.open(codeFile,
4884 ParcelFileDescriptor.MODE_READ_WRITE);
4885 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004886 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004887 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4888 }
4889 // Copy the resource now
4890 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4891 try {
4892 if (imcs.copyResource(packageURI, out)) {
4893 ret = PackageManager.INSTALL_SUCCEEDED;
4894 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004895 } finally {
4896 try { if (out != null) out.close(); } catch (IOException e) {}
4897 }
4898 return ret;
4899 }
4900
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004901 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004902 if (status != PackageManager.INSTALL_SUCCEEDED) {
4903 cleanUp();
4904 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004905 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004906 }
4907
4908 boolean doRename(int status, final String pkgName, String oldCodePath) {
4909 if (status != PackageManager.INSTALL_SUCCEEDED) {
4910 cleanUp();
4911 return false;
4912 } else {
4913 // Rename based on packageName
4914 File codeFile = new File(getCodePath());
4915 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
4916 File desFile = new File(installDir, apkName + ".apk");
4917 if (!codeFile.renameTo(desFile)) {
4918 return false;
4919 }
4920 // Reset paths since the file has been renamed.
4921 codeFileName = desFile.getPath();
4922 resourceFileName = getResourcePathFromCodePath();
4923 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004924 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004925 // Failed setting permissions.
4926 return false;
4927 }
4928 return true;
4929 }
4930 }
4931
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004932 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004933 if (status != PackageManager.INSTALL_SUCCEEDED) {
4934 cleanUp();
4935 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004936 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004937 }
4938
4939 String getResourcePath() {
4940 return resourceFileName;
4941 }
4942
4943 String getResourcePathFromCodePath() {
4944 String codePath = getCodePath();
4945 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4946 String apkNameOnly = getApkName(codePath);
4947 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
4948 } else {
4949 return codePath;
4950 }
4951 }
4952
4953 private boolean cleanUp() {
4954 boolean ret = true;
4955 String sourceDir = getCodePath();
4956 String publicSourceDir = getResourcePath();
4957 if (sourceDir != null) {
4958 File sourceFile = new File(sourceDir);
4959 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004960 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004961 ret = false;
4962 }
4963 // Delete application's code and resources
4964 sourceFile.delete();
4965 }
4966 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4967 final File publicSourceFile = new File(publicSourceDir);
4968 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004969 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004970 }
4971 if (publicSourceFile.exists()) {
4972 publicSourceFile.delete();
4973 }
4974 }
4975 return ret;
4976 }
4977
4978 void cleanUpResourcesLI() {
4979 String sourceDir = getCodePath();
4980 if (cleanUp() && mInstaller != null) {
4981 int retCode = mInstaller.rmdex(sourceDir);
4982 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004983 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004984 + " at location "
4985 + sourceDir + ", retcode=" + retCode);
4986 // we don't consider this to be a failure of the core package deletion
4987 }
4988 }
4989 }
4990
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004991 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004992 // TODO Do this in a more elegant way later on. for now just a hack
4993 if (!isFwdLocked(flags)) {
4994 final int filePermissions =
4995 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4996 |FileUtils.S_IROTH;
4997 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
4998 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004999 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005000 getCodePath()
5001 + ". The return code was: " + retCode);
5002 // TODO Define new internal error
5003 return false;
5004 }
5005 return true;
5006 }
5007 return true;
5008 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005009
5010 boolean doPostDeleteLI(boolean delete) {
5011 cleanUpResourcesLI();
5012 return true;
5013 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005014 }
5015
5016 class SdInstallArgs extends InstallArgs {
5017 String cid;
5018 String cachePath;
5019 static final String RES_FILE_NAME = "pkg.apk";
5020
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005021 SdInstallArgs(InstallParams params) {
5022 super(params.packageURI, params.observer,
5023 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005024 }
5025
5026 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005027 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005028 // Extract cid from fullCodePath
5029 int eidx = fullCodePath.lastIndexOf("/");
5030 String subStr1 = fullCodePath.substring(0, eidx);
5031 int sidx = subStr1.lastIndexOf("/");
5032 cid = subStr1.substring(sidx+1, eidx);
5033 cachePath = subStr1;
5034 }
5035
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005036 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005037 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5038 this.cid = cid;
5039 }
5040
5041 SdInstallArgs(Uri packageURI, String cid) {
5042 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005043 this.cid = cid;
5044 }
5045
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005046 void createCopyFile() {
5047 cid = getTempContainerId();
5048 }
5049
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005050 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5051 return imcs.checkFreeStorage(true, packageURI);
5052 }
5053
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005054 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005055 if (temp) {
5056 createCopyFile();
5057 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005058 cachePath = imcs.copyResourceToContainer(
5059 packageURI, cid,
5060 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005061 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5062 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005063 }
5064
5065 @Override
5066 String getCodePath() {
5067 return cachePath + "/" + RES_FILE_NAME;
5068 }
5069
5070 @Override
5071 String getResourcePath() {
5072 return cachePath + "/" + RES_FILE_NAME;
5073 }
5074
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005075 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005076 if (status != PackageManager.INSTALL_SUCCEEDED) {
5077 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005078 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005079 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005080 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005081 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005082 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005083 if (cachePath == null) {
5084 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5085 }
5086 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005087 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005088 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005089 }
5090
5091 boolean doRename(int status, final String pkgName,
5092 String oldCodePath) {
5093 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005094 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005095 if (PackageHelper.isContainerMounted(cid)) {
5096 // Unmount the container
5097 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005098 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005099 return false;
5100 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005101 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005102 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005103 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005104 return false;
5105 }
5106 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005107 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005108 newCachePath = PackageHelper.mountSdDir(newCacheId,
5109 getEncryptKey(), Process.SYSTEM_UID);
5110 } else {
5111 newCachePath = PackageHelper.getSdDir(newCacheId);
5112 }
5113 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005114 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005115 return false;
5116 }
5117 Log.i(TAG, "Succesfully renamed " + cid +
5118 " at path: " + cachePath + " to " + newCacheId +
5119 " at new path: " + newCachePath);
5120 cid = newCacheId;
5121 cachePath = newCachePath;
5122 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005123 }
5124
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005125 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005126 if (status != PackageManager.INSTALL_SUCCEEDED) {
5127 cleanUp();
5128 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005129 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005130 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005131 PackageHelper.mountSdDir(cid,
5132 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005133 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005134 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005135 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005136 }
5137
5138 private void cleanUp() {
5139 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005140 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005141 }
5142
5143 void cleanUpResourcesLI() {
5144 String sourceFile = getCodePath();
5145 // Remove dex file
5146 if (mInstaller != null) {
5147 int retCode = mInstaller.rmdex(sourceFile.toString());
5148 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005149 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005150 + " at location "
5151 + sourceFile.toString() + ", retcode=" + retCode);
5152 // we don't consider this to be a failure of the core package deletion
5153 }
5154 }
5155 cleanUp();
5156 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005157
5158 boolean matchContainer(String app) {
5159 if (cid.startsWith(app)) {
5160 return true;
5161 }
5162 return false;
5163 }
5164
5165 String getPackageName() {
5166 int idx = cid.lastIndexOf("-");
5167 if (idx == -1) {
5168 return cid;
5169 }
5170 return cid.substring(0, idx);
5171 }
5172
5173 boolean doPostDeleteLI(boolean delete) {
5174 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005175 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005176 if (mounted) {
5177 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005178 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005179 }
5180 if (ret && delete) {
5181 cleanUpResourcesLI();
5182 }
5183 return ret;
5184 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005185 };
5186
5187 // Utility method used to create code paths based on package name and available index.
5188 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5189 String idxStr = "";
5190 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005191 // Fall back to default value of idx=1 if prefix is not
5192 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005193 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005194 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005195 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005196 if (subStr.endsWith(suffix)) {
5197 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005198 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005199 // If oldCodePath already contains prefix find out the
5200 // ending index to either increment or decrement.
5201 int sidx = subStr.lastIndexOf(prefix);
5202 if (sidx != -1) {
5203 subStr = subStr.substring(sidx + prefix.length());
5204 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005205 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5206 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005207 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005208 try {
5209 idx = Integer.parseInt(subStr);
5210 if (idx <= 1) {
5211 idx++;
5212 } else {
5213 idx--;
5214 }
5215 } catch(NumberFormatException e) {
5216 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005217 }
5218 }
5219 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005220 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005221 return prefix + idxStr;
5222 }
5223
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005224 // Utility method used to ignore ADD/REMOVE events
5225 // by directory observer.
5226 private static boolean ignoreCodePath(String fullPathStr) {
5227 String apkName = getApkName(fullPathStr);
5228 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5229 if (idx != -1 && ((idx+1) < apkName.length())) {
5230 // Make sure the package ends with a numeral
5231 String version = apkName.substring(idx+1);
5232 try {
5233 Integer.parseInt(version);
5234 return true;
5235 } catch (NumberFormatException e) {}
5236 }
5237 return false;
5238 }
5239
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005240 // Utility method that returns the relative package path with respect
5241 // to the installation directory. Like say for /data/data/com.test-1.apk
5242 // string com.test-1 is returned.
5243 static String getApkName(String codePath) {
5244 if (codePath == null) {
5245 return null;
5246 }
5247 int sidx = codePath.lastIndexOf("/");
5248 int eidx = codePath.lastIndexOf(".");
5249 if (eidx == -1) {
5250 eidx = codePath.length();
5251 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005252 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005253 return null;
5254 }
5255 return codePath.substring(sidx+1, eidx);
5256 }
5257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005258 class PackageInstalledInfo {
5259 String name;
5260 int uid;
5261 PackageParser.Package pkg;
5262 int returnCode;
5263 PackageRemovedInfo removedInfo;
5264 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005266 /*
5267 * Install a non-existing package.
5268 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005269 private void installNewPackageLI(PackageParser.Package pkg,
5270 int parseFlags,
5271 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005272 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005273 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005274 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005275
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005276 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005277 res.name = pkgName;
5278 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005279 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005280 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005281 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005282 + " without first uninstalling.");
5283 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5284 return;
5285 }
5286 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005287 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005288 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005289 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005290 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005291 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5292 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5293 }
5294 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005295 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005296 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005297 res);
5298 // delete the partially installed application. the data directory will have to be
5299 // restored if it was already existing
5300 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5301 // remove package from internal structures. Note that we want deletePackageX to
5302 // delete the package data and cache directories that it created in
5303 // scanPackageLocked, unless those directories existed before we even tried to
5304 // install.
5305 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005306 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005307 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5308 res.removedInfo);
5309 }
5310 }
5311 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005312
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005313 private void replacePackageLI(PackageParser.Package pkg,
5314 int parseFlags,
5315 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005316 String installerPackageName, PackageInstalledInfo res) {
5317
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005318 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005319 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005320 // First find the old package info and check signatures
5321 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005322 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005323 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005324 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005325 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5326 return;
5327 }
5328 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005329 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005330 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005331 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005332 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005333 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005334 }
5335 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005337 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005338 PackageParser.Package pkg,
5339 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005340 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005341 PackageParser.Package newPackage = null;
5342 String pkgName = deletedPackage.packageName;
5343 boolean deletedPkg = true;
5344 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005345
Jacek Surazski65e13172009-04-28 15:26:38 +02005346 String oldInstallerPackageName = null;
5347 synchronized (mPackages) {
5348 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5349 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005350
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005351 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005352 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005353 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005354 res.removedInfo)) {
5355 // If the existing package was'nt successfully deleted
5356 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5357 deletedPkg = false;
5358 } else {
5359 // Successfully deleted the old package. Now proceed with re-installation
5360 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005361 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005362 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005363 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005364 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5365 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005366 }
5367 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005368 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005369 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005370 res);
5371 updatedSettings = true;
5372 }
5373 }
5374
5375 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5376 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005377 // were keeping around in case we needed them (see below) can now be deleted.
5378 // This info will be set on the res.removedInfo to clean up later on as post
5379 // install action.
5380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005381 //update signature on the new package setting
5382 //this should always succeed, since we checked the
5383 //signature earlier.
5384 synchronized(mPackages) {
5385 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
5386 parseFlags, true);
5387 }
5388 } else {
5389 // remove package from internal structures. Note that we want deletePackageX to
5390 // delete the package data and cache directories that it created in
5391 // scanPackageLocked, unless those directories existed before we even tried to
5392 // install.
5393 if(updatedSettings) {
5394 deletePackageLI(
5395 pkgName, true,
5396 PackageManager.DONT_DELETE_DATA,
5397 res.removedInfo);
5398 }
5399 // Since we failed to install the new package we need to restore the old
5400 // package that we deleted.
5401 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005402 File restoreFile = new File(deletedPackage.mPath);
5403 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005404 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005405 return;
5406 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005407 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5408 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005409 // Parse old package
5410 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5411 scanPackageLI(restoreFile, parseFlags, scanMode);
5412 synchronized (mPackages) {
5413 grantPermissionsLP(deletedPackage, false);
5414 mSettings.writeLP();
5415 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005416 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005417 Slog.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005419 }
5420 }
5421 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005423 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005424 PackageParser.Package pkg,
5425 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005426 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005427 PackageParser.Package newPackage = null;
5428 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005429 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005430 PackageParser.PARSE_IS_SYSTEM;
5431 String packageName = deletedPackage.packageName;
5432 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5433 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005434 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005435 return;
5436 }
5437 PackageParser.Package oldPkg;
5438 PackageSetting oldPkgSetting;
5439 synchronized (mPackages) {
5440 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005441 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005442 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5443 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005444 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005445 return;
5446 }
5447 }
5448 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5449 res.removedInfo.removedPackage = packageName;
5450 // Remove existing system package
5451 removePackageLI(oldPkg, true);
5452 synchronized (mPackages) {
5453 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5454 }
5455
5456 // Successfully disabled the old package. Now proceed with re-installation
5457 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5458 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005459 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005460 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005461 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005462 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5463 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5464 }
5465 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005466 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005467 updatedSettings = true;
5468 }
5469
5470 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5471 //update signature on the new package setting
5472 //this should always succeed, since we checked the
5473 //signature earlier.
5474 synchronized(mPackages) {
5475 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5476 parseFlags, true);
5477 }
5478 } else {
5479 // Re installation failed. Restore old information
5480 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005481 if (newPackage != null) {
5482 removePackageLI(newPackage, true);
5483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005484 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005485 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005486 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005487 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488 // Restore the old system information in Settings
5489 synchronized(mPackages) {
5490 if(updatedSettings) {
5491 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005492 mSettings.setInstallerPackageName(packageName,
5493 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005494 }
5495 mSettings.writeLP();
5496 }
5497 }
5498 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005499
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005500 // Utility method used to move dex files during install.
5501 private int moveDexFiles(PackageParser.Package newPackage) {
5502 int retCode;
5503 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5504 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5505 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005506 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005507 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5508 }
5509 }
5510 return PackageManager.INSTALL_SUCCEEDED;
5511 }
5512
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005513 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005514 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005515 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005516 synchronized (mPackages) {
5517 //write settings. the installStatus will be incomplete at this stage.
5518 //note that the new package setting would have already been
5519 //added to mPackages. It hasn't been persisted yet.
5520 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5521 mSettings.writeLP();
5522 }
5523
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005524 if ((res.returnCode = moveDexFiles(newPackage))
5525 != PackageManager.INSTALL_SUCCEEDED) {
5526 // Discontinue if moving dex files failed.
5527 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005528 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005529 if((res.returnCode = setPermissionsLI(newPackage))
5530 != PackageManager.INSTALL_SUCCEEDED) {
5531 if (mInstaller != null) {
5532 mInstaller.rmdex(newPackage.mScanPath);
5533 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005534 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005535 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005536 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005538 synchronized (mPackages) {
5539 grantPermissionsLP(newPackage, true);
5540 res.name = pkgName;
5541 res.uid = newPackage.applicationInfo.uid;
5542 res.pkg = newPackage;
5543 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005544 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005545 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5546 //to update install status
5547 mSettings.writeLP();
5548 }
5549 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005550
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005551 private void installPackageLI(InstallArgs args,
5552 boolean newInstall, PackageInstalledInfo res) {
5553 int pFlags = args.flags;
5554 String installerPackageName = args.installerPackageName;
5555 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005556 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005557 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005558 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005559 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5560 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005561 // Result object to be returned
5562 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5563
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005564 // Retrieve PackageSettings and parse package
5565 int parseFlags = PackageParser.PARSE_CHATTY |
5566 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5567 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5568 parseFlags |= mDefParseFlags;
5569 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5570 pp.setSeparateProcesses(mSeparateProcesses);
5571 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5572 null, mMetrics, parseFlags);
5573 if (pkg == null) {
5574 res.returnCode = pp.getParseError();
5575 return;
5576 }
5577 String pkgName = res.name = pkg.packageName;
5578 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5579 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5580 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5581 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005582 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005583 }
5584 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5585 res.returnCode = pp.getParseError();
5586 return;
5587 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005588 // Get rid of all references to package scan path via parser.
5589 pp = null;
5590 String oldCodePath = null;
5591 boolean systemApp = false;
5592 synchronized (mPackages) {
5593 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005594 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5595 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005596 if (pkg.mOriginalPackages != null
5597 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005598 && mPackages.containsKey(oldName)) {
5599 // This package is derived from an original package,
5600 // and this device has been updating from that original
5601 // name. We must continue using the original name, so
5602 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005603 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005604 pkgName = pkg.packageName;
5605 replace = true;
5606 } else if (mPackages.containsKey(pkgName)) {
5607 // This package, under its official name, already exists
5608 // on the device; we should replace it.
5609 replace = true;
5610 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005611 }
5612 PackageSetting ps = mSettings.mPackages.get(pkgName);
5613 if (ps != null) {
5614 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5615 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5616 systemApp = (ps.pkg.applicationInfo.flags &
5617 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005618 }
5619 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005620 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005621
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005622 if (systemApp && onSd) {
5623 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005624 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005625 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5626 return;
5627 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005628
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005629 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5630 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5631 return;
5632 }
5633 // Set application objects path explicitly after the rename
5634 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005635 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005636 replacePackageLI(pkg, parseFlags, scanMode,
5637 installerPackageName, res);
5638 } else {
5639 installNewPackageLI(pkg, parseFlags, scanMode,
5640 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005641 }
5642 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005643
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005644 private int setPermissionsLI(PackageParser.Package newPackage) {
5645 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005646 int retCode = 0;
5647 // TODO Gross hack but fix later. Ideally move this to be a post installation
5648 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005649 if ((newPackage.applicationInfo.flags
5650 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5651 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005652 try {
5653 extractPublicFiles(newPackage, destResourceFile);
5654 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005655 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 -08005656 " forward-locked app.");
5657 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5658 } finally {
5659 //TODO clean up the extracted public files
5660 }
5661 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005662 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005663 newPackage.applicationInfo.uid);
5664 } else {
5665 final int filePermissions =
5666 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005667 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005668 newPackage.applicationInfo.uid);
5669 }
5670 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005671 // The permissions on the resource file was set when it was copied for
5672 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005673 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005675 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005676 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005677 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005678 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005679 // TODO Define new internal error
5680 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005681 }
5682 return PackageManager.INSTALL_SUCCEEDED;
5683 }
5684
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005685 private boolean isForwardLocked(PackageParser.Package pkg) {
5686 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005687 }
5688
5689 private void extractPublicFiles(PackageParser.Package newPackage,
5690 File publicZipFile) throws IOException {
5691 final ZipOutputStream publicZipOutStream =
5692 new ZipOutputStream(new FileOutputStream(publicZipFile));
5693 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5694
5695 // Copy manifest, resources.arsc and res directory to public zip
5696
5697 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5698 while (privateZipEntries.hasMoreElements()) {
5699 final ZipEntry zipEntry = privateZipEntries.nextElement();
5700 final String zipEntryName = zipEntry.getName();
5701 if ("AndroidManifest.xml".equals(zipEntryName)
5702 || "resources.arsc".equals(zipEntryName)
5703 || zipEntryName.startsWith("res/")) {
5704 try {
5705 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5706 } catch (IOException e) {
5707 try {
5708 publicZipOutStream.close();
5709 throw e;
5710 } finally {
5711 publicZipFile.delete();
5712 }
5713 }
5714 }
5715 }
5716
5717 publicZipOutStream.close();
5718 FileUtils.setPermissions(
5719 publicZipFile.getAbsolutePath(),
5720 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5721 -1, -1);
5722 }
5723
5724 private static void copyZipEntry(ZipEntry zipEntry,
5725 ZipFile inZipFile,
5726 ZipOutputStream outZipStream) throws IOException {
5727 byte[] buffer = new byte[4096];
5728 int num;
5729
5730 ZipEntry newEntry;
5731 if (zipEntry.getMethod() == ZipEntry.STORED) {
5732 // Preserve the STORED method of the input entry.
5733 newEntry = new ZipEntry(zipEntry);
5734 } else {
5735 // Create a new entry so that the compressed len is recomputed.
5736 newEntry = new ZipEntry(zipEntry.getName());
5737 }
5738 outZipStream.putNextEntry(newEntry);
5739
5740 InputStream data = inZipFile.getInputStream(zipEntry);
5741 while ((num = data.read(buffer)) > 0) {
5742 outZipStream.write(buffer, 0, num);
5743 }
5744 outZipStream.flush();
5745 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005747 private void deleteTempPackageFiles() {
5748 FilenameFilter filter = new FilenameFilter() {
5749 public boolean accept(File dir, String name) {
5750 return name.startsWith("vmdl") && name.endsWith(".tmp");
5751 }
5752 };
5753 String tmpFilesList[] = mAppInstallDir.list(filter);
5754 if(tmpFilesList == null) {
5755 return;
5756 }
5757 for(int i = 0; i < tmpFilesList.length; i++) {
5758 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5759 tmpFile.delete();
5760 }
5761 }
5762
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005763 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005764 File tmpPackageFile;
5765 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005766 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005767 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005768 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005769 return null;
5770 }
5771 try {
5772 FileUtils.setPermissions(
5773 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5774 -1, -1);
5775 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005776 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005777 return null;
5778 }
5779 return tmpPackageFile;
5780 }
5781
5782 public void deletePackage(final String packageName,
5783 final IPackageDeleteObserver observer,
5784 final int flags) {
5785 mContext.enforceCallingOrSelfPermission(
5786 android.Manifest.permission.DELETE_PACKAGES, null);
5787 // Queue up an async operation since the package deletion may take a little while.
5788 mHandler.post(new Runnable() {
5789 public void run() {
5790 mHandler.removeCallbacks(this);
5791 final boolean succeded = deletePackageX(packageName, true, true, flags);
5792 if (observer != null) {
5793 try {
5794 observer.packageDeleted(succeded);
5795 } catch (RemoteException e) {
5796 Log.i(TAG, "Observer no longer exists.");
5797 } //end catch
5798 } //end if
5799 } //end run
5800 });
5801 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005803 /**
5804 * This method is an internal method that could be get invoked either
5805 * to delete an installed package or to clean up a failed installation.
5806 * After deleting an installed package, a broadcast is sent to notify any
5807 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005808 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005809 * installation wouldn't have sent the initial broadcast either
5810 * The key steps in deleting a package are
5811 * deleting the package information in internal structures like mPackages,
5812 * deleting the packages base directories through installd
5813 * updating mSettings to reflect current status
5814 * persisting settings for later use
5815 * sending a broadcast if necessary
5816 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005817 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5818 boolean deleteCodeAndResources, int flags) {
5819 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005820 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005821
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005822 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
5823 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
5824 try {
5825 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005826 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005827 return false;
5828 }
5829 } catch (RemoteException e) {
5830 }
5831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005832 synchronized (mInstallLock) {
5833 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5834 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005836 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005837 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5838 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5839
5840 // If the removed package was a system update, the old system packaged
5841 // was re-enabled; we need to broadcast this information
5842 if (systemUpdate) {
5843 Bundle extras = new Bundle(1);
5844 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5845 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5846
5847 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5848 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005850 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005851 // Force a gc here.
5852 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005853 // Delete the resources here after sending the broadcast to let
5854 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005855 if (info.args != null) {
5856 synchronized (mInstallLock) {
5857 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005858 }
5859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005860 return res;
5861 }
5862
5863 static class PackageRemovedInfo {
5864 String removedPackage;
5865 int uid = -1;
5866 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005867 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005868 // Clean up resources deleted packages.
5869 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005871 void sendBroadcast(boolean fullRemove, boolean replacing) {
5872 Bundle extras = new Bundle(1);
5873 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5874 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5875 if (replacing) {
5876 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5877 }
5878 if (removedPackage != null) {
5879 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5880 }
5881 if (removedUid >= 0) {
5882 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5883 }
5884 }
5885 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005887 /*
5888 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5889 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005890 * 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 -08005891 * delete a partially installed application.
5892 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005893 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005894 int flags) {
5895 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005896 if (outInfo != null) {
5897 outInfo.removedPackage = packageName;
5898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005899 removePackageLI(p, true);
5900 // Retrieve object to delete permissions for shared user later on
5901 PackageSetting deletedPs;
5902 synchronized (mPackages) {
5903 deletedPs = mSettings.mPackages.get(packageName);
5904 }
5905 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005906 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005907 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005908 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005909 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005910 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005911 + packageName + ", retcode=" + retCode);
5912 // we don't consider this to be a failure of the core package deletion
5913 }
5914 } else {
5915 //for emulator
5916 PackageParser.Package pkg = mPackages.get(packageName);
5917 File dataDir = new File(pkg.applicationInfo.dataDir);
5918 dataDir.delete();
5919 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005920 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005921 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005922 if (outInfo != null) {
5923 outInfo.removedUid = mSettings.removePackageLP(packageName);
5924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005925 }
5926 }
5927 synchronized (mPackages) {
5928 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5929 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005930 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005931 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005932 if (deletedPs != null) {
5933 // remove from preferred activities.
5934 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
5935 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
5936 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
5937 removed.add(pa);
5938 }
5939 }
5940 for (PreferredActivity pa : removed) {
5941 mSettings.mPreferredActivities.removeFilter(pa);
5942 }
5943 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005944 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005945 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 }
5947 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005949 /*
5950 * Tries to delete system package.
5951 */
5952 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005953 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005954 ApplicationInfo applicationInfo = p.applicationInfo;
5955 //applicable for non-partially installed applications only
5956 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005957 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005958 return false;
5959 }
5960 PackageSetting ps = null;
5961 // Confirm if the system package has been updated
5962 // An updated system app can be deleted. This will also have to restore
5963 // the system pkg from system partition
5964 synchronized (mPackages) {
5965 ps = mSettings.getDisabledSystemPkg(p.packageName);
5966 }
5967 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005968 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005969 return false;
5970 } else {
5971 Log.i(TAG, "Deleting system pkg from data partition");
5972 }
5973 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005974 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005975 boolean deleteCodeAndResources = false;
5976 if (ps.versionCode < p.mVersionCode) {
5977 // Delete code and resources for downgrades
5978 deleteCodeAndResources = true;
5979 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5980 flags &= ~PackageManager.DONT_DELETE_DATA;
5981 }
5982 } else {
5983 // Preserve data by setting flag
5984 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5985 flags |= PackageManager.DONT_DELETE_DATA;
5986 }
5987 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005988 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5989 if (!ret) {
5990 return false;
5991 }
5992 synchronized (mPackages) {
5993 // Reinstate the old system package
5994 mSettings.enableSystemPackageLP(p.packageName);
5995 }
5996 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005997 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005998 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005999 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006002 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006003 return false;
6004 }
6005 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07006006 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 mSettings.writeLP();
6008 }
6009 return true;
6010 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006012 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6013 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6014 ApplicationInfo applicationInfo = p.applicationInfo;
6015 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006016 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006017 return false;
6018 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006019 if (outInfo != null) {
6020 outInfo.uid = applicationInfo.uid;
6021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006022
6023 // Delete package data from internal structures and also remove data if flag is set
6024 removePackageDataLI(p, outInfo, flags);
6025
6026 // Delete application code and resources
6027 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006028 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006029 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006030 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006031 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6032 PackageManager.INSTALL_FORWARD_LOCK : 0;
6033 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006034 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006035 }
6036 return true;
6037 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006039 /*
6040 * This method handles package deletion in general
6041 */
6042 private boolean deletePackageLI(String packageName,
6043 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6044 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006045 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006046 return false;
6047 }
6048 PackageParser.Package p;
6049 boolean dataOnly = false;
6050 synchronized (mPackages) {
6051 p = mPackages.get(packageName);
6052 if (p == null) {
6053 //this retrieves partially installed apps
6054 dataOnly = true;
6055 PackageSetting ps = mSettings.mPackages.get(packageName);
6056 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006057 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006058 return false;
6059 }
6060 p = ps.pkg;
6061 }
6062 }
6063 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006064 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006065 return false;
6066 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006068 if (dataOnly) {
6069 // Delete application data first
6070 removePackageDataLI(p, outInfo, flags);
6071 return true;
6072 }
6073 // At this point the package should have ApplicationInfo associated with it
6074 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006075 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006076 return false;
6077 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006078 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006079 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6080 Log.i(TAG, "Removing system package:"+p.packageName);
6081 // When an updated system application is deleted we delete the existing resources as well and
6082 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006083 ret = deleteSystemPackageLI(p, flags, outInfo);
6084 } else {
6085 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006086 // Kill application pre-emptively especially for apps on sd.
6087 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006088 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006089 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006090 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006091 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093 public void clearApplicationUserData(final String packageName,
6094 final IPackageDataObserver observer) {
6095 mContext.enforceCallingOrSelfPermission(
6096 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6097 // Queue up an async operation since the package deletion may take a little while.
6098 mHandler.post(new Runnable() {
6099 public void run() {
6100 mHandler.removeCallbacks(this);
6101 final boolean succeeded;
6102 synchronized (mInstallLock) {
6103 succeeded = clearApplicationUserDataLI(packageName);
6104 }
6105 if (succeeded) {
6106 // invoke DeviceStorageMonitor's update method to clear any notifications
6107 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6108 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6109 if (dsm != null) {
6110 dsm.updateMemory();
6111 }
6112 }
6113 if(observer != null) {
6114 try {
6115 observer.onRemoveCompleted(packageName, succeeded);
6116 } catch (RemoteException e) {
6117 Log.i(TAG, "Observer no longer exists.");
6118 }
6119 } //end if observer
6120 } //end run
6121 });
6122 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006124 private boolean clearApplicationUserDataLI(String packageName) {
6125 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006126 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006127 return false;
6128 }
6129 PackageParser.Package p;
6130 boolean dataOnly = false;
6131 synchronized (mPackages) {
6132 p = mPackages.get(packageName);
6133 if(p == null) {
6134 dataOnly = true;
6135 PackageSetting ps = mSettings.mPackages.get(packageName);
6136 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006137 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006138 return false;
6139 }
6140 p = ps.pkg;
6141 }
6142 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006143 boolean useEncryptedFSDir = false;
6144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006145 if(!dataOnly) {
6146 //need to check this only for fully installed applications
6147 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006148 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006149 return false;
6150 }
6151 final ApplicationInfo applicationInfo = p.applicationInfo;
6152 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006153 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006154 return false;
6155 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006156 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006157 }
6158 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006159 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006160 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006161 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006162 + packageName);
6163 return false;
6164 }
6165 }
6166 return true;
6167 }
6168
6169 public void deleteApplicationCacheFiles(final String packageName,
6170 final IPackageDataObserver observer) {
6171 mContext.enforceCallingOrSelfPermission(
6172 android.Manifest.permission.DELETE_CACHE_FILES, null);
6173 // Queue up an async operation since the package deletion may take a little while.
6174 mHandler.post(new Runnable() {
6175 public void run() {
6176 mHandler.removeCallbacks(this);
6177 final boolean succeded;
6178 synchronized (mInstallLock) {
6179 succeded = deleteApplicationCacheFilesLI(packageName);
6180 }
6181 if(observer != null) {
6182 try {
6183 observer.onRemoveCompleted(packageName, succeded);
6184 } catch (RemoteException e) {
6185 Log.i(TAG, "Observer no longer exists.");
6186 }
6187 } //end if observer
6188 } //end run
6189 });
6190 }
6191
6192 private boolean deleteApplicationCacheFilesLI(String packageName) {
6193 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006194 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006195 return false;
6196 }
6197 PackageParser.Package p;
6198 synchronized (mPackages) {
6199 p = mPackages.get(packageName);
6200 }
6201 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006202 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203 return false;
6204 }
6205 final ApplicationInfo applicationInfo = p.applicationInfo;
6206 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006207 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006208 return false;
6209 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006210 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006211 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006212 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006213 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006214 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215 + packageName);
6216 return false;
6217 }
6218 }
6219 return true;
6220 }
6221
6222 public void getPackageSizeInfo(final String packageName,
6223 final IPackageStatsObserver observer) {
6224 mContext.enforceCallingOrSelfPermission(
6225 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6226 // Queue up an async operation since the package deletion may take a little while.
6227 mHandler.post(new Runnable() {
6228 public void run() {
6229 mHandler.removeCallbacks(this);
6230 PackageStats lStats = new PackageStats(packageName);
6231 final boolean succeded;
6232 synchronized (mInstallLock) {
6233 succeded = getPackageSizeInfoLI(packageName, lStats);
6234 }
6235 if(observer != null) {
6236 try {
6237 observer.onGetStatsCompleted(lStats, succeded);
6238 } catch (RemoteException e) {
6239 Log.i(TAG, "Observer no longer exists.");
6240 }
6241 } //end if observer
6242 } //end run
6243 });
6244 }
6245
6246 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6247 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006248 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006249 return false;
6250 }
6251 PackageParser.Package p;
6252 boolean dataOnly = false;
6253 synchronized (mPackages) {
6254 p = mPackages.get(packageName);
6255 if(p == null) {
6256 dataOnly = true;
6257 PackageSetting ps = mSettings.mPackages.get(packageName);
6258 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006259 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006260 return false;
6261 }
6262 p = ps.pkg;
6263 }
6264 }
6265 String publicSrcDir = null;
6266 if(!dataOnly) {
6267 final ApplicationInfo applicationInfo = p.applicationInfo;
6268 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006269 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006270 return false;
6271 }
6272 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6273 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006274 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006275 if (mInstaller != null) {
6276 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006277 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006278 if (res < 0) {
6279 return false;
6280 } else {
6281 return true;
6282 }
6283 }
6284 return true;
6285 }
6286
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 public void addPackageToPreferred(String packageName) {
6289 mContext.enforceCallingOrSelfPermission(
6290 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006291 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 }
6293
6294 public void removePackageFromPreferred(String packageName) {
6295 mContext.enforceCallingOrSelfPermission(
6296 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006297 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006298 }
6299
6300 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006301 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006302 }
6303
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006304 int getUidTargetSdkVersionLockedLP(int uid) {
6305 Object obj = mSettings.getUserIdLP(uid);
6306 if (obj instanceof SharedUserSetting) {
6307 SharedUserSetting sus = (SharedUserSetting)obj;
6308 final int N = sus.packages.size();
6309 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6310 Iterator<PackageSetting> it = sus.packages.iterator();
6311 int i=0;
6312 while (it.hasNext()) {
6313 PackageSetting ps = it.next();
6314 if (ps.pkg != null) {
6315 int v = ps.pkg.applicationInfo.targetSdkVersion;
6316 if (v < vers) vers = v;
6317 }
6318 }
6319 return vers;
6320 } else if (obj instanceof PackageSetting) {
6321 PackageSetting ps = (PackageSetting)obj;
6322 if (ps.pkg != null) {
6323 return ps.pkg.applicationInfo.targetSdkVersion;
6324 }
6325 }
6326 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6327 }
6328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006329 public void addPreferredActivity(IntentFilter filter, int match,
6330 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006331 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006332 if (mContext.checkCallingOrSelfPermission(
6333 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6334 != PackageManager.PERMISSION_GRANTED) {
6335 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6336 < Build.VERSION_CODES.FROYO) {
6337 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6338 + Binder.getCallingUid());
6339 return;
6340 }
6341 mContext.enforceCallingOrSelfPermission(
6342 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6343 }
6344
6345 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006346 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6347 mSettings.mPreferredActivities.addFilter(
6348 new PreferredActivity(filter, match, set, activity));
6349 mSettings.writeLP();
6350 }
6351 }
6352
Satish Sampath8dbe6122009-06-02 23:35:54 +01006353 public void replacePreferredActivity(IntentFilter filter, int match,
6354 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006355 if (filter.countActions() != 1) {
6356 throw new IllegalArgumentException(
6357 "replacePreferredActivity expects filter to have only 1 action.");
6358 }
6359 if (filter.countCategories() != 1) {
6360 throw new IllegalArgumentException(
6361 "replacePreferredActivity expects filter to have only 1 category.");
6362 }
6363 if (filter.countDataAuthorities() != 0
6364 || filter.countDataPaths() != 0
6365 || filter.countDataSchemes() != 0
6366 || filter.countDataTypes() != 0) {
6367 throw new IllegalArgumentException(
6368 "replacePreferredActivity expects filter to have no data authorities, " +
6369 "paths, schemes or types.");
6370 }
6371 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006372 if (mContext.checkCallingOrSelfPermission(
6373 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6374 != PackageManager.PERMISSION_GRANTED) {
6375 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6376 < Build.VERSION_CODES.FROYO) {
6377 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6378 + Binder.getCallingUid());
6379 return;
6380 }
6381 mContext.enforceCallingOrSelfPermission(
6382 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6383 }
6384
Satish Sampath8dbe6122009-06-02 23:35:54 +01006385 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6386 String action = filter.getAction(0);
6387 String category = filter.getCategory(0);
6388 while (it.hasNext()) {
6389 PreferredActivity pa = it.next();
6390 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6391 it.remove();
6392 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6393 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6394 }
6395 }
6396 addPreferredActivity(filter, match, set, activity);
6397 }
6398 }
6399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006400 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006401 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006402 int uid = Binder.getCallingUid();
6403 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006404 if (pkg == null || pkg.applicationInfo.uid != uid) {
6405 if (mContext.checkCallingOrSelfPermission(
6406 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6407 != PackageManager.PERMISSION_GRANTED) {
6408 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6409 < Build.VERSION_CODES.FROYO) {
6410 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6411 + Binder.getCallingUid());
6412 return;
6413 }
6414 mContext.enforceCallingOrSelfPermission(
6415 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6416 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006417 }
6418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006419 if (clearPackagePreferredActivitiesLP(packageName)) {
6420 mSettings.writeLP();
6421 }
6422 }
6423 }
6424
6425 boolean clearPackagePreferredActivitiesLP(String packageName) {
6426 boolean changed = false;
6427 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6428 while (it.hasNext()) {
6429 PreferredActivity pa = it.next();
6430 if (pa.mActivity.getPackageName().equals(packageName)) {
6431 it.remove();
6432 changed = true;
6433 }
6434 }
6435 return changed;
6436 }
6437
6438 public int getPreferredActivities(List<IntentFilter> outFilters,
6439 List<ComponentName> outActivities, String packageName) {
6440
6441 int num = 0;
6442 synchronized (mPackages) {
6443 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6444 while (it.hasNext()) {
6445 PreferredActivity pa = it.next();
6446 if (packageName == null
6447 || pa.mActivity.getPackageName().equals(packageName)) {
6448 if (outFilters != null) {
6449 outFilters.add(new IntentFilter(pa));
6450 }
6451 if (outActivities != null) {
6452 outActivities.add(pa.mActivity);
6453 }
6454 }
6455 }
6456 }
6457
6458 return num;
6459 }
6460
6461 public void setApplicationEnabledSetting(String appPackageName,
6462 int newState, int flags) {
6463 setEnabledSetting(appPackageName, null, newState, flags);
6464 }
6465
6466 public void setComponentEnabledSetting(ComponentName componentName,
6467 int newState, int flags) {
6468 setEnabledSetting(componentName.getPackageName(),
6469 componentName.getClassName(), newState, flags);
6470 }
6471
6472 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006473 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006474 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6475 || newState == COMPONENT_ENABLED_STATE_ENABLED
6476 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6477 throw new IllegalArgumentException("Invalid new component state: "
6478 + newState);
6479 }
6480 PackageSetting pkgSetting;
6481 final int uid = Binder.getCallingUid();
6482 final int permission = mContext.checkCallingPermission(
6483 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6484 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006485 boolean sendNow = false;
6486 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006487 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006488 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006489 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006490 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006491 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006493 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006494 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006495 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006496 }
6497 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006498 "Unknown component: " + packageName
6499 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006500 }
6501 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6502 throw new SecurityException(
6503 "Permission Denial: attempt to change component state from pid="
6504 + Binder.getCallingPid()
6505 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6506 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006507 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006508 // We're dealing with an application/package level state change
6509 pkgSetting.enabled = newState;
6510 } else {
6511 // We're dealing with a component level state change
6512 switch (newState) {
6513 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006514 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006515 break;
6516 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006517 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006518 break;
6519 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006520 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006521 break;
6522 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006523 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006524 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006525 }
6526 }
6527 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006528 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006529 components = mPendingBroadcasts.get(packageName);
6530 boolean newPackage = components == null;
6531 if (newPackage) {
6532 components = new ArrayList<String>();
6533 }
6534 if (!components.contains(componentName)) {
6535 components.add(componentName);
6536 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006537 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6538 sendNow = true;
6539 // Purge entry from pending broadcast list if another one exists already
6540 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006541 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006542 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006543 if (newPackage) {
6544 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006545 }
6546 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6547 // Schedule a message
6548 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6549 }
6550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006551 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006553 long callingId = Binder.clearCallingIdentity();
6554 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006555 if (sendNow) {
6556 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006557 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006559 } finally {
6560 Binder.restoreCallingIdentity(callingId);
6561 }
6562 }
6563
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006564 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006565 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6566 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6567 + " components=" + componentNames);
6568 Bundle extras = new Bundle(4);
6569 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6570 String nameList[] = new String[componentNames.size()];
6571 componentNames.toArray(nameList);
6572 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006573 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6574 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006575 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006576 }
6577
Jacek Surazski65e13172009-04-28 15:26:38 +02006578 public String getInstallerPackageName(String packageName) {
6579 synchronized (mPackages) {
6580 PackageSetting pkg = mSettings.mPackages.get(packageName);
6581 if (pkg == null) {
6582 throw new IllegalArgumentException("Unknown package: " + packageName);
6583 }
6584 return pkg.installerPackageName;
6585 }
6586 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 public int getApplicationEnabledSetting(String appPackageName) {
6589 synchronized (mPackages) {
6590 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6591 if (pkg == null) {
6592 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6593 }
6594 return pkg.enabled;
6595 }
6596 }
6597
6598 public int getComponentEnabledSetting(ComponentName componentName) {
6599 synchronized (mPackages) {
6600 final String packageNameStr = componentName.getPackageName();
6601 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6602 if (pkg == null) {
6603 throw new IllegalArgumentException("Unknown component: " + componentName);
6604 }
6605 final String classNameStr = componentName.getClassName();
6606 return pkg.currentEnabledStateLP(classNameStr);
6607 }
6608 }
6609
6610 public void enterSafeMode() {
6611 if (!mSystemReady) {
6612 mSafeMode = true;
6613 }
6614 }
6615
6616 public void systemReady() {
6617 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006618
6619 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006620 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006621 mContext.getContentResolver(),
6622 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006623 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006624 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006625 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006627 }
6628
6629 public boolean isSafeMode() {
6630 return mSafeMode;
6631 }
6632
6633 public boolean hasSystemUidErrors() {
6634 return mHasSystemUidErrors;
6635 }
6636
6637 static String arrayToString(int[] array) {
6638 StringBuffer buf = new StringBuffer(128);
6639 buf.append('[');
6640 if (array != null) {
6641 for (int i=0; i<array.length; i++) {
6642 if (i > 0) buf.append(", ");
6643 buf.append(array[i]);
6644 }
6645 }
6646 buf.append(']');
6647 return buf.toString();
6648 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006650 @Override
6651 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6652 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6653 != PackageManager.PERMISSION_GRANTED) {
6654 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6655 + Binder.getCallingPid()
6656 + ", uid=" + Binder.getCallingUid()
6657 + " without permission "
6658 + android.Manifest.permission.DUMP);
6659 return;
6660 }
6661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006662 synchronized (mPackages) {
6663 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006664 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006665 pw.println(" ");
6666 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006667 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006668 pw.println(" ");
6669 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006670 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006671 pw.println(" ");
6672 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006673 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006674 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006675 pw.println("Permissions:");
6676 {
6677 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006678 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6679 pw.print(Integer.toHexString(System.identityHashCode(p)));
6680 pw.println("):");
6681 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6682 pw.print(" uid="); pw.print(p.uid);
6683 pw.print(" gids="); pw.print(arrayToString(p.gids));
6684 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006685 }
6686 }
6687 pw.println(" ");
6688 pw.println("Packages:");
6689 {
6690 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006691 pw.print(" Package [");
6692 pw.print(ps.realName != null ? ps.realName : ps.name);
6693 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006694 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6695 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006696 if (ps.realName != null) {
6697 pw.print(" compat name="); pw.println(ps.name);
6698 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006699 pw.print(" userId="); pw.print(ps.userId);
6700 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6701 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6702 pw.print(" pkg="); pw.println(ps.pkg);
6703 pw.print(" codePath="); pw.println(ps.codePathString);
6704 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006705 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006706 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006707 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006708 pw.print(" supportsScreens=[");
6709 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006710 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006711 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006712 if (!first) pw.print(", ");
6713 first = false;
6714 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006715 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006716 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006717 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006718 if (!first) pw.print(", ");
6719 first = false;
6720 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006721 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006722 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006723 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006724 if (!first) pw.print(", ");
6725 first = false;
6726 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006727 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006728 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006729 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006730 if (!first) pw.print(", ");
6731 first = false;
6732 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006733 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006734 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006735 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6736 if (!first) pw.print(", ");
6737 first = false;
6738 pw.print("anyDensity");
6739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006740 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006741 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006742 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6743 pw.print(" signatures="); pw.println(ps.signatures);
6744 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6745 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6746 pw.print(" installStatus="); pw.print(ps.installStatus);
6747 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006748 if (ps.disabledComponents.size() > 0) {
6749 pw.println(" disabledComponents:");
6750 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006751 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006752 }
6753 }
6754 if (ps.enabledComponents.size() > 0) {
6755 pw.println(" enabledComponents:");
6756 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006757 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006758 }
6759 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006760 if (ps.grantedPermissions.size() > 0) {
6761 pw.println(" grantedPermissions:");
6762 for (String s : ps.grantedPermissions) {
6763 pw.print(" "); pw.println(s);
6764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006765 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006766 if (ps.loadedPermissions.size() > 0) {
6767 pw.println(" loadedPermissions:");
6768 for (String s : ps.loadedPermissions) {
6769 pw.print(" "); pw.println(s);
6770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006771 }
6772 }
6773 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006774 if (mSettings.mRenamedPackages.size() > 0) {
6775 pw.println(" ");
6776 pw.println("Renamed packages:");
6777 for (HashMap.Entry<String, String> e
6778 : mSettings.mRenamedPackages.entrySet()) {
6779 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6780 pw.println(e.getValue());
6781 }
6782 }
6783 if (mSettings.mDisabledSysPackages.size() > 0) {
6784 pw.println(" ");
6785 pw.println("Hidden system packages:");
6786 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
6787 pw.print(" Package [");
6788 pw.print(ps.realName != null ? ps.realName : ps.name);
6789 pw.print("] (");
6790 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6791 pw.println("):");
6792 if (ps.realName != null) {
6793 pw.print(" compat name="); pw.println(ps.name);
6794 }
6795 pw.print(" userId="); pw.println(ps.userId);
6796 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6797 pw.print(" codePath="); pw.println(ps.codePathString);
6798 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
6799 }
6800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006801 pw.println(" ");
6802 pw.println("Shared Users:");
6803 {
6804 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006805 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6806 pw.print(Integer.toHexString(System.identityHashCode(su)));
6807 pw.println("):");
6808 pw.print(" userId="); pw.print(su.userId);
6809 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006810 pw.println(" grantedPermissions:");
6811 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006812 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006813 }
6814 pw.println(" loadedPermissions:");
6815 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006816 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006817 }
6818 }
6819 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006821 pw.println(" ");
6822 pw.println("Settings parse messages:");
6823 pw.println(mSettings.mReadMessages.toString());
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006824
6825 pw.println(" ");
6826 pw.println("Package warning messages:");
6827 File fname = getSettingsProblemFile();
6828 FileInputStream in;
6829 try {
6830 in = new FileInputStream(fname);
6831 int avail = in.available();
6832 byte[] data = new byte[avail];
6833 in.read(data);
6834 pw.println(new String(data));
6835 } catch (FileNotFoundException e) {
6836 } catch (IOException e) {
6837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006838 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006839
6840 synchronized (mProviders) {
6841 pw.println(" ");
6842 pw.println("Registered ContentProviders:");
6843 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006844 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006845 pw.println(p.toString());
6846 }
6847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006848 }
6849
6850 static final class BasePermission {
6851 final static int TYPE_NORMAL = 0;
6852 final static int TYPE_BUILTIN = 1;
6853 final static int TYPE_DYNAMIC = 2;
6854
6855 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006856 String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006857 final int type;
6858 PackageParser.Permission perm;
6859 PermissionInfo pendingInfo;
6860 int uid;
6861 int[] gids;
6862
6863 BasePermission(String _name, String _sourcePackage, int _type) {
6864 name = _name;
6865 sourcePackage = _sourcePackage;
6866 type = _type;
6867 }
6868 }
6869
6870 static class PackageSignatures {
6871 private Signature[] mSignatures;
6872
6873 PackageSignatures(Signature[] sigs) {
6874 assignSignatures(sigs);
6875 }
6876
6877 PackageSignatures() {
6878 }
6879
6880 void writeXml(XmlSerializer serializer, String tagName,
6881 ArrayList<Signature> pastSignatures) throws IOException {
6882 if (mSignatures == null) {
6883 return;
6884 }
6885 serializer.startTag(null, tagName);
6886 serializer.attribute(null, "count",
6887 Integer.toString(mSignatures.length));
6888 for (int i=0; i<mSignatures.length; i++) {
6889 serializer.startTag(null, "cert");
6890 final Signature sig = mSignatures[i];
6891 final int sigHash = sig.hashCode();
6892 final int numPast = pastSignatures.size();
6893 int j;
6894 for (j=0; j<numPast; j++) {
6895 Signature pastSig = pastSignatures.get(j);
6896 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
6897 serializer.attribute(null, "index", Integer.toString(j));
6898 break;
6899 }
6900 }
6901 if (j >= numPast) {
6902 pastSignatures.add(sig);
6903 serializer.attribute(null, "index", Integer.toString(numPast));
6904 serializer.attribute(null, "key", sig.toCharsString());
6905 }
6906 serializer.endTag(null, "cert");
6907 }
6908 serializer.endTag(null, tagName);
6909 }
6910
6911 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
6912 throws IOException, XmlPullParserException {
6913 String countStr = parser.getAttributeValue(null, "count");
6914 if (countStr == null) {
6915 reportSettingsProblem(Log.WARN,
6916 "Error in package manager settings: <signatures> has"
6917 + " no count at " + parser.getPositionDescription());
6918 XmlUtils.skipCurrentTag(parser);
6919 }
6920 final int count = Integer.parseInt(countStr);
6921 mSignatures = new Signature[count];
6922 int pos = 0;
6923
6924 int outerDepth = parser.getDepth();
6925 int type;
6926 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6927 && (type != XmlPullParser.END_TAG
6928 || parser.getDepth() > outerDepth)) {
6929 if (type == XmlPullParser.END_TAG
6930 || type == XmlPullParser.TEXT) {
6931 continue;
6932 }
6933
6934 String tagName = parser.getName();
6935 if (tagName.equals("cert")) {
6936 if (pos < count) {
6937 String index = parser.getAttributeValue(null, "index");
6938 if (index != null) {
6939 try {
6940 int idx = Integer.parseInt(index);
6941 String key = parser.getAttributeValue(null, "key");
6942 if (key == null) {
6943 if (idx >= 0 && idx < pastSignatures.size()) {
6944 Signature sig = pastSignatures.get(idx);
6945 if (sig != null) {
6946 mSignatures[pos] = pastSignatures.get(idx);
6947 pos++;
6948 } else {
6949 reportSettingsProblem(Log.WARN,
6950 "Error in package manager settings: <cert> "
6951 + "index " + index + " is not defined at "
6952 + parser.getPositionDescription());
6953 }
6954 } else {
6955 reportSettingsProblem(Log.WARN,
6956 "Error in package manager settings: <cert> "
6957 + "index " + index + " is out of bounds at "
6958 + parser.getPositionDescription());
6959 }
6960 } else {
6961 while (pastSignatures.size() <= idx) {
6962 pastSignatures.add(null);
6963 }
6964 Signature sig = new Signature(key);
6965 pastSignatures.set(idx, sig);
6966 mSignatures[pos] = sig;
6967 pos++;
6968 }
6969 } catch (NumberFormatException e) {
6970 reportSettingsProblem(Log.WARN,
6971 "Error in package manager settings: <cert> "
6972 + "index " + index + " is not a number at "
6973 + parser.getPositionDescription());
6974 }
6975 } else {
6976 reportSettingsProblem(Log.WARN,
6977 "Error in package manager settings: <cert> has"
6978 + " no index at " + parser.getPositionDescription());
6979 }
6980 } else {
6981 reportSettingsProblem(Log.WARN,
6982 "Error in package manager settings: too "
6983 + "many <cert> tags, expected " + count
6984 + " at " + parser.getPositionDescription());
6985 }
6986 } else {
6987 reportSettingsProblem(Log.WARN,
6988 "Unknown element under <cert>: "
6989 + parser.getName());
6990 }
6991 XmlUtils.skipCurrentTag(parser);
6992 }
6993
6994 if (pos < count) {
6995 // Should never happen -- there is an error in the written
6996 // settings -- but if it does we don't want to generate
6997 // a bad array.
6998 Signature[] newSigs = new Signature[pos];
6999 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7000 mSignatures = newSigs;
7001 }
7002 }
7003
7004 /**
7005 * If any of the given 'sigs' is contained in the existing signatures,
7006 * then completely replace the current signatures with the ones in
7007 * 'sigs'. This is used for updating an existing package to a newly
7008 * installed version.
7009 */
7010 boolean updateSignatures(Signature[] sigs, boolean update) {
7011 if (mSignatures == null) {
7012 if (update) {
7013 assignSignatures(sigs);
7014 }
7015 return true;
7016 }
7017 if (sigs == null) {
7018 return false;
7019 }
7020
7021 for (int i=0; i<sigs.length; i++) {
7022 Signature sig = sigs[i];
7023 for (int j=0; j<mSignatures.length; j++) {
7024 if (mSignatures[j].equals(sig)) {
7025 if (update) {
7026 assignSignatures(sigs);
7027 }
7028 return true;
7029 }
7030 }
7031 }
7032 return false;
7033 }
7034
7035 /**
7036 * If any of the given 'sigs' is contained in the existing signatures,
7037 * then add in any new signatures found in 'sigs'. This is used for
7038 * including a new package into an existing shared user id.
7039 */
7040 boolean mergeSignatures(Signature[] sigs, boolean update) {
7041 if (mSignatures == null) {
7042 if (update) {
7043 assignSignatures(sigs);
7044 }
7045 return true;
7046 }
7047 if (sigs == null) {
7048 return false;
7049 }
7050
7051 Signature[] added = null;
7052 int addedCount = 0;
7053 boolean haveMatch = false;
7054 for (int i=0; i<sigs.length; i++) {
7055 Signature sig = sigs[i];
7056 boolean found = false;
7057 for (int j=0; j<mSignatures.length; j++) {
7058 if (mSignatures[j].equals(sig)) {
7059 found = true;
7060 haveMatch = true;
7061 break;
7062 }
7063 }
7064
7065 if (!found) {
7066 if (added == null) {
7067 added = new Signature[sigs.length];
7068 }
7069 added[i] = sig;
7070 addedCount++;
7071 }
7072 }
7073
7074 if (!haveMatch) {
7075 // Nothing matched -- reject the new signatures.
7076 return false;
7077 }
7078 if (added == null) {
7079 // Completely matched -- nothing else to do.
7080 return true;
7081 }
7082
7083 // Add additional signatures in.
7084 if (update) {
7085 Signature[] total = new Signature[addedCount+mSignatures.length];
7086 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
7087 int j = mSignatures.length;
7088 for (int i=0; i<added.length; i++) {
7089 if (added[i] != null) {
7090 total[j] = added[i];
7091 j++;
7092 }
7093 }
7094 mSignatures = total;
7095 }
7096 return true;
7097 }
7098
7099 private void assignSignatures(Signature[] sigs) {
7100 if (sigs == null) {
7101 mSignatures = null;
7102 return;
7103 }
7104 mSignatures = new Signature[sigs.length];
7105 for (int i=0; i<sigs.length; i++) {
7106 mSignatures[i] = sigs[i];
7107 }
7108 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007110 @Override
7111 public String toString() {
7112 StringBuffer buf = new StringBuffer(128);
7113 buf.append("PackageSignatures{");
7114 buf.append(Integer.toHexString(System.identityHashCode(this)));
7115 buf.append(" [");
7116 if (mSignatures != null) {
7117 for (int i=0; i<mSignatures.length; i++) {
7118 if (i > 0) buf.append(", ");
7119 buf.append(Integer.toHexString(
7120 System.identityHashCode(mSignatures[i])));
7121 }
7122 }
7123 buf.append("]}");
7124 return buf.toString();
7125 }
7126 }
7127
7128 static class PreferredActivity extends IntentFilter {
7129 final int mMatch;
7130 final String[] mSetPackages;
7131 final String[] mSetClasses;
7132 final String[] mSetComponents;
7133 final ComponentName mActivity;
7134 final String mShortActivity;
7135 String mParseError;
7136
7137 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7138 ComponentName activity) {
7139 super(filter);
7140 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7141 mActivity = activity;
7142 mShortActivity = activity.flattenToShortString();
7143 mParseError = null;
7144 if (set != null) {
7145 final int N = set.length;
7146 String[] myPackages = new String[N];
7147 String[] myClasses = new String[N];
7148 String[] myComponents = new String[N];
7149 for (int i=0; i<N; i++) {
7150 ComponentName cn = set[i];
7151 if (cn == null) {
7152 mSetPackages = null;
7153 mSetClasses = null;
7154 mSetComponents = null;
7155 return;
7156 }
7157 myPackages[i] = cn.getPackageName().intern();
7158 myClasses[i] = cn.getClassName().intern();
7159 myComponents[i] = cn.flattenToShortString().intern();
7160 }
7161 mSetPackages = myPackages;
7162 mSetClasses = myClasses;
7163 mSetComponents = myComponents;
7164 } else {
7165 mSetPackages = null;
7166 mSetClasses = null;
7167 mSetComponents = null;
7168 }
7169 }
7170
7171 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7172 IOException {
7173 mShortActivity = parser.getAttributeValue(null, "name");
7174 mActivity = ComponentName.unflattenFromString(mShortActivity);
7175 if (mActivity == null) {
7176 mParseError = "Bad activity name " + mShortActivity;
7177 }
7178 String matchStr = parser.getAttributeValue(null, "match");
7179 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7180 String setCountStr = parser.getAttributeValue(null, "set");
7181 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7182
7183 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7184 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7185 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7186
7187 int setPos = 0;
7188
7189 int outerDepth = parser.getDepth();
7190 int type;
7191 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7192 && (type != XmlPullParser.END_TAG
7193 || parser.getDepth() > outerDepth)) {
7194 if (type == XmlPullParser.END_TAG
7195 || type == XmlPullParser.TEXT) {
7196 continue;
7197 }
7198
7199 String tagName = parser.getName();
7200 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7201 // + parser.getDepth() + " tag=" + tagName);
7202 if (tagName.equals("set")) {
7203 String name = parser.getAttributeValue(null, "name");
7204 if (name == null) {
7205 if (mParseError == null) {
7206 mParseError = "No name in set tag in preferred activity "
7207 + mShortActivity;
7208 }
7209 } else if (setPos >= setCount) {
7210 if (mParseError == null) {
7211 mParseError = "Too many set tags in preferred activity "
7212 + mShortActivity;
7213 }
7214 } else {
7215 ComponentName cn = ComponentName.unflattenFromString(name);
7216 if (cn == null) {
7217 if (mParseError == null) {
7218 mParseError = "Bad set name " + name + " in preferred activity "
7219 + mShortActivity;
7220 }
7221 } else {
7222 myPackages[setPos] = cn.getPackageName();
7223 myClasses[setPos] = cn.getClassName();
7224 myComponents[setPos] = name;
7225 setPos++;
7226 }
7227 }
7228 XmlUtils.skipCurrentTag(parser);
7229 } else if (tagName.equals("filter")) {
7230 //Log.i(TAG, "Starting to parse filter...");
7231 readFromXml(parser);
7232 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7233 // + parser.getDepth() + " tag=" + parser.getName());
7234 } else {
7235 reportSettingsProblem(Log.WARN,
7236 "Unknown element under <preferred-activities>: "
7237 + parser.getName());
7238 XmlUtils.skipCurrentTag(parser);
7239 }
7240 }
7241
7242 if (setPos != setCount) {
7243 if (mParseError == null) {
7244 mParseError = "Not enough set tags (expected " + setCount
7245 + " but found " + setPos + ") in " + mShortActivity;
7246 }
7247 }
7248
7249 mSetPackages = myPackages;
7250 mSetClasses = myClasses;
7251 mSetComponents = myComponents;
7252 }
7253
7254 public void writeToXml(XmlSerializer serializer) throws IOException {
7255 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7256 serializer.attribute(null, "name", mShortActivity);
7257 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7258 serializer.attribute(null, "set", Integer.toString(NS));
7259 for (int s=0; s<NS; s++) {
7260 serializer.startTag(null, "set");
7261 serializer.attribute(null, "name", mSetComponents[s]);
7262 serializer.endTag(null, "set");
7263 }
7264 serializer.startTag(null, "filter");
7265 super.writeToXml(serializer);
7266 serializer.endTag(null, "filter");
7267 }
7268
7269 boolean sameSet(List<ResolveInfo> query, int priority) {
7270 if (mSetPackages == null) return false;
7271 final int NQ = query.size();
7272 final int NS = mSetPackages.length;
7273 int numMatch = 0;
7274 for (int i=0; i<NQ; i++) {
7275 ResolveInfo ri = query.get(i);
7276 if (ri.priority != priority) continue;
7277 ActivityInfo ai = ri.activityInfo;
7278 boolean good = false;
7279 for (int j=0; j<NS; j++) {
7280 if (mSetPackages[j].equals(ai.packageName)
7281 && mSetClasses[j].equals(ai.name)) {
7282 numMatch++;
7283 good = true;
7284 break;
7285 }
7286 }
7287 if (!good) return false;
7288 }
7289 return numMatch == NS;
7290 }
7291 }
7292
7293 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007294 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007296 HashSet<String> grantedPermissions = new HashSet<String>();
7297 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007299 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007301 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007302 setFlags(pkgFlags);
7303 }
7304
7305 void setFlags(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007306 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007307 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08007308 (pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) |
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08007309 (pkgFlags & ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007310 }
7311 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007313 /**
7314 * Settings base class for pending and resolved classes.
7315 */
7316 static class PackageSettingBase extends GrantedPermissions {
7317 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007318 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007319 File codePath;
7320 String codePathString;
7321 File resourcePath;
7322 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007323 private long timeStamp;
7324 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007325 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007326
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007327 boolean uidError;
7328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007329 PackageSignatures signatures = new PackageSignatures();
7330
7331 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007333 /* Explicitly disabled components */
7334 HashSet<String> disabledComponents = new HashSet<String>(0);
7335 /* Explicitly enabled components */
7336 HashSet<String> enabledComponents = new HashSet<String>(0);
7337 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7338 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007339
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007340 PackageSettingBase origPackage;
7341
Jacek Surazski65e13172009-04-28 15:26:38 +02007342 /* package name of the app that installed this package */
7343 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007344
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007345 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007346 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007347 super(pkgFlags);
7348 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007349 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007350 init(codePath, resourcePath, pVersionCode);
7351 }
7352
7353 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007354 this.codePath = codePath;
7355 this.codePathString = codePath.toString();
7356 this.resourcePath = resourcePath;
7357 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007358 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007359 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007360
Jacek Surazski65e13172009-04-28 15:26:38 +02007361 public void setInstallerPackageName(String packageName) {
7362 installerPackageName = packageName;
7363 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007364
Jacek Surazski65e13172009-04-28 15:26:38 +02007365 String getInstallerPackageName() {
7366 return installerPackageName;
7367 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007369 public void setInstallStatus(int newStatus) {
7370 installStatus = newStatus;
7371 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007373 public int getInstallStatus() {
7374 return installStatus;
7375 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007377 public void setTimeStamp(long newStamp) {
7378 if (newStamp != timeStamp) {
7379 timeStamp = newStamp;
7380 timeStampString = Long.toString(newStamp);
7381 }
7382 }
7383
7384 public void setTimeStamp(long newStamp, String newStampStr) {
7385 timeStamp = newStamp;
7386 timeStampString = newStampStr;
7387 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007389 public long getTimeStamp() {
7390 return timeStamp;
7391 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007393 public String getTimeStampStr() {
7394 return timeStampString;
7395 }
7396
7397 public void copyFrom(PackageSettingBase base) {
7398 grantedPermissions = base.grantedPermissions;
7399 gids = base.gids;
7400 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007402 timeStamp = base.timeStamp;
7403 timeStampString = base.timeStampString;
7404 signatures = base.signatures;
7405 permissionsFixed = base.permissionsFixed;
7406 disabledComponents = base.disabledComponents;
7407 enabledComponents = base.enabledComponents;
7408 enabled = base.enabled;
7409 installStatus = base.installStatus;
7410 }
7411
7412 void enableComponentLP(String componentClassName) {
7413 disabledComponents.remove(componentClassName);
7414 enabledComponents.add(componentClassName);
7415 }
7416
7417 void disableComponentLP(String componentClassName) {
7418 enabledComponents.remove(componentClassName);
7419 disabledComponents.add(componentClassName);
7420 }
7421
7422 void restoreComponentLP(String componentClassName) {
7423 enabledComponents.remove(componentClassName);
7424 disabledComponents.remove(componentClassName);
7425 }
7426
7427 int currentEnabledStateLP(String componentName) {
7428 if (enabledComponents.contains(componentName)) {
7429 return COMPONENT_ENABLED_STATE_ENABLED;
7430 } else if (disabledComponents.contains(componentName)) {
7431 return COMPONENT_ENABLED_STATE_DISABLED;
7432 } else {
7433 return COMPONENT_ENABLED_STATE_DEFAULT;
7434 }
7435 }
7436 }
7437
7438 /**
7439 * Settings data for a particular package we know about.
7440 */
7441 static final class PackageSetting extends PackageSettingBase {
7442 int userId;
7443 PackageParser.Package pkg;
7444 SharedUserSetting sharedUser;
7445
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007446 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007447 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007448 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007449 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007451 @Override
7452 public String toString() {
7453 return "PackageSetting{"
7454 + Integer.toHexString(System.identityHashCode(this))
7455 + " " + name + "/" + userId + "}";
7456 }
7457 }
7458
7459 /**
7460 * Settings data for a particular shared user ID we know about.
7461 */
7462 static final class SharedUserSetting extends GrantedPermissions {
7463 final String name;
7464 int userId;
7465 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7466 final PackageSignatures signatures = new PackageSignatures();
7467
7468 SharedUserSetting(String _name, int _pkgFlags) {
7469 super(_pkgFlags);
7470 name = _name;
7471 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007473 @Override
7474 public String toString() {
7475 return "SharedUserSetting{"
7476 + Integer.toHexString(System.identityHashCode(this))
7477 + " " + name + "/" + userId + "}";
7478 }
7479 }
7480
7481 /**
7482 * Holds information about dynamic settings.
7483 */
7484 private static final class Settings {
7485 private final File mSettingsFilename;
7486 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007487 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007488 private final HashMap<String, PackageSetting> mPackages =
7489 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007490 // List of replaced system applications
7491 final HashMap<String, PackageSetting> mDisabledSysPackages =
7492 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007494 // The user's preferred activities associated with particular intent
7495 // filters.
7496 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7497 new IntentResolver<PreferredActivity, PreferredActivity>() {
7498 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007499 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007500 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007501 out.print(prefix); out.print(
7502 Integer.toHexString(System.identityHashCode(filter)));
7503 out.print(' ');
7504 out.print(filter.mActivity.flattenToShortString());
7505 out.print(" match=0x");
7506 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007507 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007508 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007509 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007510 out.print(prefix); out.print(" ");
7511 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007512 }
7513 }
7514 }
7515 };
7516 private final HashMap<String, SharedUserSetting> mSharedUsers =
7517 new HashMap<String, SharedUserSetting>();
7518 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7519 private final SparseArray<Object> mOtherUserIds =
7520 new SparseArray<Object>();
7521
7522 // For reading/writing settings file.
7523 private final ArrayList<Signature> mPastSignatures =
7524 new ArrayList<Signature>();
7525
7526 // Mapping from permission names to info about them.
7527 final HashMap<String, BasePermission> mPermissions =
7528 new HashMap<String, BasePermission>();
7529
7530 // Mapping from permission tree names to info about them.
7531 final HashMap<String, BasePermission> mPermissionTrees =
7532 new HashMap<String, BasePermission>();
7533
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007534 // Packages that have been uninstalled and still need their external
7535 // storage data deleted.
7536 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7537
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007538 // Packages that have been renamed since they were first installed.
7539 // Keys are the new names of the packages, values are the original
7540 // names. The packages appear everwhere else under their original
7541 // names.
7542 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007544 private final StringBuilder mReadMessages = new StringBuilder();
7545
7546 private static final class PendingPackage extends PackageSettingBase {
7547 final int sharedId;
7548
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007549 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007550 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007551 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007552 this.sharedId = sharedId;
7553 }
7554 }
7555 private final ArrayList<PendingPackage> mPendingPackages
7556 = new ArrayList<PendingPackage>();
7557
7558 Settings() {
7559 File dataDir = Environment.getDataDirectory();
7560 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007561 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7562 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007563 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007564 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007565 FileUtils.setPermissions(systemDir.toString(),
7566 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7567 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7568 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007569 FileUtils.setPermissions(systemSecureDir.toString(),
7570 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7571 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7572 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007573 mSettingsFilename = new File(systemDir, "packages.xml");
7574 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007575 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007576 }
7577
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007578 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007579 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007580 int pkgFlags, boolean create, boolean add) {
7581 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007582 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007583 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007584 return p;
7585 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007586
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007587 PackageSetting peekPackageLP(String name) {
7588 return mPackages.get(name);
7589 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007590 PackageSetting p = mPackages.get(name);
7591 if (p != null && p.codePath.getPath().equals(codePath)) {
7592 return p;
7593 }
7594 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007595 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007596 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007598 void setInstallStatus(String pkgName, int status) {
7599 PackageSetting p = mPackages.get(pkgName);
7600 if(p != null) {
7601 if(p.getInstallStatus() != status) {
7602 p.setInstallStatus(status);
7603 }
7604 }
7605 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007606
Jacek Surazski65e13172009-04-28 15:26:38 +02007607 void setInstallerPackageName(String pkgName,
7608 String installerPkgName) {
7609 PackageSetting p = mPackages.get(pkgName);
7610 if(p != null) {
7611 p.setInstallerPackageName(installerPkgName);
7612 }
7613 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007614
Jacek Surazski65e13172009-04-28 15:26:38 +02007615 String getInstallerPackageName(String pkgName) {
7616 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007617 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007618 }
7619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007620 int getInstallStatus(String pkgName) {
7621 PackageSetting p = mPackages.get(pkgName);
7622 if(p != null) {
7623 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007625 return -1;
7626 }
7627
7628 SharedUserSetting getSharedUserLP(String name,
7629 int pkgFlags, boolean create) {
7630 SharedUserSetting s = mSharedUsers.get(name);
7631 if (s == null) {
7632 if (!create) {
7633 return null;
7634 }
7635 s = new SharedUserSetting(name, pkgFlags);
7636 if (MULTIPLE_APPLICATION_UIDS) {
7637 s.userId = newUserIdLP(s);
7638 } else {
7639 s.userId = FIRST_APPLICATION_UID;
7640 }
7641 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7642 // < 0 means we couldn't assign a userid; fall out and return
7643 // s, which is currently null
7644 if (s.userId >= 0) {
7645 mSharedUsers.put(name, s);
7646 }
7647 }
7648
7649 return s;
7650 }
7651
7652 int disableSystemPackageLP(String name) {
7653 PackageSetting p = mPackages.get(name);
7654 if(p == null) {
7655 Log.w(TAG, "Package:"+name+" is not an installed package");
7656 return -1;
7657 }
7658 PackageSetting dp = mDisabledSysPackages.get(name);
7659 // always make sure the system package code and resource paths dont change
7660 if(dp == null) {
7661 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7662 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7663 }
7664 mDisabledSysPackages.put(name, p);
7665 }
7666 return removePackageLP(name);
7667 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007669 PackageSetting enableSystemPackageLP(String name) {
7670 PackageSetting p = mDisabledSysPackages.get(name);
7671 if(p == null) {
7672 Log.w(TAG, "Package:"+name+" is not disabled");
7673 return null;
7674 }
7675 // Reset flag in ApplicationInfo object
7676 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7677 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7678 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007679 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007680 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007681 mDisabledSysPackages.remove(name);
7682 return ret;
7683 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007684
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007685 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007686 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007687 PackageSetting p = mPackages.get(name);
7688 if (p != null) {
7689 if (p.userId == uid) {
7690 return p;
7691 }
7692 reportSettingsProblem(Log.ERROR,
7693 "Adding duplicate package, keeping first: " + name);
7694 return null;
7695 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007696 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007697 p.userId = uid;
7698 if (addUserIdLP(uid, p, name)) {
7699 mPackages.put(name, p);
7700 return p;
7701 }
7702 return null;
7703 }
7704
7705 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7706 SharedUserSetting s = mSharedUsers.get(name);
7707 if (s != null) {
7708 if (s.userId == uid) {
7709 return s;
7710 }
7711 reportSettingsProblem(Log.ERROR,
7712 "Adding duplicate shared user, keeping first: " + name);
7713 return null;
7714 }
7715 s = new SharedUserSetting(name, pkgFlags);
7716 s.userId = uid;
7717 if (addUserIdLP(uid, s, name)) {
7718 mSharedUsers.put(name, s);
7719 return s;
7720 }
7721 return null;
7722 }
7723
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007724 // Transfer ownership of permissions from one package to another.
7725 private void transferPermissions(String origPkg, String newPkg) {
7726 // Transfer ownership of permissions to the new package.
7727 for (int i=0; i<2; i++) {
7728 HashMap<String, BasePermission> permissions =
7729 i == 0 ? mPermissionTrees : mPermissions;
7730 for (BasePermission bp : permissions.values()) {
7731 if (origPkg.equals(bp.sourcePackage)) {
7732 if (DEBUG_UPGRADE) Log.v(TAG,
7733 "Moving permission " + bp.name
7734 + " from pkg " + bp.sourcePackage
7735 + " to " + newPkg);
7736 bp.sourcePackage = newPkg;
7737 bp.perm = null;
7738 if (bp.pendingInfo != null) {
7739 bp.sourcePackage = newPkg;
7740 }
7741 bp.uid = 0;
7742 bp.gids = null;
7743 }
7744 }
7745 }
7746 }
7747
7748 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007749 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007750 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007751 PackageSetting p = mPackages.get(name);
7752 if (p != null) {
7753 if (!p.codePath.equals(codePath)) {
7754 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007755 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007756 // This is an updated system app with versions in both system
7757 // and data partition. Just let the most recent version
7758 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007759 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007760 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007761 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007762 // Just a change in the code path is not an issue, but
7763 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007764 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007765 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007766 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007767 }
7768 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007769 reportSettingsProblem(Log.WARN,
7770 "Package " + name + " shared user changed from "
7771 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7772 + " to "
7773 + (sharedUser != null ? sharedUser.name : "<nothing>")
7774 + "; replacing with new");
7775 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007776 } else {
7777 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7778 // If what we are scanning is a system package, then
7779 // make it so, regardless of whether it was previously
7780 // installed only in the data partition.
7781 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007783 }
7784 }
7785 if (p == null) {
7786 // Create a new PackageSettings entry. this can end up here because
7787 // of code path mismatch or user id mismatch of an updated system partition
7788 if (!create) {
7789 return null;
7790 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007791 if (origPackage != null) {
7792 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007793 p = new PackageSetting(origPackage.name, name, codePath,
7794 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007795 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
7796 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08007797 // Note that we will retain the new package's signature so
7798 // that we can keep its data.
7799 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007800 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08007801 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007802 p.sharedUser = origPackage.sharedUser;
7803 p.userId = origPackage.userId;
7804 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007805 mRenamedPackages.put(name, origPackage.name);
7806 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007807 // Update new package state.
7808 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007809 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007810 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007811 p.setTimeStamp(codePath.lastModified());
7812 p.sharedUser = sharedUser;
7813 if (sharedUser != null) {
7814 p.userId = sharedUser.userId;
7815 } else if (MULTIPLE_APPLICATION_UIDS) {
7816 // Clone the setting here for disabled system packages
7817 PackageSetting dis = mDisabledSysPackages.get(name);
7818 if (dis != null) {
7819 // For disabled packages a new setting is created
7820 // from the existing user id. This still has to be
7821 // added to list of user id's
7822 // Copy signatures from previous setting
7823 if (dis.signatures.mSignatures != null) {
7824 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
7825 }
7826 p.userId = dis.userId;
7827 // Clone permissions
7828 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
7829 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
7830 // Clone component info
7831 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
7832 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
7833 // Add new setting to list of user ids
7834 addUserIdLP(p.userId, p, name);
7835 } else {
7836 // Assign new user id
7837 p.userId = newUserIdLP(p);
7838 }
7839 } else {
7840 p.userId = FIRST_APPLICATION_UID;
7841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007842 }
7843 if (p.userId < 0) {
7844 reportSettingsProblem(Log.WARN,
7845 "Package " + name + " could not be assigned a valid uid");
7846 return null;
7847 }
7848 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007849 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007850 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007851 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007852 }
7853 }
7854 return p;
7855 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007856
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007857 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007858 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007859 String codePath = pkg.applicationInfo.sourceDir;
7860 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007861 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007862 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007863 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007864 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007865 p.codePath = new File(codePath);
7866 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007867 }
7868 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007869 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007870 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007871 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007872 p.resourcePath = new File(resourcePath);
7873 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007874 }
7875 // Update version code if needed
7876 if (pkg.mVersionCode != p.versionCode) {
7877 p.versionCode = pkg.mVersionCode;
7878 }
7879 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
7880 }
7881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007882 // Utility method that adds a PackageSetting to mPackages and
7883 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007884 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007885 SharedUserSetting sharedUser) {
7886 mPackages.put(name, p);
7887 if (sharedUser != null) {
7888 if (p.sharedUser != null && p.sharedUser != sharedUser) {
7889 reportSettingsProblem(Log.ERROR,
7890 "Package " + p.name + " was user "
7891 + p.sharedUser + " but is now " + sharedUser
7892 + "; I am not changing its files so it will probably fail!");
7893 p.sharedUser.packages.remove(p);
7894 } else if (p.userId != sharedUser.userId) {
7895 reportSettingsProblem(Log.ERROR,
7896 "Package " + p.name + " was user id " + p.userId
7897 + " but is now user " + sharedUser
7898 + " with id " + sharedUser.userId
7899 + "; I am not changing its files so it will probably fail!");
7900 }
7901
7902 sharedUser.packages.add(p);
7903 p.sharedUser = sharedUser;
7904 p.userId = sharedUser.userId;
7905 }
7906 }
7907
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007908 /*
7909 * Update the shared user setting when a package using
7910 * specifying the shared user id is removed. The gids
7911 * associated with each permission of the deleted package
7912 * are removed from the shared user's gid list only if its
7913 * not in use by other permissions of packages in the
7914 * shared user setting.
7915 */
7916 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007917 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007918 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007919 return;
7920 }
7921 // No sharedUserId
7922 if (deletedPs.sharedUser == null) {
7923 return;
7924 }
7925 SharedUserSetting sus = deletedPs.sharedUser;
7926 // Update permissions
7927 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
7928 boolean used = false;
7929 if (!sus.grantedPermissions.contains (eachPerm)) {
7930 continue;
7931 }
7932 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007933 if (pkg.pkg != null &&
7934 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
7935 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007936 used = true;
7937 break;
7938 }
7939 }
7940 if (!used) {
7941 // can safely delete this permission from list
7942 sus.grantedPermissions.remove(eachPerm);
7943 sus.loadedPermissions.remove(eachPerm);
7944 }
7945 }
7946 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007947 int newGids[] = globalGids;
7948 for (String eachPerm : sus.grantedPermissions) {
7949 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007950 if (bp != null) {
7951 newGids = appendInts(newGids, bp.gids);
7952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007953 }
7954 sus.gids = newGids;
7955 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007957 private int removePackageLP(String name) {
7958 PackageSetting p = mPackages.get(name);
7959 if (p != null) {
7960 mPackages.remove(name);
7961 if (p.sharedUser != null) {
7962 p.sharedUser.packages.remove(p);
7963 if (p.sharedUser.packages.size() == 0) {
7964 mSharedUsers.remove(p.sharedUser.name);
7965 removeUserIdLP(p.sharedUser.userId);
7966 return p.sharedUser.userId;
7967 }
7968 } else {
7969 removeUserIdLP(p.userId);
7970 return p.userId;
7971 }
7972 }
7973 return -1;
7974 }
7975
7976 private boolean addUserIdLP(int uid, Object obj, Object name) {
7977 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
7978 return false;
7979 }
7980
7981 if (uid >= FIRST_APPLICATION_UID) {
7982 int N = mUserIds.size();
7983 final int index = uid - FIRST_APPLICATION_UID;
7984 while (index >= N) {
7985 mUserIds.add(null);
7986 N++;
7987 }
7988 if (mUserIds.get(index) != null) {
7989 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007990 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007991 + " name=" + name);
7992 return false;
7993 }
7994 mUserIds.set(index, obj);
7995 } else {
7996 if (mOtherUserIds.get(uid) != null) {
7997 reportSettingsProblem(Log.ERROR,
7998 "Adding duplicate shared id: " + uid
7999 + " name=" + name);
8000 return false;
8001 }
8002 mOtherUserIds.put(uid, obj);
8003 }
8004 return true;
8005 }
8006
8007 public Object getUserIdLP(int uid) {
8008 if (uid >= FIRST_APPLICATION_UID) {
8009 int N = mUserIds.size();
8010 final int index = uid - FIRST_APPLICATION_UID;
8011 return index < N ? mUserIds.get(index) : null;
8012 } else {
8013 return mOtherUserIds.get(uid);
8014 }
8015 }
8016
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008017 private Set<String> findPackagesWithFlag(int flag) {
8018 Set<String> ret = new HashSet<String>();
8019 for (PackageSetting ps : mPackages.values()) {
8020 // Has to match atleast all the flag bits set on flag
8021 if ((ps.pkgFlags & flag) == flag) {
8022 ret.add(ps.name);
8023 }
8024 }
8025 return ret;
8026 }
8027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008028 private void removeUserIdLP(int uid) {
8029 if (uid >= FIRST_APPLICATION_UID) {
8030 int N = mUserIds.size();
8031 final int index = uid - FIRST_APPLICATION_UID;
8032 if (index < N) mUserIds.set(index, null);
8033 } else {
8034 mOtherUserIds.remove(uid);
8035 }
8036 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008038 void writeLP() {
8039 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8040
8041 // Keep the old settings around until we know the new ones have
8042 // been successfully written.
8043 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008044 // Presence of backup settings file indicates that we failed
8045 // to persist settings earlier. So preserve the older
8046 // backup for future reference since the current settings
8047 // might have been corrupted.
8048 if (!mBackupSettingsFilename.exists()) {
8049 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008050 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008051 return;
8052 }
8053 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008054 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008056 }
8057
8058 mPastSignatures.clear();
8059
8060 try {
8061 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8062
8063 //XmlSerializer serializer = XmlUtils.serializerInstance();
8064 XmlSerializer serializer = new FastXmlSerializer();
8065 serializer.setOutput(str, "utf-8");
8066 serializer.startDocument(null, true);
8067 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8068
8069 serializer.startTag(null, "packages");
8070
8071 serializer.startTag(null, "permission-trees");
8072 for (BasePermission bp : mPermissionTrees.values()) {
8073 writePermission(serializer, bp);
8074 }
8075 serializer.endTag(null, "permission-trees");
8076
8077 serializer.startTag(null, "permissions");
8078 for (BasePermission bp : mPermissions.values()) {
8079 writePermission(serializer, bp);
8080 }
8081 serializer.endTag(null, "permissions");
8082
8083 for (PackageSetting pkg : mPackages.values()) {
8084 writePackage(serializer, pkg);
8085 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008087 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8088 writeDisabledSysPackage(serializer, pkg);
8089 }
8090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008091 serializer.startTag(null, "preferred-activities");
8092 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8093 serializer.startTag(null, "item");
8094 pa.writeToXml(serializer);
8095 serializer.endTag(null, "item");
8096 }
8097 serializer.endTag(null, "preferred-activities");
8098
8099 for (SharedUserSetting usr : mSharedUsers.values()) {
8100 serializer.startTag(null, "shared-user");
8101 serializer.attribute(null, "name", usr.name);
8102 serializer.attribute(null, "userId",
8103 Integer.toString(usr.userId));
8104 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8105 serializer.startTag(null, "perms");
8106 for (String name : usr.grantedPermissions) {
8107 serializer.startTag(null, "item");
8108 serializer.attribute(null, "name", name);
8109 serializer.endTag(null, "item");
8110 }
8111 serializer.endTag(null, "perms");
8112 serializer.endTag(null, "shared-user");
8113 }
8114
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008115 if (mPackagesToBeCleaned.size() > 0) {
8116 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8117 serializer.startTag(null, "cleaning-package");
8118 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8119 serializer.endTag(null, "cleaning-package");
8120 }
8121 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008122
8123 if (mRenamedPackages.size() > 0) {
8124 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8125 serializer.startTag(null, "renamed-package");
8126 serializer.attribute(null, "new", e.getKey());
8127 serializer.attribute(null, "old", e.getValue());
8128 serializer.endTag(null, "renamed-package");
8129 }
8130 }
8131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008132 serializer.endTag(null, "packages");
8133
8134 serializer.endDocument();
8135
8136 str.flush();
8137 str.close();
8138
8139 // New settings successfully written, old ones are no longer
8140 // needed.
8141 mBackupSettingsFilename.delete();
8142 FileUtils.setPermissions(mSettingsFilename.toString(),
8143 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8144 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8145 |FileUtils.S_IROTH,
8146 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008147
8148 // Write package list file now, use a JournaledFile.
8149 //
8150 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8151 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8152
8153 str = new FileOutputStream(journal.chooseForWrite());
8154 try {
8155 StringBuilder sb = new StringBuilder();
8156 for (PackageSetting pkg : mPackages.values()) {
8157 ApplicationInfo ai = pkg.pkg.applicationInfo;
8158 String dataPath = ai.dataDir;
8159 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8160
8161 // Avoid any application that has a space in its path
8162 // or that is handled by the system.
8163 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8164 continue;
8165
8166 // we store on each line the following information for now:
8167 //
8168 // pkgName - package name
8169 // userId - application-specific user id
8170 // debugFlag - 0 or 1 if the package is debuggable.
8171 // dataPath - path to package's data path
8172 //
8173 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8174 //
8175 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8176 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8177 // system/core/run-as/run-as.c
8178 //
8179 sb.setLength(0);
8180 sb.append(ai.packageName);
8181 sb.append(" ");
8182 sb.append((int)ai.uid);
8183 sb.append(isDebug ? " 1 " : " 0 ");
8184 sb.append(dataPath);
8185 sb.append("\n");
8186 str.write(sb.toString().getBytes());
8187 }
8188 str.flush();
8189 str.close();
8190 journal.commit();
8191 }
8192 catch (Exception e) {
8193 journal.rollback();
8194 }
8195
8196 FileUtils.setPermissions(mPackageListFilename.toString(),
8197 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8198 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8199 |FileUtils.S_IROTH,
8200 -1, -1);
8201
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008202 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008203
8204 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008205 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 -08008206 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008207 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 -08008208 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008209 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008210 if (mSettingsFilename.exists()) {
8211 if (!mSettingsFilename.delete()) {
8212 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8213 }
8214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008215 //Debug.stopMethodTracing();
8216 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008217
8218 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008219 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008220 serializer.startTag(null, "updated-package");
8221 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008222 if (pkg.realName != null) {
8223 serializer.attribute(null, "realName", pkg.realName);
8224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008225 serializer.attribute(null, "codePath", pkg.codePathString);
8226 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008227 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008228 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8229 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8230 }
8231 if (pkg.sharedUser == null) {
8232 serializer.attribute(null, "userId",
8233 Integer.toString(pkg.userId));
8234 } else {
8235 serializer.attribute(null, "sharedUserId",
8236 Integer.toString(pkg.userId));
8237 }
8238 serializer.startTag(null, "perms");
8239 if (pkg.sharedUser == null) {
8240 // If this is a shared user, the permissions will
8241 // be written there. We still need to write an
8242 // empty permissions list so permissionsFixed will
8243 // be set.
8244 for (final String name : pkg.grantedPermissions) {
8245 BasePermission bp = mPermissions.get(name);
8246 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
8247 // We only need to write signature or system permissions but this wont
8248 // match the semantics of grantedPermissions. So write all permissions.
8249 serializer.startTag(null, "item");
8250 serializer.attribute(null, "name", name);
8251 serializer.endTag(null, "item");
8252 }
8253 }
8254 }
8255 serializer.endTag(null, "perms");
8256 serializer.endTag(null, "updated-package");
8257 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008258
8259 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008260 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008261 serializer.startTag(null, "package");
8262 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008263 if (pkg.realName != null) {
8264 serializer.attribute(null, "realName", pkg.realName);
8265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008266 serializer.attribute(null, "codePath", pkg.codePathString);
8267 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8268 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8269 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008270 serializer.attribute(null, "flags",
8271 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008272 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008273 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008274 if (pkg.sharedUser == null) {
8275 serializer.attribute(null, "userId",
8276 Integer.toString(pkg.userId));
8277 } else {
8278 serializer.attribute(null, "sharedUserId",
8279 Integer.toString(pkg.userId));
8280 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008281 if (pkg.uidError) {
8282 serializer.attribute(null, "uidError", "true");
8283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008284 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8285 serializer.attribute(null, "enabled",
8286 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8287 ? "true" : "false");
8288 }
8289 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8290 serializer.attribute(null, "installStatus", "false");
8291 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008292 if (pkg.installerPackageName != null) {
8293 serializer.attribute(null, "installer", pkg.installerPackageName);
8294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008295 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8296 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8297 serializer.startTag(null, "perms");
8298 if (pkg.sharedUser == null) {
8299 // If this is a shared user, the permissions will
8300 // be written there. We still need to write an
8301 // empty permissions list so permissionsFixed will
8302 // be set.
8303 for (final String name : pkg.grantedPermissions) {
8304 serializer.startTag(null, "item");
8305 serializer.attribute(null, "name", name);
8306 serializer.endTag(null, "item");
8307 }
8308 }
8309 serializer.endTag(null, "perms");
8310 }
8311 if (pkg.disabledComponents.size() > 0) {
8312 serializer.startTag(null, "disabled-components");
8313 for (final String name : pkg.disabledComponents) {
8314 serializer.startTag(null, "item");
8315 serializer.attribute(null, "name", name);
8316 serializer.endTag(null, "item");
8317 }
8318 serializer.endTag(null, "disabled-components");
8319 }
8320 if (pkg.enabledComponents.size() > 0) {
8321 serializer.startTag(null, "enabled-components");
8322 for (final String name : pkg.enabledComponents) {
8323 serializer.startTag(null, "item");
8324 serializer.attribute(null, "name", name);
8325 serializer.endTag(null, "item");
8326 }
8327 serializer.endTag(null, "enabled-components");
8328 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008330 serializer.endTag(null, "package");
8331 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008333 void writePermission(XmlSerializer serializer, BasePermission bp)
8334 throws XmlPullParserException, java.io.IOException {
8335 if (bp.type != BasePermission.TYPE_BUILTIN
8336 && bp.sourcePackage != null) {
8337 serializer.startTag(null, "item");
8338 serializer.attribute(null, "name", bp.name);
8339 serializer.attribute(null, "package", bp.sourcePackage);
8340 if (DEBUG_SETTINGS) Log.v(TAG,
8341 "Writing perm: name=" + bp.name + " type=" + bp.type);
8342 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8343 PermissionInfo pi = bp.perm != null ? bp.perm.info
8344 : bp.pendingInfo;
8345 if (pi != null) {
8346 serializer.attribute(null, "type", "dynamic");
8347 if (pi.icon != 0) {
8348 serializer.attribute(null, "icon",
8349 Integer.toString(pi.icon));
8350 }
8351 if (pi.nonLocalizedLabel != null) {
8352 serializer.attribute(null, "label",
8353 pi.nonLocalizedLabel.toString());
8354 }
8355 if (pi.protectionLevel !=
8356 PermissionInfo.PROTECTION_NORMAL) {
8357 serializer.attribute(null, "protection",
8358 Integer.toString(pi.protectionLevel));
8359 }
8360 }
8361 }
8362 serializer.endTag(null, "item");
8363 }
8364 }
8365
8366 String getReadMessagesLP() {
8367 return mReadMessages.toString();
8368 }
8369
Oscar Montemayora8529f62009-11-18 10:14:20 -08008370 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008371 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8372 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008373 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008374 while(its.hasNext()) {
8375 String key = its.next();
8376 PackageSetting ps = mPackages.get(key);
8377 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008378 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008379 }
8380 }
8381 return ret;
8382 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008384 boolean readLP() {
8385 FileInputStream str = null;
8386 if (mBackupSettingsFilename.exists()) {
8387 try {
8388 str = new FileInputStream(mBackupSettingsFilename);
8389 mReadMessages.append("Reading from backup settings file\n");
8390 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008391 if (mSettingsFilename.exists()) {
8392 // If both the backup and settings file exist, we
8393 // ignore the settings since it might have been
8394 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008395 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008396 mSettingsFilename.delete();
8397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008398 } catch (java.io.IOException e) {
8399 // We'll try for the normal settings file.
8400 }
8401 }
8402
8403 mPastSignatures.clear();
8404
8405 try {
8406 if (str == null) {
8407 if (!mSettingsFilename.exists()) {
8408 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008409 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008410 return false;
8411 }
8412 str = new FileInputStream(mSettingsFilename);
8413 }
8414 XmlPullParser parser = Xml.newPullParser();
8415 parser.setInput(str, null);
8416
8417 int type;
8418 while ((type=parser.next()) != XmlPullParser.START_TAG
8419 && type != XmlPullParser.END_DOCUMENT) {
8420 ;
8421 }
8422
8423 if (type != XmlPullParser.START_TAG) {
8424 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008425 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008426 return false;
8427 }
8428
8429 int outerDepth = parser.getDepth();
8430 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8431 && (type != XmlPullParser.END_TAG
8432 || parser.getDepth() > outerDepth)) {
8433 if (type == XmlPullParser.END_TAG
8434 || type == XmlPullParser.TEXT) {
8435 continue;
8436 }
8437
8438 String tagName = parser.getName();
8439 if (tagName.equals("package")) {
8440 readPackageLP(parser);
8441 } else if (tagName.equals("permissions")) {
8442 readPermissionsLP(mPermissions, parser);
8443 } else if (tagName.equals("permission-trees")) {
8444 readPermissionsLP(mPermissionTrees, parser);
8445 } else if (tagName.equals("shared-user")) {
8446 readSharedUserLP(parser);
8447 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008448 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008449 } else if (tagName.equals("preferred-activities")) {
8450 readPreferredActivitiesLP(parser);
8451 } else if(tagName.equals("updated-package")) {
8452 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008453 } else if (tagName.equals("cleaning-package")) {
8454 String name = parser.getAttributeValue(null, "name");
8455 if (name != null) {
8456 mPackagesToBeCleaned.add(name);
8457 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008458 } else if (tagName.equals("renamed-package")) {
8459 String nname = parser.getAttributeValue(null, "new");
8460 String oname = parser.getAttributeValue(null, "old");
8461 if (nname != null && oname != null) {
8462 mRenamedPackages.put(nname, oname);
8463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008464 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008465 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008466 + parser.getName());
8467 XmlUtils.skipCurrentTag(parser);
8468 }
8469 }
8470
8471 str.close();
8472
8473 } catch(XmlPullParserException e) {
8474 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008475 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008476
8477 } catch(java.io.IOException e) {
8478 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008479 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008480
8481 }
8482
8483 int N = mPendingPackages.size();
8484 for (int i=0; i<N; i++) {
8485 final PendingPackage pp = mPendingPackages.get(i);
8486 Object idObj = getUserIdLP(pp.sharedId);
8487 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008488 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008489 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008490 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008491 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008492 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008493 + pp.name);
8494 continue;
8495 }
8496 p.copyFrom(pp);
8497 } else if (idObj != null) {
8498 String msg = "Bad package setting: package " + pp.name
8499 + " has shared uid " + pp.sharedId
8500 + " that is not a shared uid\n";
8501 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008502 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008503 } else {
8504 String msg = "Bad package setting: package " + pp.name
8505 + " has shared uid " + pp.sharedId
8506 + " that is not defined\n";
8507 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008508 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008509 }
8510 }
8511 mPendingPackages.clear();
8512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008513 mReadMessages.append("Read completed successfully: "
8514 + mPackages.size() + " packages, "
8515 + mSharedUsers.size() + " shared uids\n");
8516
8517 return true;
8518 }
8519
8520 private int readInt(XmlPullParser parser, String ns, String name,
8521 int defValue) {
8522 String v = parser.getAttributeValue(ns, name);
8523 try {
8524 if (v == null) {
8525 return defValue;
8526 }
8527 return Integer.parseInt(v);
8528 } catch (NumberFormatException e) {
8529 reportSettingsProblem(Log.WARN,
8530 "Error in package manager settings: attribute " +
8531 name + " has bad integer value " + v + " at "
8532 + parser.getPositionDescription());
8533 }
8534 return defValue;
8535 }
8536
8537 private void readPermissionsLP(HashMap<String, BasePermission> out,
8538 XmlPullParser parser)
8539 throws IOException, XmlPullParserException {
8540 int outerDepth = parser.getDepth();
8541 int type;
8542 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8543 && (type != XmlPullParser.END_TAG
8544 || parser.getDepth() > outerDepth)) {
8545 if (type == XmlPullParser.END_TAG
8546 || type == XmlPullParser.TEXT) {
8547 continue;
8548 }
8549
8550 String tagName = parser.getName();
8551 if (tagName.equals("item")) {
8552 String name = parser.getAttributeValue(null, "name");
8553 String sourcePackage = parser.getAttributeValue(null, "package");
8554 String ptype = parser.getAttributeValue(null, "type");
8555 if (name != null && sourcePackage != null) {
8556 boolean dynamic = "dynamic".equals(ptype);
8557 BasePermission bp = new BasePermission(name, sourcePackage,
8558 dynamic
8559 ? BasePermission.TYPE_DYNAMIC
8560 : BasePermission.TYPE_NORMAL);
8561 if (dynamic) {
8562 PermissionInfo pi = new PermissionInfo();
8563 pi.packageName = sourcePackage.intern();
8564 pi.name = name.intern();
8565 pi.icon = readInt(parser, null, "icon", 0);
8566 pi.nonLocalizedLabel = parser.getAttributeValue(
8567 null, "label");
8568 pi.protectionLevel = readInt(parser, null, "protection",
8569 PermissionInfo.PROTECTION_NORMAL);
8570 bp.pendingInfo = pi;
8571 }
8572 out.put(bp.name, bp);
8573 } else {
8574 reportSettingsProblem(Log.WARN,
8575 "Error in package manager settings: permissions has"
8576 + " no name at " + parser.getPositionDescription());
8577 }
8578 } else {
8579 reportSettingsProblem(Log.WARN,
8580 "Unknown element reading permissions: "
8581 + parser.getName() + " at "
8582 + parser.getPositionDescription());
8583 }
8584 XmlUtils.skipCurrentTag(parser);
8585 }
8586 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008588 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008589 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008590 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008591 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008592 String codePathStr = parser.getAttributeValue(null, "codePath");
8593 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008594 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008595 resourcePathStr = codePathStr;
8596 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008597 String version = parser.getAttributeValue(null, "version");
8598 int versionCode = 0;
8599 if (version != null) {
8600 try {
8601 versionCode = Integer.parseInt(version);
8602 } catch (NumberFormatException e) {
8603 }
8604 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008606 int pkgFlags = 0;
8607 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008608 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008609 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008610 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008611 String timeStampStr = parser.getAttributeValue(null, "ts");
8612 if (timeStampStr != null) {
8613 try {
8614 long timeStamp = Long.parseLong(timeStampStr);
8615 ps.setTimeStamp(timeStamp, timeStampStr);
8616 } catch (NumberFormatException e) {
8617 }
8618 }
8619 String idStr = parser.getAttributeValue(null, "userId");
8620 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8621 if(ps.userId <= 0) {
8622 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8623 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8624 }
8625 int outerDepth = parser.getDepth();
8626 int type;
8627 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8628 && (type != XmlPullParser.END_TAG
8629 || parser.getDepth() > outerDepth)) {
8630 if (type == XmlPullParser.END_TAG
8631 || type == XmlPullParser.TEXT) {
8632 continue;
8633 }
8634
8635 String tagName = parser.getName();
8636 if (tagName.equals("perms")) {
8637 readGrantedPermissionsLP(parser,
8638 ps.grantedPermissions);
8639 } else {
8640 reportSettingsProblem(Log.WARN,
8641 "Unknown element under <updated-package>: "
8642 + parser.getName());
8643 XmlUtils.skipCurrentTag(parser);
8644 }
8645 }
8646 mDisabledSysPackages.put(name, ps);
8647 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008649 private void readPackageLP(XmlPullParser parser)
8650 throws XmlPullParserException, IOException {
8651 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008652 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008653 String idStr = null;
8654 String sharedIdStr = null;
8655 String codePathStr = null;
8656 String resourcePathStr = null;
8657 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008658 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008659 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008660 int pkgFlags = 0;
8661 String timeStampStr;
8662 long timeStamp = 0;
8663 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008664 String version = null;
8665 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008666 try {
8667 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008668 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008669 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008670 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008671 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8672 codePathStr = parser.getAttributeValue(null, "codePath");
8673 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008674 version = parser.getAttributeValue(null, "version");
8675 if (version != null) {
8676 try {
8677 versionCode = Integer.parseInt(version);
8678 } catch (NumberFormatException e) {
8679 }
8680 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008681 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008682
8683 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008684 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008685 try {
8686 pkgFlags = Integer.parseInt(systemStr);
8687 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008688 }
8689 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008690 // For backward compatibility
8691 systemStr = parser.getAttributeValue(null, "system");
8692 if (systemStr != null) {
8693 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8694 } else {
8695 // Old settings that don't specify system... just treat
8696 // them as system, good enough.
8697 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008699 }
8700 timeStampStr = parser.getAttributeValue(null, "ts");
8701 if (timeStampStr != null) {
8702 try {
8703 timeStamp = Long.parseLong(timeStampStr);
8704 } catch (NumberFormatException e) {
8705 }
8706 }
8707 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8708 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8709 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8710 if (resourcePathStr == null) {
8711 resourcePathStr = codePathStr;
8712 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008713 if (realName != null) {
8714 realName = realName.intern();
8715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008716 if (name == null) {
8717 reportSettingsProblem(Log.WARN,
8718 "Error in package manager settings: <package> has no name at "
8719 + parser.getPositionDescription());
8720 } else if (codePathStr == null) {
8721 reportSettingsProblem(Log.WARN,
8722 "Error in package manager settings: <package> has no codePath at "
8723 + parser.getPositionDescription());
8724 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008725 packageSetting = addPackageLP(name.intern(), realName,
8726 new File(codePathStr), new File(resourcePathStr),
8727 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008728 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8729 + ": userId=" + userId + " pkg=" + packageSetting);
8730 if (packageSetting == null) {
8731 reportSettingsProblem(Log.ERROR,
8732 "Failure adding uid " + userId
8733 + " while parsing settings at "
8734 + parser.getPositionDescription());
8735 } else {
8736 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8737 }
8738 } else if (sharedIdStr != null) {
8739 userId = sharedIdStr != null
8740 ? Integer.parseInt(sharedIdStr) : 0;
8741 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008742 packageSetting = new PendingPackage(name.intern(), realName,
8743 new File(codePathStr), new File(resourcePathStr),
8744 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008745 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8746 mPendingPackages.add((PendingPackage) packageSetting);
8747 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8748 + ": sharedUserId=" + userId + " pkg="
8749 + packageSetting);
8750 } else {
8751 reportSettingsProblem(Log.WARN,
8752 "Error in package manager settings: package "
8753 + name + " has bad sharedId " + sharedIdStr
8754 + " at " + parser.getPositionDescription());
8755 }
8756 } else {
8757 reportSettingsProblem(Log.WARN,
8758 "Error in package manager settings: package "
8759 + name + " has bad userId " + idStr + " at "
8760 + parser.getPositionDescription());
8761 }
8762 } catch (NumberFormatException e) {
8763 reportSettingsProblem(Log.WARN,
8764 "Error in package manager settings: package "
8765 + name + " has bad userId " + idStr + " at "
8766 + parser.getPositionDescription());
8767 }
8768 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008769 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008770 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008771 final String enabledStr = parser.getAttributeValue(null, "enabled");
8772 if (enabledStr != null) {
8773 if (enabledStr.equalsIgnoreCase("true")) {
8774 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8775 } else if (enabledStr.equalsIgnoreCase("false")) {
8776 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
8777 } else if (enabledStr.equalsIgnoreCase("default")) {
8778 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8779 } else {
8780 reportSettingsProblem(Log.WARN,
8781 "Error in package manager settings: package "
8782 + name + " has bad enabled value: " + idStr
8783 + " at " + parser.getPositionDescription());
8784 }
8785 } else {
8786 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8787 }
8788 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
8789 if (installStatusStr != null) {
8790 if (installStatusStr.equalsIgnoreCase("false")) {
8791 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
8792 } else {
8793 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
8794 }
8795 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008797 int outerDepth = parser.getDepth();
8798 int type;
8799 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8800 && (type != XmlPullParser.END_TAG
8801 || parser.getDepth() > outerDepth)) {
8802 if (type == XmlPullParser.END_TAG
8803 || type == XmlPullParser.TEXT) {
8804 continue;
8805 }
8806
8807 String tagName = parser.getName();
8808 if (tagName.equals("disabled-components")) {
8809 readDisabledComponentsLP(packageSetting, parser);
8810 } else if (tagName.equals("enabled-components")) {
8811 readEnabledComponentsLP(packageSetting, parser);
8812 } else if (tagName.equals("sigs")) {
8813 packageSetting.signatures.readXml(parser, mPastSignatures);
8814 } else if (tagName.equals("perms")) {
8815 readGrantedPermissionsLP(parser,
8816 packageSetting.loadedPermissions);
8817 packageSetting.permissionsFixed = true;
8818 } else {
8819 reportSettingsProblem(Log.WARN,
8820 "Unknown element under <package>: "
8821 + parser.getName());
8822 XmlUtils.skipCurrentTag(parser);
8823 }
8824 }
8825 } else {
8826 XmlUtils.skipCurrentTag(parser);
8827 }
8828 }
8829
8830 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
8831 XmlPullParser parser)
8832 throws IOException, XmlPullParserException {
8833 int outerDepth = parser.getDepth();
8834 int type;
8835 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8836 && (type != XmlPullParser.END_TAG
8837 || parser.getDepth() > outerDepth)) {
8838 if (type == XmlPullParser.END_TAG
8839 || type == XmlPullParser.TEXT) {
8840 continue;
8841 }
8842
8843 String tagName = parser.getName();
8844 if (tagName.equals("item")) {
8845 String name = parser.getAttributeValue(null, "name");
8846 if (name != null) {
8847 packageSetting.disabledComponents.add(name.intern());
8848 } else {
8849 reportSettingsProblem(Log.WARN,
8850 "Error in package manager settings: <disabled-components> has"
8851 + " no name at " + parser.getPositionDescription());
8852 }
8853 } else {
8854 reportSettingsProblem(Log.WARN,
8855 "Unknown element under <disabled-components>: "
8856 + parser.getName());
8857 }
8858 XmlUtils.skipCurrentTag(parser);
8859 }
8860 }
8861
8862 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
8863 XmlPullParser parser)
8864 throws IOException, XmlPullParserException {
8865 int outerDepth = parser.getDepth();
8866 int type;
8867 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8868 && (type != XmlPullParser.END_TAG
8869 || parser.getDepth() > outerDepth)) {
8870 if (type == XmlPullParser.END_TAG
8871 || type == XmlPullParser.TEXT) {
8872 continue;
8873 }
8874
8875 String tagName = parser.getName();
8876 if (tagName.equals("item")) {
8877 String name = parser.getAttributeValue(null, "name");
8878 if (name != null) {
8879 packageSetting.enabledComponents.add(name.intern());
8880 } else {
8881 reportSettingsProblem(Log.WARN,
8882 "Error in package manager settings: <enabled-components> has"
8883 + " no name at " + parser.getPositionDescription());
8884 }
8885 } else {
8886 reportSettingsProblem(Log.WARN,
8887 "Unknown element under <enabled-components>: "
8888 + parser.getName());
8889 }
8890 XmlUtils.skipCurrentTag(parser);
8891 }
8892 }
8893
8894 private void readSharedUserLP(XmlPullParser parser)
8895 throws XmlPullParserException, IOException {
8896 String name = null;
8897 String idStr = null;
8898 int pkgFlags = 0;
8899 SharedUserSetting su = null;
8900 try {
8901 name = parser.getAttributeValue(null, "name");
8902 idStr = parser.getAttributeValue(null, "userId");
8903 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8904 if ("true".equals(parser.getAttributeValue(null, "system"))) {
8905 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8906 }
8907 if (name == null) {
8908 reportSettingsProblem(Log.WARN,
8909 "Error in package manager settings: <shared-user> has no name at "
8910 + parser.getPositionDescription());
8911 } else if (userId == 0) {
8912 reportSettingsProblem(Log.WARN,
8913 "Error in package manager settings: shared-user "
8914 + name + " has bad userId " + idStr + " at "
8915 + parser.getPositionDescription());
8916 } else {
8917 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
8918 reportSettingsProblem(Log.ERROR,
8919 "Occurred while parsing settings at "
8920 + parser.getPositionDescription());
8921 }
8922 }
8923 } catch (NumberFormatException e) {
8924 reportSettingsProblem(Log.WARN,
8925 "Error in package manager settings: package "
8926 + name + " has bad userId " + idStr + " at "
8927 + parser.getPositionDescription());
8928 };
8929
8930 if (su != null) {
8931 int outerDepth = parser.getDepth();
8932 int type;
8933 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8934 && (type != XmlPullParser.END_TAG
8935 || parser.getDepth() > outerDepth)) {
8936 if (type == XmlPullParser.END_TAG
8937 || type == XmlPullParser.TEXT) {
8938 continue;
8939 }
8940
8941 String tagName = parser.getName();
8942 if (tagName.equals("sigs")) {
8943 su.signatures.readXml(parser, mPastSignatures);
8944 } else if (tagName.equals("perms")) {
8945 readGrantedPermissionsLP(parser, su.loadedPermissions);
8946 } else {
8947 reportSettingsProblem(Log.WARN,
8948 "Unknown element under <shared-user>: "
8949 + parser.getName());
8950 XmlUtils.skipCurrentTag(parser);
8951 }
8952 }
8953
8954 } else {
8955 XmlUtils.skipCurrentTag(parser);
8956 }
8957 }
8958
8959 private void readGrantedPermissionsLP(XmlPullParser parser,
8960 HashSet<String> outPerms) throws IOException, XmlPullParserException {
8961 int outerDepth = parser.getDepth();
8962 int type;
8963 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8964 && (type != XmlPullParser.END_TAG
8965 || parser.getDepth() > outerDepth)) {
8966 if (type == XmlPullParser.END_TAG
8967 || type == XmlPullParser.TEXT) {
8968 continue;
8969 }
8970
8971 String tagName = parser.getName();
8972 if (tagName.equals("item")) {
8973 String name = parser.getAttributeValue(null, "name");
8974 if (name != null) {
8975 outPerms.add(name.intern());
8976 } else {
8977 reportSettingsProblem(Log.WARN,
8978 "Error in package manager settings: <perms> has"
8979 + " no name at " + parser.getPositionDescription());
8980 }
8981 } else {
8982 reportSettingsProblem(Log.WARN,
8983 "Unknown element under <perms>: "
8984 + parser.getName());
8985 }
8986 XmlUtils.skipCurrentTag(parser);
8987 }
8988 }
8989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008990 private void readPreferredActivitiesLP(XmlPullParser parser)
8991 throws XmlPullParserException, IOException {
8992 int outerDepth = parser.getDepth();
8993 int type;
8994 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8995 && (type != XmlPullParser.END_TAG
8996 || parser.getDepth() > outerDepth)) {
8997 if (type == XmlPullParser.END_TAG
8998 || type == XmlPullParser.TEXT) {
8999 continue;
9000 }
9001
9002 String tagName = parser.getName();
9003 if (tagName.equals("item")) {
9004 PreferredActivity pa = new PreferredActivity(parser);
9005 if (pa.mParseError == null) {
9006 mPreferredActivities.addFilter(pa);
9007 } else {
9008 reportSettingsProblem(Log.WARN,
9009 "Error in package manager settings: <preferred-activity> "
9010 + pa.mParseError + " at "
9011 + parser.getPositionDescription());
9012 }
9013 } else {
9014 reportSettingsProblem(Log.WARN,
9015 "Unknown element under <preferred-activities>: "
9016 + parser.getName());
9017 XmlUtils.skipCurrentTag(parser);
9018 }
9019 }
9020 }
9021
9022 // Returns -1 if we could not find an available UserId to assign
9023 private int newUserIdLP(Object obj) {
9024 // Let's be stupidly inefficient for now...
9025 final int N = mUserIds.size();
9026 for (int i=0; i<N; i++) {
9027 if (mUserIds.get(i) == null) {
9028 mUserIds.set(i, obj);
9029 return FIRST_APPLICATION_UID + i;
9030 }
9031 }
9032
9033 // None left?
9034 if (N >= MAX_APPLICATION_UIDS) {
9035 return -1;
9036 }
9037
9038 mUserIds.add(obj);
9039 return FIRST_APPLICATION_UID + N;
9040 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009042 public PackageSetting getDisabledSystemPkg(String name) {
9043 synchronized(mPackages) {
9044 PackageSetting ps = mDisabledSysPackages.get(name);
9045 return ps;
9046 }
9047 }
9048
9049 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9050 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9051 if (Config.LOGV) {
9052 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9053 + " componentName = " + componentInfo.name);
9054 Log.v(TAG, "enabledComponents: "
9055 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9056 Log.v(TAG, "disabledComponents: "
9057 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9058 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009059 if (packageSettings == null) {
9060 if (false) {
9061 Log.w(TAG, "WAITING FOR DEBUGGER");
9062 Debug.waitForDebugger();
9063 Log.i(TAG, "We will crash!");
9064 }
9065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009066 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9067 || ((componentInfo.enabled
9068 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9069 || (componentInfo.applicationInfo.enabled
9070 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9071 && !packageSettings.disabledComponents.contains(componentInfo.name))
9072 || packageSettings.enabledComponents.contains(componentInfo.name));
9073 }
9074 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009075
9076 // ------- apps on sdcard specific code -------
9077 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009078 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009079 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009080 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009081 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009082
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009083 private String getEncryptKey() {
9084 try {
9085 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9086 if (sdEncKey == null) {
9087 sdEncKey = SystemKeyStore.getInstance().
9088 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9089 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009090 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009091 return null;
9092 }
9093 }
9094 return sdEncKey;
9095 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009096 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009097 return null;
9098 }
9099 }
9100
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009101 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009102 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009103 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009104 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009105 if (list != null) {
9106 int idx = 0;
9107 int idList[] = new int[MAX_CONTAINERS];
9108 boolean neverFound = true;
9109 for (String name : list) {
9110 // Ignore null entries
9111 if (name == null) {
9112 continue;
9113 }
9114 int sidx = name.indexOf(prefix);
9115 if (sidx == -1) {
9116 // Not a temp file. just ignore
9117 continue;
9118 }
9119 String subStr = name.substring(sidx + prefix.length());
9120 idList[idx] = -1;
9121 if (subStr != null) {
9122 try {
9123 int cid = Integer.parseInt(subStr);
9124 idList[idx++] = cid;
9125 neverFound = false;
9126 } catch (NumberFormatException e) {
9127 }
9128 }
9129 }
9130 if (!neverFound) {
9131 // Sort idList
9132 Arrays.sort(idList);
9133 for (int j = 1; j <= idList.length; j++) {
9134 if (idList[j-1] != j) {
9135 tmpIdx = j;
9136 break;
9137 }
9138 }
9139 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009140 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009141 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009142 }
9143
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009144 /*
9145 * Return true if PackageManager does have packages to be updated.
9146 */
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009147 public boolean updateExternalMediaStatus(final boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009148 final boolean ret;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009149 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009150 Log.i(TAG, "Updating external media status from " +
9151 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9152 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009153 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9154 mediaStatus+", mMediaMounted=" + mMediaMounted);
9155 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009156 return false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009157 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009158 mMediaMounted = mediaStatus;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009159 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_EXTERNAL_STORAGE);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009160 ret = appList != null && appList.size() > 0;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009161 if (DEBUG_SD_INSTALL) {
9162 if (appList != null) {
9163 for (String app : appList) {
9164 Log.i(TAG, "Should enable " + app + " on sdcard");
9165 }
9166 }
9167 }
9168 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus returning " + ret);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009169 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009170 // Queue up an async operation since the package installation may take a little while.
9171 mHandler.post(new Runnable() {
9172 public void run() {
9173 mHandler.removeCallbacks(this);
9174 updateExternalMediaStatusInner(mediaStatus, ret);
9175 }
9176 });
9177 return ret;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009178 }
9179
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009180 private void updateExternalMediaStatusInner(boolean mediaStatus,
9181 boolean sendUpdateBroadcast) {
9182 // If we are up here that means there are packages to be
9183 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009184 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009185 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009186 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009187 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009188 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009189
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009190 int uidList[] = new int[list.length];
9191 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009192 HashSet<String> removeCids = new HashSet<String>();
9193 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009194 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009195 for (String cid : list) {
9196 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009197 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9198 boolean failed = true;
9199 try {
9200 String pkgName = args.getPackageName();
9201 if (pkgName == null) {
9202 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009203 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009204 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9205 PackageSetting ps = mSettings.mPackages.get(pkgName);
9206 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009207 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009208 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9209 " corresponds to pkg : " + pkgName +
9210 " at code path: " + ps.codePathString);
9211 // We do have a valid package installed on sdcard
9212 processCids.put(args, ps.codePathString);
9213 failed = false;
9214 int uid = ps.userId;
9215 if (uid != -1) {
9216 uidList[num++] = uid;
9217 }
9218 }
9219 } finally {
9220 if (failed) {
9221 // Stale container on sdcard. Just delete
9222 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9223 removeCids.add(cid);
9224 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009225 }
9226 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009227 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009228 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009229 int uidArr[] = null;
9230 if (num > 0) {
9231 // Sort uid list
9232 Arrays.sort(uidList, 0, num);
9233 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009234 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009235 uidArr[0] = uidList[0];
9236 int di = 0;
9237 for (int i = 1; i < num; i++) {
9238 if (uidList[i-1] != uidList[i]) {
9239 uidArr[di++] = uidList[i];
9240 }
9241 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009242 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009243 // Process packages with valid entries.
9244 if (mediaStatus) {
9245 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
9246 loadMediaPackages(processCids, uidArr, sendUpdateBroadcast, removeCids);
9247 startCleaningPackages();
9248 } else {
9249 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
9250 unloadMediaPackages(processCids, uidArr, sendUpdateBroadcast);
9251 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009252 }
9253
9254 private void sendResourcesChangedBroadcast(boolean mediaStatus,
9255 ArrayList<String> pkgList, int uidArr[]) {
9256 int size = pkgList.size();
9257 if (size > 0) {
9258 // Send broadcasts here
9259 Bundle extras = new Bundle();
9260 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9261 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009262 if (uidArr != null) {
9263 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9264 }
9265 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9266 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009267 sendPackageBroadcast(action, null, extras);
9268 }
9269 }
9270
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009271 /*
9272 * Look at potentially valid container ids from processCids
9273 * If package information doesn't match the one on record
9274 * or package scanning fails, the cid is added to list of
9275 * removeCids and cleaned up. Since cleaning up containers
9276 * involves destroying them, we do not want any parse
9277 * references to such stale containers. So force gc's
9278 * to avoid unnecessary crashes.
9279 */
9280 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
9281 int uidArr[], boolean sendUpdateBroadcast,
9282 HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009283 ArrayList<String> pkgList = new ArrayList<String>();
9284 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009285 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009286 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009287 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009288 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9289 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009290 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009291 try {
9292 // Make sure there are no container errors first.
9293 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9294 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009295 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009296 " when installing from sdcard");
9297 continue;
9298 }
9299 // Check code path here.
9300 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009301 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009302 " does not match one in settings " + codePath);
9303 continue;
9304 }
9305 // Parse package
9306 int parseFlags = PackageParser.PARSE_CHATTY |
9307 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
9308 PackageParser pp = new PackageParser(codePath);
9309 pp.setSeparateProcesses(mSeparateProcesses);
9310 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
9311 codePath, mMetrics, parseFlags);
9312 pp = null;
9313 doGc = true;
9314 // Check for parse errors
9315 if (pkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009316 Slog.e(TAG, "Parse error when installing install pkg : "
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009317 + args.cid + " from " + args.cachePath);
9318 continue;
9319 }
9320 setApplicationInfoPaths(pkg, codePath, codePath);
9321 synchronized (mInstallLock) {
9322 // Scan the package
9323 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
9324 synchronized (mPackages) {
9325 // Grant permissions
9326 grantPermissionsLP(pkg, false);
9327 // Persist settings
9328 mSettings.writeLP();
9329 retCode = PackageManager.INSTALL_SUCCEEDED;
9330 pkgList.add(pkg.packageName);
9331 // Post process args
9332 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9333 }
9334 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009335 Slog.i(TAG, "Failed to install pkg: " +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009336 pkg.packageName + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009337 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009338 }
9339
9340 } finally {
9341 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9342 // Don't destroy container here. Wait till gc clears things up.
9343 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009344 }
9345 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009346 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009347 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009348 if (sendUpdateBroadcast) {
9349 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9350 }
9351 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009352 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009353 }
9354 // Delete any stale containers if needed.
9355 if (removeCids != null) {
9356 for (String cid : removeCids) {
9357 Log.i(TAG, "Destroying stale container : " + cid);
9358 PackageHelper.destroySdDir(cid);
9359 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009360 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009361 }
9362
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009363 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
9364 int uidArr[], boolean sendUpdateBroadcast) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009365 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009366 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009367 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009368 Set<SdInstallArgs> keys = processCids.keySet();
9369 for (SdInstallArgs args : keys) {
9370 String cid = args.cid;
9371 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009372 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009373 // Delete package internally
9374 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9375 synchronized (mInstallLock) {
9376 boolean res = deletePackageLI(pkgName, false,
9377 PackageManager.DONT_DELETE_DATA, outInfo);
9378 if (res) {
9379 pkgList.add(pkgName);
9380 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009381 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009382 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009383 }
9384 }
9385 }
9386 // Send broadcasts
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009387 if (sendUpdateBroadcast) {
9388 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009389 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009390 // Force gc
9391 Runtime.getRuntime().gc();
9392 // Just unmount all valid containers.
9393 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009394 synchronized (mInstallLock) {
9395 args.doPostDeleteLI(false);
9396 }
9397 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009398 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009399
9400 public void movePackage(final String packageName,
9401 final IPackageMoveObserver observer, final int flags) {
9402 if (packageName == null) {
9403 return;
9404 }
9405 mContext.enforceCallingOrSelfPermission(
9406 android.Manifest.permission.MOVE_PACKAGE, null);
9407 int returnCode = PackageManager.MOVE_SUCCEEDED;
9408 int currFlags = 0;
9409 int newFlags = 0;
9410 synchronized (mPackages) {
9411 PackageParser.Package pkg = mPackages.get(packageName);
9412 if (pkg == null) {
9413 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9414 }
9415 // Disable moving fwd locked apps and system packages
9416 if (pkg.applicationInfo != null &&
9417 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009418 Slog.w(TAG, "Cannot move system application");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009419 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9420 } else if (pkg.applicationInfo != null &&
9421 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009422 Slog.w(TAG, "Cannot move forward locked app.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009423 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9424 } else {
9425 // Find install location first
9426 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9427 (flags & PackageManager.MOVE_INTERNAL) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009428 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009429 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9430 } else {
9431 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9432 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009433 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009434 PackageManager.INSTALL_EXTERNAL : 0;
9435 if (newFlags == currFlags) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009436 Slog.w(TAG, "No move required. Trying to move to same location");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009437 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9438 }
9439 }
9440 }
9441 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9442 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9443 } else {
9444 Message msg = mHandler.obtainMessage(INIT_COPY);
9445 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9446 pkg.applicationInfo.publicSourceDir);
9447 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9448 packageName);
9449 msg.obj = mp;
9450 mHandler.sendMessage(msg);
9451 }
9452 }
9453 }
9454
9455 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9456 // Queue up an async operation since the package deletion may take a little while.
9457 mHandler.post(new Runnable() {
9458 public void run() {
9459 mHandler.removeCallbacks(this);
9460 int returnCode = currentStatus;
9461 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9462 if (moveSucceeded) {
9463 int uid = -1;
9464 synchronized (mPackages) {
9465 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9466 }
9467 ArrayList<String> pkgList = new ArrayList<String>();
9468 pkgList.add(mp.packageName);
9469 int uidArr[] = new int[] { uid };
9470 // Send resources unavailable broadcast
9471 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9472
9473 // Update package code and resource paths
9474 synchronized (mPackages) {
9475 PackageParser.Package pkg = mPackages.get(mp.packageName);
9476 if (pkg != null) {
9477 String oldCodePath = pkg.mPath;
9478 String newCodePath = mp.targetArgs.getCodePath();
9479 String newResPath = mp.targetArgs.getResourcePath();
9480 pkg.mPath = newCodePath;
9481 // Move dex files around
9482 if (moveDexFiles(pkg)
9483 != PackageManager.INSTALL_SUCCEEDED) {
9484 // Moving of dex files failed. Set
9485 // error code and abort move.
9486 pkg.mPath = pkg.mScanPath;
9487 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9488 moveSucceeded = false;
9489 } else {
9490 pkg.mScanPath = newCodePath;
9491 pkg.applicationInfo.sourceDir = newCodePath;
9492 pkg.applicationInfo.publicSourceDir = newResPath;
9493 PackageSetting ps = (PackageSetting) pkg.mExtras;
9494 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9495 ps.codePathString = ps.codePath.getPath();
9496 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9497 ps.resourcePathString = ps.resourcePath.getPath();
9498 // Set the application info flag correctly.
9499 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009500 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009501 } else {
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009502 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009503 }
9504 ps.setFlags(pkg.applicationInfo.flags);
9505 mAppDirs.remove(oldCodePath);
9506 mAppDirs.put(newCodePath, pkg);
9507 // Persist settings
9508 mSettings.writeLP();
9509 }
9510 }
9511 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009512 // Send resources available broadcast
9513 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009514 }
9515 if (!moveSucceeded){
9516 // Clean up failed installation
9517 if (mp.targetArgs != null) {
9518 mp.targetArgs.doPostInstall(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009519 returnCode);
9520 }
9521 } else {
9522 // Force a gc to clear things up.
9523 Runtime.getRuntime().gc();
9524 // Delete older code
9525 synchronized (mInstallLock) {
9526 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009527 }
9528 }
9529 IPackageMoveObserver observer = mp.observer;
9530 if (observer != null) {
9531 try {
9532 observer.packageMoved(mp.packageName, returnCode);
9533 } catch (RemoteException e) {
9534 Log.i(TAG, "Observer no longer exists.");
9535 }
9536 }
9537 }
9538 });
9539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009540}