blob: 39c754071654fd6e93d35b447b6469010daf3a26 [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;
Kenny Root85387d72010-08-26 10:13:11 -070021import com.android.internal.content.NativeLibraryHelper;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080022import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080023import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070024import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080025import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026
27import org.xmlpull.v1.XmlPullParser;
28import org.xmlpull.v1.XmlPullParserException;
29import org.xmlpull.v1.XmlSerializer;
30
31import android.app.ActivityManagerNative;
32import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080033import 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.Context;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070036import android.content.ComponentName;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070037import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.Intent;
39import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070040import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080041import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070042import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.pm.ActivityInfo;
44import android.content.pm.ApplicationInfo;
45import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070046import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.content.pm.IPackageDataObserver;
48import android.content.pm.IPackageDeleteObserver;
49import android.content.pm.IPackageInstallObserver;
50import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080051import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.content.pm.IPackageStatsObserver;
53import android.content.pm.InstrumentationInfo;
54import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080055import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.pm.PackageManager;
57import android.content.pm.PackageStats;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
59import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
60import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.pm.PackageParser;
62import android.content.pm.PermissionInfo;
63import android.content.pm.PermissionGroupInfo;
64import android.content.pm.ProviderInfo;
65import android.content.pm.ResolveInfo;
66import android.content.pm.ServiceInfo;
67import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.Uri;
69import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070070import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080072import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080074import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070075import android.os.Looper;
76import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Parcel;
78import android.os.RemoteException;
79import android.os.Environment;
80import android.os.FileObserver;
81import android.os.FileUtils;
82import android.os.Handler;
83import android.os.ParcelFileDescriptor;
84import android.os.Process;
85import android.os.ServiceManager;
86import android.os.SystemClock;
87import android.os.SystemProperties;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070088import android.provider.Settings;
Oscar Montemayord02546b2010-01-14 16:38:40 -080089import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.util.*;
91import android.view.Display;
92import android.view.WindowManager;
93
Kenny Root9f306d72010-09-26 11:19:47 -070094import java.io.BufferedOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import 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;
Kenny Root6c4d9042010-11-19 12:48:05 -0800105import java.lang.reflect.Array;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800106import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800107import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import java.util.ArrayList;
109import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700110import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import java.util.Collections;
112import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800113import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import java.util.Enumeration;
115import java.util.HashMap;
116import java.util.HashSet;
117import java.util.Iterator;
Kenny Root85387d72010-08-26 10:13:11 -0700118import java.util.LinkedList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119import java.util.List;
120import java.util.Map;
121import java.util.Set;
122import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800123import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import java.util.zip.ZipFile;
125import java.util.zip.ZipOutputStream;
126
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700127/**
128 * Keep track of all those .apks everywhere.
129 *
130 * This is very central to the platform's security; please run the unit
131 * tests whenever making modifications here:
132 *
133mmm frameworks/base/tests/AndroidTests
134adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
135adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
136 *
137 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138class PackageManagerService extends IPackageManager.Stub {
139 private static final String TAG = "PackageManager";
140 private static final boolean DEBUG_SETTINGS = false;
141 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800142 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800143 private static final boolean DEBUG_INSTALL = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144
145 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
146 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400147 private static final int LOG_UID = Process.LOG_UID;
Nick Pellybc21fde2010-10-13 17:25:24 -0700148 private static final int NFC_UID = Process.NFC_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149 private static final int FIRST_APPLICATION_UID =
150 Process.FIRST_APPLICATION_UID;
151 private static final int MAX_APPLICATION_UIDS = 1000;
152
153 private static final boolean SHOW_INFO = false;
154
155 private static final boolean GET_CERTIFICATES = true;
156
Oscar Montemayora8529f62009-11-18 10:14:20 -0800157 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 private static final int REMOVE_EVENTS =
160 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
161 private static final int ADD_EVENTS =
162 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
163
164 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800165 // Suffix used during package installation when copying/moving
166 // package apks to install directory.
167 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800169 /**
170 * Indicates the state of installation. Used by PackageManager to
171 * figure out incomplete installations. Say a package is being installed
172 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
173 * the package installation is successful or unsuccesful lin which case
174 * the PackageManager will no longer maintain state information associated
175 * with the package. If some exception(like device freeze or battery being
176 * pulled out) occurs during installation of a package, the PackageManager
177 * needs this information to clean up the previously failed installation.
178 */
179 private static final int PKG_INSTALL_INCOMPLETE = 0;
180 private static final int PKG_INSTALL_COMPLETE = 1;
181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 static final int SCAN_MONITOR = 1<<0;
183 static final int SCAN_NO_DEX = 1<<1;
184 static final int SCAN_FORCE_DEX = 1<<2;
185 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800186 static final int SCAN_NEW_INSTALL = 1<<4;
187 static final int SCAN_NO_PATHS = 1<<5;
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700188 static final int SCAN_UPDATE_TIME = 1<<6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700190 static final int REMOVE_CHATTY = 1<<16;
Kenny Root11128572010-10-11 10:51:32 -0700191
192 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
193
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800194 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
Kenny Root11128572010-10-11 10:51:32 -0700195 DEFAULT_CONTAINER_PACKAGE,
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800196 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700197
Kenny Root85387d72010-08-26 10:13:11 -0700198 private static final String LIB_DIR_NAME = "lib";
199
Kenny Rootc78a8072010-07-27 15:18:38 -0700200 static final String mTempContainerPrefix = "smdl2tmp";
201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
203 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700204 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205
Dianne Hackborn851a5412009-05-08 12:06:44 -0700206 final int mSdkVersion = Build.VERSION.SDK_INT;
207 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
208 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 final Context mContext;
211 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700212 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 final DisplayMetrics mMetrics;
214 final int mDefParseFlags;
215 final String[] mSeparateProcesses;
216
217 // This is where all application persistent data goes.
218 final File mAppDataDir;
219
Oscar Montemayora8529f62009-11-18 10:14:20 -0800220 // If Encrypted File System feature is enabled, all application persistent data
221 // should go here instead.
222 final File mSecureAppDataDir;
223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 // This is the object monitoring the framework dir.
225 final FileObserver mFrameworkInstallObserver;
226
227 // This is the object monitoring the system app dir.
228 final FileObserver mSystemInstallObserver;
229
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700230 // This is the object monitoring the system app dir.
231 final FileObserver mVendorInstallObserver;
232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 // This is the object monitoring mAppInstallDir.
234 final FileObserver mAppInstallObserver;
235
236 // This is the object monitoring mDrmAppPrivateInstallDir.
237 final FileObserver mDrmAppInstallObserver;
238
239 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
240 // LOCK HELD. Can be called with mInstallLock held.
241 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 final File mFrameworkDir;
244 final File mSystemAppDir;
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700245 final File mVendorAppDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700247 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248
249 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
250 // apps.
251 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 // Lock for state used when installing and doing other long running
256 // operations. Methods that must be called with this lock held have
257 // the prefix "LI".
258 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 // These are the directories in the 3rd party applications installed dir
261 // that we have currently loaded packages from. Keys are the application's
262 // installed zip file (absolute codePath), and values are Package.
263 final HashMap<String, PackageParser.Package> mAppDirs =
264 new HashMap<String, PackageParser.Package>();
265
266 // Information for the parser to write more useful error messages.
267 File mScanningPath;
268 int mLastScanError;
269
270 final int[] mOutPermissions = new int[3];
271
272 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274 // Keys are String (package name), values are Package. This also serves
275 // as the lock for the global state. Methods that must be called with
276 // this lock held have the prefix "LP".
277 final HashMap<String, PackageParser.Package> mPackages =
278 new HashMap<String, PackageParser.Package>();
279
280 final Settings mSettings;
281 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282
283 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
284 int[] mGlobalGids;
285
286 // These are the built-in uid -> permission mappings that were read from the
287 // etc/permissions.xml file.
288 final SparseArray<HashSet<String>> mSystemPermissions =
289 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291 // These are the built-in shared libraries that were read from the
292 // etc/permissions.xml file.
293 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800294
Dianne Hackborn49237342009-08-27 20:08:01 -0700295 // Temporary for building the final shared libraries for an .apk.
296 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800297
Dianne Hackborn49237342009-08-27 20:08:01 -0700298 // These are the features this devices supports that were read from the
299 // etc/permissions.xml file.
300 final HashMap<String, FeatureInfo> mAvailableFeatures =
301 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 // All available activities, for your resolving pleasure.
304 final ActivityIntentResolver mActivities =
305 new ActivityIntentResolver();
306
307 // All available receivers, for your resolving pleasure.
308 final ActivityIntentResolver mReceivers =
309 new ActivityIntentResolver();
310
311 // All available services, for your resolving pleasure.
312 final ServiceIntentResolver mServices = new ServiceIntentResolver();
313
314 // Keys are String (provider class name), values are Provider.
315 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
316 new HashMap<ComponentName, PackageParser.Provider>();
317
318 // Mapping from provider base names (first directory in content URI codePath)
319 // to the provider information.
320 final HashMap<String, PackageParser.Provider> mProviders =
321 new HashMap<String, PackageParser.Provider>();
322
323 // Mapping from instrumentation class names to info about them.
324 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
325 new HashMap<ComponentName, PackageParser.Instrumentation>();
326
327 // Mapping from permission names to info about them.
328 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
329 new HashMap<String, PackageParser.PermissionGroup>();
330
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800331 // Packages whose data we have transfered into another package, thus
332 // should no longer exist.
333 final HashSet<String> mTransferedPackages = new HashSet<String>();
334
Dianne Hackborn854060af2009-07-09 18:14:31 -0700335 // Broadcast actions that are only available to the system.
336 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 boolean mSystemReady;
339 boolean mSafeMode;
340 boolean mHasSystemUidErrors;
341
342 ApplicationInfo mAndroidApplication;
343 final ActivityInfo mResolveActivity = new ActivityInfo();
344 final ResolveInfo mResolveInfo = new ResolveInfo();
345 ComponentName mResolveComponentName;
346 PackageParser.Package mPlatformPackage;
347
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700348 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800349 final HashMap<String, ArrayList<String>> mPendingBroadcasts
350 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800351 // Service Connection to remote media container service to copy
352 // package uri's from external media onto secure containers
353 // or internal storage.
354 private IMediaContainerService mContainerService = null;
355
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700356 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800357 static final int MCS_BOUND = 3;
358 static final int END_COPY = 4;
359 static final int INIT_COPY = 5;
360 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800361 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800362 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800363 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800364 static final int MCS_RECONNECT = 10;
365 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700366 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700367 static final int WRITE_SETTINGS = 13;
368
369 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800370
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700371 // Delay time in millisecs
372 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800373 final private DefaultContainerConnection mDefContainerConn =
374 new DefaultContainerConnection();
375 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800376 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800377 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800378 IMediaContainerService imcs =
379 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800380 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800381 }
382
383 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800384 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800385 }
386 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700387
Christopher Tate1bb69062010-02-19 17:02:12 -0800388 // Recordkeeping of restore-after-install operations that are currently in flight
389 // between the Package Manager and the Backup Manager
390 class PostInstallData {
391 public InstallArgs args;
392 public PackageInstalledInfo res;
393
394 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
395 args = _a;
396 res = _r;
397 }
398 };
399 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
400 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
401
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700402 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800403 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800404 final ArrayList<HandlerParams> mPendingInstalls =
405 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800406
407 private boolean connectToService() {
408 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
409 " DefaultContainerService");
410 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700411 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800412 if (mContext.bindService(service, mDefContainerConn,
413 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700414 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800415 mBound = true;
416 return true;
417 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700418 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800419 return false;
420 }
421
422 private void disconnectService() {
423 mContainerService = null;
424 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700425 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800426 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700427 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800428 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800429
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700430 PackageHandler(Looper looper) {
431 super(looper);
432 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700433
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700434 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700435 try {
436 doHandleMessage(msg);
437 } finally {
438 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
439 }
440 }
441
442 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700443 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800444 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800445 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800446 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800447 int idx = mPendingInstalls.size();
448 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
449 // If a bind was already initiated we dont really
450 // need to do anything. The pending install
451 // will be processed later on.
452 if (!mBound) {
453 // If this is the only one pending we might
454 // have to bind to the service again.
455 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800456 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800457 params.serviceError();
458 return;
459 } else {
460 // Once we bind to the service, the first
461 // pending request will be processed.
462 mPendingInstalls.add(idx, params);
463 }
464 } else {
465 mPendingInstalls.add(idx, params);
466 // Already bound to the service. Just make
467 // sure we trigger off processing the first request.
468 if (idx == 0) {
469 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800470 }
471 }
472 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800473 }
474 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800475 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800476 if (msg.obj != null) {
477 mContainerService = (IMediaContainerService) msg.obj;
478 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800479 if (mContainerService == null) {
480 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800481 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800482 for (HandlerParams params : mPendingInstalls) {
483 mPendingInstalls.remove(0);
484 // Indicate service bind error
485 params.serviceError();
486 }
487 mPendingInstalls.clear();
488 } else if (mPendingInstalls.size() > 0) {
489 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800490 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800491 params.startCopy();
492 }
493 } else {
494 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800495 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800496 }
497 break;
498 }
499 case MCS_RECONNECT : {
500 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
501 if (mPendingInstalls.size() > 0) {
502 if (mBound) {
503 disconnectService();
504 }
505 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800506 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800507 for (HandlerParams params : mPendingInstalls) {
508 mPendingInstalls.remove(0);
509 // Indicate service bind error
510 params.serviceError();
511 }
512 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800513 }
514 }
515 break;
516 }
517 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800518 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
519 // Delete pending install
520 if (mPendingInstalls.size() > 0) {
521 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800522 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800523 if (mPendingInstalls.size() == 0) {
524 if (mBound) {
525 disconnectService();
526 }
527 } else {
528 // There are more pending requests in queue.
529 // Just post MCS_BOUND message to trigger processing
530 // of next pending install.
531 mHandler.sendEmptyMessage(MCS_BOUND);
532 }
533 break;
534 }
535 case MCS_GIVE_UP: {
536 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
537 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800538 break;
539 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700540 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800541 String packages[];
542 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700543 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700544 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700545 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700546 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800547 if (mPendingBroadcasts == null) {
548 return;
549 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700550 size = mPendingBroadcasts.size();
551 if (size <= 0) {
552 // Nothing to be done. Just return
553 return;
554 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800555 packages = new String[size];
556 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700557 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800558 Iterator<HashMap.Entry<String, ArrayList<String>>>
559 it = mPendingBroadcasts.entrySet().iterator();
560 int i = 0;
561 while (it.hasNext() && i < size) {
562 HashMap.Entry<String, ArrayList<String>> ent = it.next();
563 packages[i] = ent.getKey();
564 components[i] = ent.getValue();
565 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700566 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800567 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700568 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800569 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700570 mPendingBroadcasts.clear();
571 }
572 // Send broadcasts
573 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800574 sendPackageChangedBroadcast(packages[i], true,
575 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700576 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700577 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700578 break;
579 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800580 case START_CLEANING_PACKAGE: {
581 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700582 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800583 synchronized (mPackages) {
584 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
585 mSettings.mPackagesToBeCleaned.add(packageName);
586 }
587 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700588 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800589 startCleaningPackages();
590 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800591 case POST_INSTALL: {
592 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
593 PostInstallData data = mRunningInstalls.get(msg.arg1);
594 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700595 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800596
597 if (data != null) {
598 InstallArgs args = data.args;
599 PackageInstalledInfo res = data.res;
600
601 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700602 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800603 Bundle extras = new Bundle(1);
604 extras.putInt(Intent.EXTRA_UID, res.uid);
605 final boolean update = res.removedInfo.removedPackage != null;
606 if (update) {
607 extras.putBoolean(Intent.EXTRA_REPLACING, true);
608 }
609 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
610 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700611 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800612 if (update) {
613 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
614 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700615 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800616 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700617 if (res.removedInfo.args != null) {
618 // Remove the replaced package's older resources safely now
619 deleteOld = true;
620 }
621 }
622 // Force a gc to clear up things
623 Runtime.getRuntime().gc();
624 // We delete after a gc for applications on sdcard.
625 if (deleteOld) {
626 synchronized (mInstallLock) {
627 res.removedInfo.args.doPostDeleteLI(true);
628 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800629 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800630 if (args.observer != null) {
631 try {
632 args.observer.packageInstalled(res.name, res.returnCode);
633 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800634 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800635 }
636 }
637 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800638 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800639 }
640 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700641 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700642 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
643 boolean reportStatus = msg.arg1 == 1;
644 boolean doGc = msg.arg2 == 1;
645 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
646 if (doGc) {
647 // Force a gc to clear up stale containers.
648 Runtime.getRuntime().gc();
649 }
650 if (msg.obj != null) {
651 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
652 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
653 // Unload containers
654 unloadAllContainers(args);
655 }
656 if (reportStatus) {
657 try {
658 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
659 PackageHelper.getMountService().finishMediaUpdate();
660 } catch (RemoteException e) {
661 Log.e(TAG, "MountService not running?");
662 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700663 }
664 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700665 case WRITE_SETTINGS: {
666 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
667 synchronized (mPackages) {
668 removeMessages(WRITE_SETTINGS);
669 mSettings.writeLP();
670 }
671 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
672 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700673 }
674 }
675 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800676
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700677 void scheduleWriteSettingsLocked() {
678 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
679 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
680 }
681 }
682
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800683 static boolean installOnSd(int flags) {
684 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700685 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800686 return false;
687 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700688 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
689 return true;
690 }
691 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800692 }
693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 public static final IPackageManager main(Context context, boolean factoryTest) {
695 PackageManagerService m = new PackageManagerService(context, factoryTest);
696 ServiceManager.addService("package", m);
697 return m;
698 }
699
700 static String[] splitString(String str, char sep) {
701 int count = 1;
702 int i = 0;
703 while ((i=str.indexOf(sep, i)) >= 0) {
704 count++;
705 i++;
706 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 String[] res = new String[count];
709 i=0;
710 count = 0;
711 int lastI=0;
712 while ((i=str.indexOf(sep, i)) >= 0) {
713 res[count] = str.substring(lastI, i);
714 count++;
715 i++;
716 lastI = i;
717 }
718 res[count] = str.substring(lastI, str.length());
719 return res;
720 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800723 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800727 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 mContext = context;
731 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700732 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 mMetrics = new DisplayMetrics();
734 mSettings = new Settings();
735 mSettings.addSharedUserLP("android.uid.system",
736 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
737 mSettings.addSharedUserLP("android.uid.phone",
738 MULTIPLE_APPLICATION_UIDS
739 ? RADIO_UID : FIRST_APPLICATION_UID,
740 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400741 mSettings.addSharedUserLP("android.uid.log",
742 MULTIPLE_APPLICATION_UIDS
743 ? LOG_UID : FIRST_APPLICATION_UID,
744 ApplicationInfo.FLAG_SYSTEM);
Nick Pellybc21fde2010-10-13 17:25:24 -0700745 mSettings.addSharedUserLP("android.uid.nfc",
746 MULTIPLE_APPLICATION_UIDS
747 ? NFC_UID : FIRST_APPLICATION_UID,
748 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749
750 String separateProcesses = SystemProperties.get("debug.separate_processes");
751 if (separateProcesses != null && separateProcesses.length() > 0) {
752 if ("*".equals(separateProcesses)) {
753 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
754 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800755 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 } else {
757 mDefParseFlags = 0;
758 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800759 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 + separateProcesses);
761 }
762 } else {
763 mDefParseFlags = 0;
764 mSeparateProcesses = null;
765 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 Installer installer = new Installer();
768 // Little hacky thing to check if installd is here, to determine
769 // whether we are running on the simulator and thus need to take
770 // care of building the /data file structure ourself.
771 // (apparently the sim now has a working installer)
772 if (installer.ping() && Process.supportsProcesses()) {
773 mInstaller = installer;
774 } else {
775 mInstaller = null;
776 }
777
778 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
779 Display d = wm.getDefaultDisplay();
780 d.getMetrics(mMetrics);
781
782 synchronized (mInstallLock) {
783 synchronized (mPackages) {
784 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700785 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 File dataDir = Environment.getDataDirectory();
788 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800789 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
791
792 if (mInstaller == null) {
793 // Make sure these dirs exist, when we are running in
794 // the simulator.
795 // Make a wide-open directory for random misc stuff.
796 File miscDir = new File(dataDir, "misc");
797 miscDir.mkdirs();
798 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800799 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 mDrmAppPrivateInstallDir.mkdirs();
801 }
802
803 readPermissions();
804
805 mRestoredSettings = mSettings.readLP();
806 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800807
808 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800810
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800811 // Set flag to monitor and not change apk file paths when
812 // scanning install directories.
813 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700814 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800815 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800816 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700817 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700822 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700825 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 /**
828 * Out of paranoia, ensure that everything in the boot class
829 * path has been dexed.
830 */
831 String bootClassPath = System.getProperty("java.boot.class.path");
832 if (bootClassPath != null) {
833 String[] paths = splitString(bootClassPath, ':');
834 for (int i=0; i<paths.length; i++) {
835 try {
836 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
837 libFiles.add(paths[i]);
838 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700839 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 }
841 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800842 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800844 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 }
846 }
847 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800848 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 /**
852 * Also ensure all external libraries have had dexopt run on them.
853 */
854 if (mSharedLibraries.size() > 0) {
855 Iterator<String> libs = mSharedLibraries.values().iterator();
856 while (libs.hasNext()) {
857 String lib = libs.next();
858 try {
859 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
860 libFiles.add(lib);
861 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700862 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 }
864 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800865 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800867 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 }
869 }
870 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 // Gross hack for now: we know this file doesn't contain any
873 // code, so don't dexopt it to avoid the resulting log spew.
874 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800875
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 /**
877 * And there are a number of commands implemented in Java, which
878 * we currently need to do the dexopt on so that they can be
879 * run from a non-root shell.
880 */
881 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700882 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 for (int i=0; i<frameworkFiles.length; i++) {
884 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
885 String path = libPath.getPath();
886 // Skip the file if we alrady did it.
887 if (libFiles.contains(path)) {
888 continue;
889 }
890 // Skip the file if it is not a type we want to dexopt.
891 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
892 continue;
893 }
894 try {
895 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
896 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700897 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 }
899 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800900 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800902 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 }
904 }
905 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800906
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700907 if (didDexOpt) {
908 // If we had to do a dexopt of one of the previous
909 // things, then something on the system has changed.
910 // Consider this significant, and wipe away all other
911 // existing dexopt files to ensure we don't leave any
912 // dangling around.
913 String[] files = mDalvikCacheDir.list();
914 if (files != null) {
915 for (int i=0; i<files.length; i++) {
916 String fn = files[i];
917 if (fn.startsWith("data@app@")
918 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800919 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700920 (new File(mDalvikCacheDir, fn)).delete();
921 }
922 }
923 }
924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800926
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800927 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 mFrameworkInstallObserver = new AppDirObserver(
929 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
930 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700931 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
932 | PackageParser.PARSE_IS_SYSTEM_DIR,
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700933 scanMode | SCAN_NO_DEX, 0);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800934
935 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
937 mSystemInstallObserver = new AppDirObserver(
938 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
939 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700940 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700941 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800942
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700943 // Collect all vendor packages.
944 mVendorAppDir = new File("/vendor/app");
945 mVendorInstallObserver = new AppDirObserver(
946 mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
947 mVendorInstallObserver.startWatching();
948 scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700949 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700950
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800951 if (mInstaller != null) {
952 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
953 mInstaller.moveFiles();
954 }
955
956 // Prune any system packages that no longer exist.
957 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
958 while (psit.hasNext()) {
959 PackageSetting ps = psit.next();
960 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800961 && !mPackages.containsKey(ps.name)
962 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800963 psit.remove();
964 String msg = "System package " + ps.name
965 + " no longer exists; wiping its data";
966 reportSettingsProblem(Log.WARN, msg);
967 if (mInstaller != null) {
968 // XXX how to set useEncryptedFSDir for packages that
969 // are not encrypted?
970 mInstaller.remove(ps.name, true);
971 }
972 }
973 }
974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 mAppInstallDir = new File(dataDir, "app");
976 if (mInstaller == null) {
977 // Make sure these dirs exist, when we are running in
978 // the simulator.
979 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
980 }
981 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800982 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 //clean up list
984 for(int i = 0; i < deletePkgsList.size(); i++) {
985 //clean up here
986 cleanupInstallFailedPackage(deletePkgsList.get(i));
987 }
988 //delete tmp files
989 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800990
991 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 SystemClock.uptimeMillis());
993 mAppInstallObserver = new AppDirObserver(
994 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
995 mAppInstallObserver.startWatching();
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700996 scanDirLI(mAppInstallDir, 0, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997
998 mDrmAppInstallObserver = new AppDirObserver(
999 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
1000 mDrmAppInstallObserver.startWatching();
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001001 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1002 scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001004 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001006 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 + ((SystemClock.uptimeMillis()-startTime)/1000f)
1008 + " seconds");
1009
Dianne Hackbornf22221f2010-04-05 18:35:42 -07001010 // If the platform SDK has changed since the last time we booted,
1011 // we need to re-grant app permission to catch any new ones that
1012 // appear. This is really a hack, and means that apps can in some
1013 // cases get permissions that the user didn't initially explicitly
1014 // allow... it would be nice to have some better way to handle
1015 // this situation.
1016 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1017 != mSdkVersion;
1018 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1019 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1020 + "; regranting permissions for internal storage");
1021 mSettings.mInternalSdkPlatform = mSdkVersion;
1022
Dianne Hackborn92cfa102010-04-28 11:00:44 -07001023 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024
1025 mSettings.writeLP();
1026
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001027 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 // Now after opening every single application zip, make sure they
1031 // are all flushed. Not really needed, but keeps things nice and
1032 // tidy.
1033 Runtime.getRuntime().gc();
1034 } // synchronized (mPackages)
1035 } // synchronized (mInstallLock)
1036 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 @Override
1039 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1040 throws RemoteException {
1041 try {
1042 return super.onTransact(code, data, reply, flags);
1043 } catch (RuntimeException e) {
1044 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001045 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 }
1047 throw e;
1048 }
1049 }
1050
Dianne Hackborne6620b22010-01-22 14:46:21 -08001051 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001052 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001054 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1055 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001057 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001058 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 }
1060 } else {
1061 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001062 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 File dataDir = new File(pkg.applicationInfo.dataDir);
1064 dataDir.delete();
1065 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001066 if (ps.codePath != null) {
1067 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001068 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001069 }
1070 }
1071 if (ps.resourcePath != null) {
1072 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001073 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001074 }
1075 }
1076 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 }
1078
1079 void readPermissions() {
1080 // Read permissions from .../etc/permission directory.
1081 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1082 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001083 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 return;
1085 }
1086 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001087 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 return;
1089 }
1090
1091 // Iterate over the files in the directory and scan .xml files
1092 for (File f : libraryDir.listFiles()) {
1093 // We'll read platform.xml last
1094 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1095 continue;
1096 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001099 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 continue;
1101 }
1102 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001103 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 continue;
1105 }
1106
1107 readPermissionsFromXml(f);
1108 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1111 final File permFile = new File(Environment.getRootDirectory(),
1112 "etc/permissions/platform.xml");
1113 readPermissionsFromXml(permFile);
1114 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001115
1116 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 FileReader permReader = null;
1118 try {
1119 permReader = new FileReader(permFile);
1120 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001121 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 return;
1123 }
1124
1125 try {
1126 XmlPullParser parser = Xml.newPullParser();
1127 parser.setInput(permReader);
1128
1129 XmlUtils.beginDocument(parser, "permissions");
1130
1131 while (true) {
1132 XmlUtils.nextElement(parser);
1133 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1134 break;
1135 }
1136
1137 String name = parser.getName();
1138 if ("group".equals(name)) {
1139 String gidStr = parser.getAttributeValue(null, "gid");
1140 if (gidStr != null) {
1141 int gid = Integer.parseInt(gidStr);
1142 mGlobalGids = appendInt(mGlobalGids, gid);
1143 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001144 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 + parser.getPositionDescription());
1146 }
1147
1148 XmlUtils.skipCurrentTag(parser);
1149 continue;
1150 } else if ("permission".equals(name)) {
1151 String perm = parser.getAttributeValue(null, "name");
1152 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001153 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 + parser.getPositionDescription());
1155 XmlUtils.skipCurrentTag(parser);
1156 continue;
1157 }
1158 perm = perm.intern();
1159 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 } else if ("assign-permission".equals(name)) {
1162 String perm = parser.getAttributeValue(null, "name");
1163 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001164 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 + parser.getPositionDescription());
1166 XmlUtils.skipCurrentTag(parser);
1167 continue;
1168 }
1169 String uidStr = parser.getAttributeValue(null, "uid");
1170 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001171 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 + parser.getPositionDescription());
1173 XmlUtils.skipCurrentTag(parser);
1174 continue;
1175 }
1176 int uid = Process.getUidForName(uidStr);
1177 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001178 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 + uidStr + "\" at "
1180 + parser.getPositionDescription());
1181 XmlUtils.skipCurrentTag(parser);
1182 continue;
1183 }
1184 perm = perm.intern();
1185 HashSet<String> perms = mSystemPermissions.get(uid);
1186 if (perms == null) {
1187 perms = new HashSet<String>();
1188 mSystemPermissions.put(uid, perms);
1189 }
1190 perms.add(perm);
1191 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 } else if ("library".equals(name)) {
1194 String lname = parser.getAttributeValue(null, "name");
1195 String lfile = parser.getAttributeValue(null, "file");
1196 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001197 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 + parser.getPositionDescription());
1199 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001200 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 + parser.getPositionDescription());
1202 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001203 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001204 mSharedLibraries.put(lname, lfile);
1205 }
1206 XmlUtils.skipCurrentTag(parser);
1207 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001208
Dianne Hackborn49237342009-08-27 20:08:01 -07001209 } else if ("feature".equals(name)) {
1210 String fname = parser.getAttributeValue(null, "name");
1211 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001212 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001213 + parser.getPositionDescription());
1214 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001215 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001216 FeatureInfo fi = new FeatureInfo();
1217 fi.name = fname;
1218 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 }
1220 XmlUtils.skipCurrentTag(parser);
1221 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 } else {
1224 XmlUtils.skipCurrentTag(parser);
1225 continue;
1226 }
1227
1228 }
1229 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001230 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001232 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 }
1234 }
1235
1236 void readPermission(XmlPullParser parser, String name)
1237 throws IOException, XmlPullParserException {
1238
1239 name = name.intern();
1240
1241 BasePermission bp = mSettings.mPermissions.get(name);
1242 if (bp == null) {
1243 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1244 mSettings.mPermissions.put(name, bp);
1245 }
1246 int outerDepth = parser.getDepth();
1247 int type;
1248 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1249 && (type != XmlPullParser.END_TAG
1250 || parser.getDepth() > outerDepth)) {
1251 if (type == XmlPullParser.END_TAG
1252 || type == XmlPullParser.TEXT) {
1253 continue;
1254 }
1255
1256 String tagName = parser.getName();
1257 if ("group".equals(tagName)) {
1258 String gidStr = parser.getAttributeValue(null, "gid");
1259 if (gidStr != null) {
1260 int gid = Process.getGidForName(gidStr);
1261 bp.gids = appendInt(bp.gids, gid);
1262 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001263 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 + parser.getPositionDescription());
1265 }
1266 }
1267 XmlUtils.skipCurrentTag(parser);
1268 }
1269 }
1270
1271 static int[] appendInt(int[] cur, int val) {
1272 if (cur == null) {
1273 return new int[] { val };
1274 }
1275 final int N = cur.length;
1276 for (int i=0; i<N; i++) {
1277 if (cur[i] == val) {
1278 return cur;
1279 }
1280 }
1281 int[] ret = new int[N+1];
1282 System.arraycopy(cur, 0, ret, 0, N);
1283 ret[N] = val;
1284 return ret;
1285 }
1286
1287 static int[] appendInts(int[] cur, int[] add) {
1288 if (add == null) return cur;
1289 if (cur == null) return add;
1290 final int N = add.length;
1291 for (int i=0; i<N; i++) {
1292 cur = appendInt(cur, add[i]);
1293 }
1294 return cur;
1295 }
1296
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001297 static int[] removeInt(int[] cur, int val) {
1298 if (cur == null) {
1299 return null;
1300 }
1301 final int N = cur.length;
1302 for (int i=0; i<N; i++) {
1303 if (cur[i] == val) {
1304 int[] ret = new int[N-1];
1305 if (i > 0) {
1306 System.arraycopy(cur, 0, ret, 0, i);
1307 }
1308 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001309 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001310 }
1311 return ret;
1312 }
1313 }
1314 return cur;
1315 }
1316
1317 static int[] removeInts(int[] cur, int[] rem) {
1318 if (rem == null) return cur;
1319 if (cur == null) return cur;
1320 final int N = rem.length;
1321 for (int i=0; i<N; i++) {
1322 cur = removeInt(cur, rem[i]);
1323 }
1324 return cur;
1325 }
1326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001328 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1329 // The package has been uninstalled but has retained data and resources.
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001330 return PackageParser.generatePackageInfo(p, null, flags, 0, 0);
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 final PackageSetting ps = (PackageSetting)p.mExtras;
1333 if (ps == null) {
1334 return null;
1335 }
1336 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001337 return PackageParser.generatePackageInfo(p, gp.gids, flags,
1338 ps.firstInstallTime, ps.lastUpdateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 }
1340
1341 public PackageInfo getPackageInfo(String packageName, int flags) {
1342 synchronized (mPackages) {
1343 PackageParser.Package p = mPackages.get(packageName);
1344 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001345 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 + ": " + p);
1347 if (p != null) {
1348 return generatePackageInfo(p, flags);
1349 }
1350 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1351 return generatePackageInfoFromSettingsLP(packageName, flags);
1352 }
1353 }
1354 return null;
1355 }
1356
Dianne Hackborn47096932010-02-11 15:57:09 -08001357 public String[] currentToCanonicalPackageNames(String[] names) {
1358 String[] out = new String[names.length];
1359 synchronized (mPackages) {
1360 for (int i=names.length-1; i>=0; i--) {
1361 PackageSetting ps = mSettings.mPackages.get(names[i]);
1362 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1363 }
1364 }
1365 return out;
1366 }
1367
1368 public String[] canonicalToCurrentPackageNames(String[] names) {
1369 String[] out = new String[names.length];
1370 synchronized (mPackages) {
1371 for (int i=names.length-1; i>=0; i--) {
1372 String cur = mSettings.mRenamedPackages.get(names[i]);
1373 out[i] = cur != null ? cur : names[i];
1374 }
1375 }
1376 return out;
1377 }
1378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 public int getPackageUid(String packageName) {
1380 synchronized (mPackages) {
1381 PackageParser.Package p = mPackages.get(packageName);
1382 if(p != null) {
1383 return p.applicationInfo.uid;
1384 }
1385 PackageSetting ps = mSettings.mPackages.get(packageName);
1386 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1387 return -1;
1388 }
1389 p = ps.pkg;
1390 return p != null ? p.applicationInfo.uid : -1;
1391 }
1392 }
1393
1394 public int[] getPackageGids(String packageName) {
1395 synchronized (mPackages) {
1396 PackageParser.Package p = mPackages.get(packageName);
1397 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001398 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 + ": " + p);
1400 if (p != null) {
1401 final PackageSetting ps = (PackageSetting)p.mExtras;
1402 final SharedUserSetting suid = ps.sharedUser;
1403 return suid != null ? suid.gids : ps.gids;
1404 }
1405 }
1406 // stupid thing to indicate an error.
1407 return new int[0];
1408 }
1409
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001410 static final PermissionInfo generatePermissionInfo(
1411 BasePermission bp, int flags) {
1412 if (bp.perm != null) {
1413 return PackageParser.generatePermissionInfo(bp.perm, flags);
1414 }
1415 PermissionInfo pi = new PermissionInfo();
1416 pi.name = bp.name;
1417 pi.packageName = bp.sourcePackage;
1418 pi.nonLocalizedLabel = bp.name;
1419 pi.protectionLevel = bp.protectionLevel;
1420 return pi;
1421 }
1422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 public PermissionInfo getPermissionInfo(String name, int flags) {
1424 synchronized (mPackages) {
1425 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001426 if (p != null) {
1427 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 }
1429 return null;
1430 }
1431 }
1432
1433 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1434 synchronized (mPackages) {
1435 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1436 for (BasePermission p : mSettings.mPermissions.values()) {
1437 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001438 if (p.perm == null || p.perm.info.group == null) {
1439 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 }
1441 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001442 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1444 }
1445 }
1446 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 if (out.size() > 0) {
1449 return out;
1450 }
1451 return mPermissionGroups.containsKey(group) ? out : null;
1452 }
1453 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1456 synchronized (mPackages) {
1457 return PackageParser.generatePermissionGroupInfo(
1458 mPermissionGroups.get(name), flags);
1459 }
1460 }
1461
1462 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1463 synchronized (mPackages) {
1464 final int N = mPermissionGroups.size();
1465 ArrayList<PermissionGroupInfo> out
1466 = new ArrayList<PermissionGroupInfo>(N);
1467 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1468 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1469 }
1470 return out;
1471 }
1472 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1475 PackageSetting ps = mSettings.mPackages.get(packageName);
1476 if(ps != null) {
1477 if(ps.pkg == null) {
1478 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1479 if(pInfo != null) {
1480 return pInfo.applicationInfo;
1481 }
1482 return null;
1483 }
1484 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1485 }
1486 return null;
1487 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1490 PackageSetting ps = mSettings.mPackages.get(packageName);
1491 if(ps != null) {
1492 if(ps.pkg == null) {
1493 ps.pkg = new PackageParser.Package(packageName);
1494 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001495 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1496 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1497 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1498 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001499 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001500 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 }
1502 return generatePackageInfo(ps.pkg, flags);
1503 }
1504 return null;
1505 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1508 synchronized (mPackages) {
1509 PackageParser.Package p = mPackages.get(packageName);
1510 if (Config.LOGV) Log.v(
1511 TAG, "getApplicationInfo " + packageName
1512 + ": " + p);
1513 if (p != null) {
1514 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001515 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 }
1517 if ("android".equals(packageName)||"system".equals(packageName)) {
1518 return mAndroidApplication;
1519 }
1520 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1521 return generateApplicationInfoFromSettingsLP(packageName, flags);
1522 }
1523 }
1524 return null;
1525 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001526
1527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1529 mContext.enforceCallingOrSelfPermission(
1530 android.Manifest.permission.CLEAR_APP_CACHE, null);
1531 // Queue up an async operation since clearing cache may take a little while.
1532 mHandler.post(new Runnable() {
1533 public void run() {
1534 mHandler.removeCallbacks(this);
1535 int retCode = -1;
1536 if (mInstaller != null) {
1537 retCode = mInstaller.freeCache(freeStorageSize);
1538 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001539 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 }
1541 } //end if mInstaller
1542 if (observer != null) {
1543 try {
1544 observer.onRemoveCompleted(null, (retCode >= 0));
1545 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001546 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 }
1548 }
1549 }
1550 });
1551 }
1552
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001553 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001554 mContext.enforceCallingOrSelfPermission(
1555 android.Manifest.permission.CLEAR_APP_CACHE, null);
1556 // Queue up an async operation since clearing cache may take a little while.
1557 mHandler.post(new Runnable() {
1558 public void run() {
1559 mHandler.removeCallbacks(this);
1560 int retCode = -1;
1561 if (mInstaller != null) {
1562 retCode = mInstaller.freeCache(freeStorageSize);
1563 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001564 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001565 }
1566 }
1567 if(pi != null) {
1568 try {
1569 // Callback via pending intent
1570 int code = (retCode >= 0) ? 1 : 0;
1571 pi.sendIntent(null, code, null,
1572 null, null);
1573 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001574 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001575 }
1576 }
1577 }
1578 });
1579 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1582 synchronized (mPackages) {
1583 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001584
1585 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001587 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 }
1589 if (mResolveComponentName.equals(component)) {
1590 return mResolveActivity;
1591 }
1592 }
1593 return null;
1594 }
1595
1596 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1597 synchronized (mPackages) {
1598 PackageParser.Activity a = mReceivers.mActivities.get(component);
1599 if (Config.LOGV) Log.v(
1600 TAG, "getReceiverInfo " + component + ": " + a);
1601 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1602 return PackageParser.generateActivityInfo(a, flags);
1603 }
1604 }
1605 return null;
1606 }
1607
1608 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1609 synchronized (mPackages) {
1610 PackageParser.Service s = mServices.mServices.get(component);
1611 if (Config.LOGV) Log.v(
1612 TAG, "getServiceInfo " + component + ": " + s);
1613 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1614 return PackageParser.generateServiceInfo(s, flags);
1615 }
1616 }
1617 return null;
1618 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001619
Dianne Hackborn361199b2010-08-30 17:42:07 -07001620 public ProviderInfo getProviderInfo(ComponentName component, int flags) {
1621 synchronized (mPackages) {
1622 PackageParser.Provider p = mProvidersByComponent.get(component);
1623 if (Config.LOGV) Log.v(
1624 TAG, "getProviderInfo " + component + ": " + p);
1625 if (p != null && mSettings.isEnabledLP(p.info, flags)) {
1626 return PackageParser.generateProviderInfo(p, flags);
1627 }
1628 }
1629 return null;
1630 }
1631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 public String[] getSystemSharedLibraryNames() {
1633 Set<String> libSet;
1634 synchronized (mPackages) {
1635 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001636 int size = libSet.size();
1637 if (size > 0) {
1638 String[] libs = new String[size];
1639 libSet.toArray(libs);
1640 return libs;
1641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001643 return null;
1644 }
1645
1646 public FeatureInfo[] getSystemAvailableFeatures() {
1647 Collection<FeatureInfo> featSet;
1648 synchronized (mPackages) {
1649 featSet = mAvailableFeatures.values();
1650 int size = featSet.size();
1651 if (size > 0) {
1652 FeatureInfo[] features = new FeatureInfo[size+1];
1653 featSet.toArray(features);
1654 FeatureInfo fi = new FeatureInfo();
1655 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1656 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1657 features[size] = fi;
1658 return features;
1659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 }
1661 return null;
1662 }
1663
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001664 public boolean hasSystemFeature(String name) {
1665 synchronized (mPackages) {
1666 return mAvailableFeatures.containsKey(name);
1667 }
1668 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 public int checkPermission(String permName, String pkgName) {
1671 synchronized (mPackages) {
1672 PackageParser.Package p = mPackages.get(pkgName);
1673 if (p != null && p.mExtras != null) {
1674 PackageSetting ps = (PackageSetting)p.mExtras;
1675 if (ps.sharedUser != null) {
1676 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1677 return PackageManager.PERMISSION_GRANTED;
1678 }
1679 } else if (ps.grantedPermissions.contains(permName)) {
1680 return PackageManager.PERMISSION_GRANTED;
1681 }
1682 }
1683 }
1684 return PackageManager.PERMISSION_DENIED;
1685 }
1686
1687 public int checkUidPermission(String permName, int uid) {
1688 synchronized (mPackages) {
1689 Object obj = mSettings.getUserIdLP(uid);
1690 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001691 GrantedPermissions gp = (GrantedPermissions)obj;
1692 if (gp.grantedPermissions.contains(permName)) {
1693 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 }
1695 } else {
1696 HashSet<String> perms = mSystemPermissions.get(uid);
1697 if (perms != null && perms.contains(permName)) {
1698 return PackageManager.PERMISSION_GRANTED;
1699 }
1700 }
1701 }
1702 return PackageManager.PERMISSION_DENIED;
1703 }
1704
1705 private BasePermission findPermissionTreeLP(String permName) {
1706 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1707 if (permName.startsWith(bp.name) &&
1708 permName.length() > bp.name.length() &&
1709 permName.charAt(bp.name.length()) == '.') {
1710 return bp;
1711 }
1712 }
1713 return null;
1714 }
1715
1716 private BasePermission checkPermissionTreeLP(String permName) {
1717 if (permName != null) {
1718 BasePermission bp = findPermissionTreeLP(permName);
1719 if (bp != null) {
1720 if (bp.uid == Binder.getCallingUid()) {
1721 return bp;
1722 }
1723 throw new SecurityException("Calling uid "
1724 + Binder.getCallingUid()
1725 + " is not allowed to add to permission tree "
1726 + bp.name + " owned by uid " + bp.uid);
1727 }
1728 }
1729 throw new SecurityException("No permission tree found for " + permName);
1730 }
1731
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001732 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1733 if (s1 == null) {
1734 return s2 == null;
1735 }
1736 if (s2 == null) {
1737 return false;
1738 }
1739 if (s1.getClass() != s2.getClass()) {
1740 return false;
1741 }
1742 return s1.equals(s2);
1743 }
1744
1745 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1746 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001747 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001748 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1749 if (!compareStrings(pi1.name, pi2.name)) return false;
1750 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1751 // We'll take care of setting this one.
1752 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1753 // These are not currently stored in settings.
1754 //if (!compareStrings(pi1.group, pi2.group)) return false;
1755 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1756 //if (pi1.labelRes != pi2.labelRes) return false;
1757 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1758 return true;
1759 }
1760
1761 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1762 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1763 throw new SecurityException("Label must be specified in permission");
1764 }
1765 BasePermission tree = checkPermissionTreeLP(info.name);
1766 BasePermission bp = mSettings.mPermissions.get(info.name);
1767 boolean added = bp == null;
1768 boolean changed = true;
1769 if (added) {
1770 bp = new BasePermission(info.name, tree.sourcePackage,
1771 BasePermission.TYPE_DYNAMIC);
1772 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1773 throw new SecurityException(
1774 "Not allowed to modify non-dynamic permission "
1775 + info.name);
1776 } else {
1777 if (bp.protectionLevel == info.protectionLevel
1778 && bp.perm.owner.equals(tree.perm.owner)
1779 && bp.uid == tree.uid
1780 && comparePermissionInfos(bp.perm.info, info)) {
1781 changed = false;
1782 }
1783 }
1784 bp.protectionLevel = info.protectionLevel;
1785 bp.perm = new PackageParser.Permission(tree.perm.owner,
1786 new PermissionInfo(info));
1787 bp.perm.info.packageName = tree.perm.info.packageName;
1788 bp.uid = tree.uid;
1789 if (added) {
1790 mSettings.mPermissions.put(info.name, bp);
1791 }
1792 if (changed) {
1793 if (!async) {
1794 mSettings.writeLP();
1795 } else {
1796 scheduleWriteSettingsLocked();
1797 }
1798 }
1799 return added;
1800 }
1801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 public boolean addPermission(PermissionInfo info) {
1803 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001804 return addPermissionLocked(info, false);
1805 }
1806 }
1807
1808 public boolean addPermissionAsync(PermissionInfo info) {
1809 synchronized (mPackages) {
1810 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 }
1812 }
1813
1814 public void removePermission(String name) {
1815 synchronized (mPackages) {
1816 checkPermissionTreeLP(name);
1817 BasePermission bp = mSettings.mPermissions.get(name);
1818 if (bp != null) {
1819 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1820 throw new SecurityException(
1821 "Not allowed to modify non-dynamic permission "
1822 + name);
1823 }
1824 mSettings.mPermissions.remove(name);
1825 mSettings.writeLP();
1826 }
1827 }
1828 }
1829
Dianne Hackborn854060af2009-07-09 18:14:31 -07001830 public boolean isProtectedBroadcast(String actionName) {
1831 synchronized (mPackages) {
1832 return mProtectedBroadcasts.contains(actionName);
1833 }
1834 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 public int checkSignatures(String pkg1, String pkg2) {
1837 synchronized (mPackages) {
1838 PackageParser.Package p1 = mPackages.get(pkg1);
1839 PackageParser.Package p2 = mPackages.get(pkg2);
1840 if (p1 == null || p1.mExtras == null
1841 || p2 == null || p2.mExtras == null) {
1842 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1843 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001844 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 }
1846 }
1847
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001848 public int checkUidSignatures(int uid1, int uid2) {
1849 synchronized (mPackages) {
1850 Signature[] s1;
1851 Signature[] s2;
1852 Object obj = mSettings.getUserIdLP(uid1);
1853 if (obj != null) {
1854 if (obj instanceof SharedUserSetting) {
1855 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1856 } else if (obj instanceof PackageSetting) {
1857 s1 = ((PackageSetting)obj).signatures.mSignatures;
1858 } else {
1859 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1860 }
1861 } else {
1862 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1863 }
1864 obj = mSettings.getUserIdLP(uid2);
1865 if (obj != null) {
1866 if (obj instanceof SharedUserSetting) {
1867 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1868 } else if (obj instanceof PackageSetting) {
1869 s2 = ((PackageSetting)obj).signatures.mSignatures;
1870 } else {
1871 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1872 }
1873 } else {
1874 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1875 }
1876 return checkSignaturesLP(s1, s2);
1877 }
1878 }
1879
1880 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1881 if (s1 == null) {
1882 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1884 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1885 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001886 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1888 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001889 HashSet<Signature> set1 = new HashSet<Signature>();
1890 for (Signature sig : s1) {
1891 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001893 HashSet<Signature> set2 = new HashSet<Signature>();
1894 for (Signature sig : s2) {
1895 set2.add(sig);
1896 }
1897 // Make sure s2 contains all signatures in s1.
1898 if (set1.equals(set2)) {
1899 return PackageManager.SIGNATURE_MATCH;
1900 }
1901 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 }
1903
1904 public String[] getPackagesForUid(int uid) {
1905 synchronized (mPackages) {
1906 Object obj = mSettings.getUserIdLP(uid);
1907 if (obj instanceof SharedUserSetting) {
1908 SharedUserSetting sus = (SharedUserSetting)obj;
1909 final int N = sus.packages.size();
1910 String[] res = new String[N];
1911 Iterator<PackageSetting> it = sus.packages.iterator();
1912 int i=0;
1913 while (it.hasNext()) {
1914 res[i++] = it.next().name;
1915 }
1916 return res;
1917 } else if (obj instanceof PackageSetting) {
1918 PackageSetting ps = (PackageSetting)obj;
1919 return new String[] { ps.name };
1920 }
1921 }
1922 return null;
1923 }
1924
1925 public String getNameForUid(int uid) {
1926 synchronized (mPackages) {
1927 Object obj = mSettings.getUserIdLP(uid);
1928 if (obj instanceof SharedUserSetting) {
1929 SharedUserSetting sus = (SharedUserSetting)obj;
1930 return sus.name + ":" + sus.userId;
1931 } else if (obj instanceof PackageSetting) {
1932 PackageSetting ps = (PackageSetting)obj;
1933 return ps.name;
1934 }
1935 }
1936 return null;
1937 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 public int getUidForSharedUser(String sharedUserName) {
1940 if(sharedUserName == null) {
1941 return -1;
1942 }
1943 synchronized (mPackages) {
1944 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1945 if(suid == null) {
1946 return -1;
1947 }
1948 return suid.userId;
1949 }
1950 }
1951
1952 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1953 int flags) {
1954 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001955 return chooseBestActivity(intent, resolvedType, flags, query);
1956 }
1957
Mihai Predaeae850c2009-05-13 10:13:48 +02001958 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1959 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 if (query != null) {
1961 final int N = query.size();
1962 if (N == 1) {
1963 return query.get(0);
1964 } else if (N > 1) {
1965 // If there is more than one activity with the same priority,
1966 // then let the user decide between them.
1967 ResolveInfo r0 = query.get(0);
1968 ResolveInfo r1 = query.get(1);
1969 if (false) {
1970 System.out.println(r0.activityInfo.name +
1971 "=" + r0.priority + " vs " +
1972 r1.activityInfo.name +
1973 "=" + r1.priority);
1974 }
1975 // If the first activity has a higher priority, or a different
1976 // default, then it is always desireable to pick it.
1977 if (r0.priority != r1.priority
1978 || r0.preferredOrder != r1.preferredOrder
1979 || r0.isDefault != r1.isDefault) {
1980 return query.get(0);
1981 }
1982 // If we have saved a preference for a preferred activity for
1983 // this Intent, use that.
1984 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1985 flags, query, r0.priority);
1986 if (ri != null) {
1987 return ri;
1988 }
1989 return mResolveInfo;
1990 }
1991 }
1992 return null;
1993 }
1994
1995 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1996 int flags, List<ResolveInfo> query, int priority) {
1997 synchronized (mPackages) {
1998 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1999 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02002000 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
2002 if (prefs != null && prefs.size() > 0) {
2003 // First figure out how good the original match set is.
2004 // We will only allow preferred activities that came
2005 // from the same match quality.
2006 int match = 0;
2007 final int N = query.size();
2008 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
2009 for (int j=0; j<N; j++) {
2010 ResolveInfo ri = query.get(j);
2011 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2012 + ": 0x" + Integer.toHexString(match));
2013 if (ri.match > match) match = ri.match;
2014 }
2015 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2016 + Integer.toHexString(match));
2017 match &= IntentFilter.MATCH_CATEGORY_MASK;
2018 final int M = prefs.size();
2019 for (int i=0; i<M; i++) {
2020 PreferredActivity pa = prefs.get(i);
2021 if (pa.mMatch != match) {
2022 continue;
2023 }
2024 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2025 if (DEBUG_PREFERRED) {
2026 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002027 if (ai != null) {
2028 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2029 } else {
2030 Log.v(TAG, " null");
2031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 }
2033 if (ai != null) {
2034 for (int j=0; j<N; j++) {
2035 ResolveInfo ri = query.get(j);
2036 if (!ri.activityInfo.applicationInfo.packageName
2037 .equals(ai.applicationInfo.packageName)) {
2038 continue;
2039 }
2040 if (!ri.activityInfo.name.equals(ai.name)) {
2041 continue;
2042 }
2043
2044 // Okay we found a previously set preferred app.
2045 // If the result set is different from when this
2046 // was created, we need to clear it and re-ask the
2047 // user their preference.
2048 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002049 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 + intent + " type " + resolvedType);
2051 mSettings.mPreferredActivities.removeFilter(pa);
2052 return null;
2053 }
2054
2055 // Yay!
2056 return ri;
2057 }
2058 }
2059 }
2060 }
2061 }
2062 return null;
2063 }
2064
2065 public List<ResolveInfo> queryIntentActivities(Intent intent,
2066 String resolvedType, int flags) {
2067 ComponentName comp = intent.getComponent();
2068 if (comp != null) {
2069 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2070 ActivityInfo ai = getActivityInfo(comp, flags);
2071 if (ai != null) {
2072 ResolveInfo ri = new ResolveInfo();
2073 ri.activityInfo = ai;
2074 list.add(ri);
2075 }
2076 return list;
2077 }
2078
2079 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002080 String pkgName = intent.getPackage();
2081 if (pkgName == null) {
2082 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2083 resolvedType, flags);
2084 }
2085 PackageParser.Package pkg = mPackages.get(pkgName);
2086 if (pkg != null) {
2087 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2088 resolvedType, flags, pkg.activities);
2089 }
2090 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 }
2092 }
2093
2094 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2095 Intent[] specifics, String[] specificTypes, Intent intent,
2096 String resolvedType, int flags) {
2097 final String resultsAction = intent.getAction();
2098
2099 List<ResolveInfo> results = queryIntentActivities(
2100 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2101 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2102
2103 int specificsPos = 0;
2104 int N;
2105
2106 // todo: note that the algorithm used here is O(N^2). This
2107 // isn't a problem in our current environment, but if we start running
2108 // into situations where we have more than 5 or 10 matches then this
2109 // should probably be changed to something smarter...
2110
2111 // First we go through and resolve each of the specific items
2112 // that were supplied, taking care of removing any corresponding
2113 // duplicate items in the generic resolve list.
2114 if (specifics != null) {
2115 for (int i=0; i<specifics.length; i++) {
2116 final Intent sintent = specifics[i];
2117 if (sintent == null) {
2118 continue;
2119 }
2120
2121 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2122 String action = sintent.getAction();
2123 if (resultsAction != null && resultsAction.equals(action)) {
2124 // If this action was explicitly requested, then don't
2125 // remove things that have it.
2126 action = null;
2127 }
2128 ComponentName comp = sintent.getComponent();
2129 ResolveInfo ri = null;
2130 ActivityInfo ai = null;
2131 if (comp == null) {
2132 ri = resolveIntent(
2133 sintent,
2134 specificTypes != null ? specificTypes[i] : null,
2135 flags);
2136 if (ri == null) {
2137 continue;
2138 }
2139 if (ri == mResolveInfo) {
2140 // ACK! Must do something better with this.
2141 }
2142 ai = ri.activityInfo;
2143 comp = new ComponentName(ai.applicationInfo.packageName,
2144 ai.name);
2145 } else {
2146 ai = getActivityInfo(comp, flags);
2147 if (ai == null) {
2148 continue;
2149 }
2150 }
2151
2152 // Look for any generic query activities that are duplicates
2153 // of this specific one, and remove them from the results.
2154 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2155 N = results.size();
2156 int j;
2157 for (j=specificsPos; j<N; j++) {
2158 ResolveInfo sri = results.get(j);
2159 if ((sri.activityInfo.name.equals(comp.getClassName())
2160 && sri.activityInfo.applicationInfo.packageName.equals(
2161 comp.getPackageName()))
2162 || (action != null && sri.filter.matchAction(action))) {
2163 results.remove(j);
2164 if (Config.LOGV) Log.v(
2165 TAG, "Removing duplicate item from " + j
2166 + " due to specific " + specificsPos);
2167 if (ri == null) {
2168 ri = sri;
2169 }
2170 j--;
2171 N--;
2172 }
2173 }
2174
2175 // Add this specific item to its proper place.
2176 if (ri == null) {
2177 ri = new ResolveInfo();
2178 ri.activityInfo = ai;
2179 }
2180 results.add(specificsPos, ri);
2181 ri.specificIndex = i;
2182 specificsPos++;
2183 }
2184 }
2185
2186 // Now we go through the remaining generic results and remove any
2187 // duplicate actions that are found here.
2188 N = results.size();
2189 for (int i=specificsPos; i<N-1; i++) {
2190 final ResolveInfo rii = results.get(i);
2191 if (rii.filter == null) {
2192 continue;
2193 }
2194
2195 // Iterate over all of the actions of this result's intent
2196 // filter... typically this should be just one.
2197 final Iterator<String> it = rii.filter.actionsIterator();
2198 if (it == null) {
2199 continue;
2200 }
2201 while (it.hasNext()) {
2202 final String action = it.next();
2203 if (resultsAction != null && resultsAction.equals(action)) {
2204 // If this action was explicitly requested, then don't
2205 // remove things that have it.
2206 continue;
2207 }
2208 for (int j=i+1; j<N; j++) {
2209 final ResolveInfo rij = results.get(j);
2210 if (rij.filter != null && rij.filter.hasAction(action)) {
2211 results.remove(j);
2212 if (Config.LOGV) Log.v(
2213 TAG, "Removing duplicate item from " + j
2214 + " due to action " + action + " at " + i);
2215 j--;
2216 N--;
2217 }
2218 }
2219 }
2220
2221 // If the caller didn't request filter information, drop it now
2222 // so we don't have to marshall/unmarshall it.
2223 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2224 rii.filter = null;
2225 }
2226 }
2227
2228 // Filter out the caller activity if so requested.
2229 if (caller != null) {
2230 N = results.size();
2231 for (int i=0; i<N; i++) {
2232 ActivityInfo ainfo = results.get(i).activityInfo;
2233 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2234 && caller.getClassName().equals(ainfo.name)) {
2235 results.remove(i);
2236 break;
2237 }
2238 }
2239 }
2240
2241 // If the caller didn't request filter information,
2242 // drop them now so we don't have to
2243 // marshall/unmarshall it.
2244 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2245 N = results.size();
2246 for (int i=0; i<N; i++) {
2247 results.get(i).filter = null;
2248 }
2249 }
2250
2251 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2252 return results;
2253 }
2254
2255 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2256 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002257 ComponentName comp = intent.getComponent();
2258 if (comp != null) {
2259 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2260 ActivityInfo ai = getReceiverInfo(comp, flags);
2261 if (ai != null) {
2262 ResolveInfo ri = new ResolveInfo();
2263 ri.activityInfo = ai;
2264 list.add(ri);
2265 }
2266 return list;
2267 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002270 String pkgName = intent.getPackage();
2271 if (pkgName == null) {
2272 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2273 resolvedType, flags);
2274 }
2275 PackageParser.Package pkg = mPackages.get(pkgName);
2276 if (pkg != null) {
2277 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2278 resolvedType, flags, pkg.receivers);
2279 }
2280 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002281 }
2282 }
2283
2284 public ResolveInfo resolveService(Intent intent, String resolvedType,
2285 int flags) {
2286 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2287 flags);
2288 if (query != null) {
2289 if (query.size() >= 1) {
2290 // If there is more than one service with the same priority,
2291 // just arbitrarily pick the first one.
2292 return query.get(0);
2293 }
2294 }
2295 return null;
2296 }
2297
2298 public List<ResolveInfo> queryIntentServices(Intent intent,
2299 String resolvedType, int flags) {
2300 ComponentName comp = intent.getComponent();
2301 if (comp != null) {
2302 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2303 ServiceInfo si = getServiceInfo(comp, flags);
2304 if (si != null) {
2305 ResolveInfo ri = new ResolveInfo();
2306 ri.serviceInfo = si;
2307 list.add(ri);
2308 }
2309 return list;
2310 }
2311
2312 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002313 String pkgName = intent.getPackage();
2314 if (pkgName == null) {
2315 return (List<ResolveInfo>)mServices.queryIntent(intent,
2316 resolvedType, flags);
2317 }
2318 PackageParser.Package pkg = mPackages.get(pkgName);
2319 if (pkg != null) {
2320 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2321 resolvedType, flags, pkg.services);
2322 }
2323 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 }
2325 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002327 public List<PackageInfo> getInstalledPackages(int flags) {
2328 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2329
2330 synchronized (mPackages) {
2331 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2332 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2333 while (i.hasNext()) {
2334 final PackageSetting ps = i.next();
2335 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2336 if(psPkg != null) {
2337 finalList.add(psPkg);
2338 }
2339 }
2340 }
2341 else {
2342 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2343 while (i.hasNext()) {
2344 final PackageParser.Package p = i.next();
2345 if (p.applicationInfo != null) {
2346 PackageInfo pi = generatePackageInfo(p, flags);
2347 if(pi != null) {
2348 finalList.add(pi);
2349 }
2350 }
2351 }
2352 }
2353 }
2354 return finalList;
2355 }
2356
2357 public List<ApplicationInfo> getInstalledApplications(int flags) {
2358 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2359 synchronized(mPackages) {
2360 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2361 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2362 while (i.hasNext()) {
2363 final PackageSetting ps = i.next();
2364 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2365 if(ai != null) {
2366 finalList.add(ai);
2367 }
2368 }
2369 }
2370 else {
2371 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2372 while (i.hasNext()) {
2373 final PackageParser.Package p = i.next();
2374 if (p.applicationInfo != null) {
2375 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2376 if(ai != null) {
2377 finalList.add(ai);
2378 }
2379 }
2380 }
2381 }
2382 }
2383 return finalList;
2384 }
2385
2386 public List<ApplicationInfo> getPersistentApplications(int flags) {
2387 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2388
2389 synchronized (mPackages) {
2390 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2391 while (i.hasNext()) {
2392 PackageParser.Package p = i.next();
2393 if (p.applicationInfo != null
2394 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002395 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002396 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 }
2398 }
2399 }
2400
2401 return finalList;
2402 }
2403
2404 public ProviderInfo resolveContentProvider(String name, int flags) {
2405 synchronized (mPackages) {
2406 final PackageParser.Provider provider = mProviders.get(name);
2407 return provider != null
2408 && mSettings.isEnabledLP(provider.info, flags)
2409 && (!mSafeMode || (provider.info.applicationInfo.flags
2410 &ApplicationInfo.FLAG_SYSTEM) != 0)
2411 ? PackageParser.generateProviderInfo(provider, flags)
2412 : null;
2413 }
2414 }
2415
Fred Quintana718d8a22009-04-29 17:53:20 -07002416 /**
2417 * @deprecated
2418 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002419 public void querySyncProviders(List outNames, List outInfo) {
2420 synchronized (mPackages) {
2421 Iterator<Map.Entry<String, PackageParser.Provider>> i
2422 = mProviders.entrySet().iterator();
2423
2424 while (i.hasNext()) {
2425 Map.Entry<String, PackageParser.Provider> entry = i.next();
2426 PackageParser.Provider p = entry.getValue();
2427
2428 if (p.syncable
2429 && (!mSafeMode || (p.info.applicationInfo.flags
2430 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2431 outNames.add(entry.getKey());
2432 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2433 }
2434 }
2435 }
2436 }
2437
2438 public List<ProviderInfo> queryContentProviders(String processName,
2439 int uid, int flags) {
2440 ArrayList<ProviderInfo> finalList = null;
2441
2442 synchronized (mPackages) {
2443 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2444 while (i.hasNext()) {
2445 PackageParser.Provider p = i.next();
2446 if (p.info.authority != null
2447 && (processName == null ||
2448 (p.info.processName.equals(processName)
2449 && p.info.applicationInfo.uid == uid))
2450 && mSettings.isEnabledLP(p.info, flags)
2451 && (!mSafeMode || (p.info.applicationInfo.flags
2452 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2453 if (finalList == null) {
2454 finalList = new ArrayList<ProviderInfo>(3);
2455 }
2456 finalList.add(PackageParser.generateProviderInfo(p,
2457 flags));
2458 }
2459 }
2460 }
2461
2462 if (finalList != null) {
2463 Collections.sort(finalList, mProviderInitOrderSorter);
2464 }
2465
2466 return finalList;
2467 }
2468
2469 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2470 int flags) {
2471 synchronized (mPackages) {
2472 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2473 return PackageParser.generateInstrumentationInfo(i, flags);
2474 }
2475 }
2476
2477 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2478 int flags) {
2479 ArrayList<InstrumentationInfo> finalList =
2480 new ArrayList<InstrumentationInfo>();
2481
2482 synchronized (mPackages) {
2483 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2484 while (i.hasNext()) {
2485 PackageParser.Instrumentation p = i.next();
2486 if (targetPackage == null
2487 || targetPackage.equals(p.info.targetPackage)) {
2488 finalList.add(PackageParser.generateInstrumentationInfo(p,
2489 flags));
2490 }
2491 }
2492 }
2493
2494 return finalList;
2495 }
2496
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002497 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 String[] files = dir.list();
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07002499 if (files == null) {
2500 Log.d(TAG, "No files in app dir " + dir);
2501 return;
2502 }
2503
Joe Onorato431bb222010-10-18 19:13:23 -04002504 if (false) {
2505 Log.d(TAG, "Scanning app dir " + dir);
2506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507
2508 int i;
2509 for (i=0; i<files.length; i++) {
2510 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002511 if (!isPackageFilename(files[i])) {
2512 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002513 continue;
2514 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002515 PackageParser.Package pkg = scanPackageLI(file,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002516 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002517 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002518 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2519 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002520 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002521 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002522 file.delete();
2523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 }
2525 }
2526
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002527 private static File getSettingsProblemFile() {
2528 File dataDir = Environment.getDataDirectory();
2529 File systemDir = new File(dataDir, "system");
2530 File fname = new File(systemDir, "uiderrors.txt");
2531 return fname;
2532 }
2533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 private static void reportSettingsProblem(int priority, String msg) {
2535 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002536 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 FileOutputStream out = new FileOutputStream(fname, true);
2538 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002539 SimpleDateFormat formatter = new SimpleDateFormat();
2540 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2541 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 pw.close();
2543 FileUtils.setPermissions(
2544 fname.toString(),
2545 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2546 -1, -1);
2547 } catch (java.io.IOException e) {
2548 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002549 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 }
2551
2552 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2553 PackageParser.Package pkg, File srcFile, int parseFlags) {
2554 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002555 if (ps != null
2556 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07002557 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07002558 if (ps.signatures.mSignatures != null
2559 && ps.signatures.mSignatures.length != 0) {
2560 // Optimization: reuse the existing cached certificates
2561 // if the package appears to be unchanged.
2562 pkg.mSignatures = ps.signatures.mSignatures;
2563 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 }
Jeff Browne7600722010-04-07 18:28:23 -07002565
2566 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002567 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002568 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2569 }
2570
2571 if (!pp.collectCertificates(pkg, parseFlags)) {
2572 mLastScanError = pp.getParseError();
2573 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 }
2575 }
2576 return true;
2577 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 /*
2580 * Scan a package and return the newly parsed package.
2581 * Returns null in case of errors and the error code is stored in mLastScanError
2582 */
2583 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002584 int parseFlags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002586 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002588 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002591 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 if (pkg == null) {
2593 mLastScanError = pp.getParseError();
2594 return null;
2595 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002596 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597 PackageSetting updatedPkg;
2598 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002599 // Look to see if we already know about this package.
2600 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002601 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002602 // This package has been renamed to its original name. Let's
2603 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002604 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002605 }
2606 // If there was no original package, see one for the real package name.
2607 if (ps == null) {
2608 ps = mSettings.peekPackageLP(pkg.packageName);
2609 }
2610 // Check to see if this package could be hiding/updating a system
2611 // package. Must look for it either under the original or real
2612 // package name depending on our state.
2613 updatedPkg = mSettings.mDisabledSysPackages.get(
2614 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002616 // First check if this is a system package that may involve an update
2617 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002618 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002619 // The path has changed from what was last scanned... check the
2620 // version of the new path against what we have stored to determine
2621 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002622 if (pkg.mVersionCode < ps.versionCode) {
2623 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002624 // Ignore entry. Skip it.
2625 Log.i(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002626 + " ignored: updated version " + ps.versionCode
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002627 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002628 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2629 return null;
2630 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002631 // The current app on the system partion is better than
2632 // what we have updated to on the data partition; switch
2633 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002634 // At this point, its safely assumed that package installation for
2635 // apps in system partition will go through. If not there won't be a working
2636 // version of the app
2637 synchronized (mPackages) {
2638 // Just remove the loaded entries from package lists.
2639 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002640 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002641 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002642 + "reverting from " + ps.codePathString
2643 + ": new version " + pkg.mVersionCode
2644 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002645 InstallArgs args = new FileInstallArgs(ps.codePathString,
2646 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002647 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002648 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 }
2651 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002652 if (updatedPkg != null) {
2653 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2654 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2655 }
2656 // Verify certificates against what was last scanned
2657 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002658 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002659 return null;
2660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 // The apk is forward locked (not public) if its code and resources
2662 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002663 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002665 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002666 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002667
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002668 String codePath = null;
2669 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002670 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2671 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002672 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002673 } else {
2674 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002675 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002676 }
2677 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002678 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002679 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002680 codePath = pkg.mScanPath;
2681 // Set application objects path explicitly.
2682 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 // Note that we invoke the following method only if we are about to unpack an application
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002684 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE, currentTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 }
2686
Kenny Root85387d72010-08-26 10:13:11 -07002687 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2688 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002689 pkg.mPath = pkg.mScanPath = destCodePath;
2690 pkg.applicationInfo.sourceDir = destCodePath;
2691 pkg.applicationInfo.publicSourceDir = destResPath;
2692 }
2693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 private static String fixProcessName(String defProcessName,
2695 String processName, int uid) {
2696 if (processName == null) {
2697 return defProcessName;
2698 }
2699 return processName;
2700 }
2701
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002702 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002703 PackageParser.Package pkg) {
2704 if (pkgSetting.signatures.mSignatures != null) {
2705 // Already existing package. Make sure signatures match
2706 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2707 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002708 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002709 + " signatures do not match the previously installed version; ignoring!");
2710 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 return false;
2712 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002713 }
2714 // Check for shared user signatures
2715 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2716 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2717 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2718 Slog.e(TAG, "Package " + pkg.packageName
2719 + " has no signatures that match those in shared user "
2720 + pkgSetting.sharedUser.name + "; ignoring!");
2721 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2722 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 }
2725 return true;
2726 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002727
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002728 public boolean performDexOpt(String packageName) {
2729 if (!mNoDexOpt) {
2730 return false;
2731 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002732
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002733 PackageParser.Package p;
2734 synchronized (mPackages) {
2735 p = mPackages.get(packageName);
2736 if (p == null || p.mDidDexOpt) {
2737 return false;
2738 }
2739 }
2740 synchronized (mInstallLock) {
2741 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2742 }
2743 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002744
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002745 static final int DEX_OPT_SKIPPED = 0;
2746 static final int DEX_OPT_PERFORMED = 1;
2747 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002748
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002749 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2750 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002751 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002752 String path = pkg.mScanPath;
2753 int ret = 0;
2754 try {
2755 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002756 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002757 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002758 pkg.mDidDexOpt = true;
2759 performed = true;
2760 }
2761 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002762 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002763 ret = -1;
2764 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002765 Slog.w(TAG, "IOException reading apk: " + path, e);
2766 ret = -1;
2767 } catch (dalvik.system.StaleDexCacheError e) {
2768 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2769 ret = -1;
2770 } catch (Exception e) {
2771 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002772 ret = -1;
2773 }
2774 if (ret < 0) {
2775 //error from installer
2776 return DEX_OPT_FAILED;
2777 }
2778 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002779
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002780 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2781 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002782
2783 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2784 return Environment.isEncryptedFilesystemEnabled() &&
2785 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2786 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002787
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002788 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2789 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002790 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002791 + " to " + newPkg.packageName
2792 + ": old package not in system partition");
2793 return false;
2794 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002795 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002796 + " to " + newPkg.packageName
2797 + ": old package still exists");
2798 return false;
2799 }
2800 return true;
2801 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002802
2803 private File getDataPathForPackage(PackageParser.Package pkg) {
2804 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2805 File dataPath;
2806 if (useEncryptedFSDir) {
2807 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2808 } else {
2809 dataPath = new File(mAppDataDir, pkg.packageName);
2810 }
2811 return dataPath;
2812 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002813
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002814 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002815 int parseFlags, int scanMode, long currentTime) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002816 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002817 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2818 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002819 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002820 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002821 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2822 return null;
2823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 mScanningPath = scanFile;
2825 if (pkg == null) {
2826 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2827 return null;
2828 }
2829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2831 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2832 }
2833
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002834 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 synchronized (mPackages) {
2836 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002837 Slog.w(TAG, "*************************************************");
2838 Slog.w(TAG, "Core android package being redefined. Skipping.");
2839 Slog.w(TAG, " file=" + mScanningPath);
2840 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2842 return null;
2843 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 // Set up information for our fall-back user intent resolution
2846 // activity.
2847 mPlatformPackage = pkg;
2848 pkg.mVersionCode = mSdkVersion;
2849 mAndroidApplication = pkg.applicationInfo;
2850 mResolveActivity.applicationInfo = mAndroidApplication;
2851 mResolveActivity.name = ResolverActivity.class.getName();
2852 mResolveActivity.packageName = mAndroidApplication.packageName;
2853 mResolveActivity.processName = mAndroidApplication.processName;
2854 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2855 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2856 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2857 mResolveActivity.exported = true;
2858 mResolveActivity.enabled = true;
2859 mResolveInfo.activityInfo = mResolveActivity;
2860 mResolveInfo.priority = 0;
2861 mResolveInfo.preferredOrder = 0;
2862 mResolveInfo.match = 0;
2863 mResolveComponentName = new ComponentName(
2864 mAndroidApplication.packageName, mResolveActivity.name);
2865 }
2866 }
2867
2868 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002869 TAG, "Scanning package " + pkg.packageName);
2870 if (mPackages.containsKey(pkg.packageName)
2871 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002872 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 + " already installed. Skipping duplicate.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2875 return null;
2876 }
2877
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002878 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002879 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2880 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 SharedUserSetting suid = null;
2883 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002884
Kenny Root1c6e7642011-01-10 13:48:15 -08002885 if (!isSystemApp(pkg)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002886 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002887 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002888 pkg.mRealPackage = null;
2889 pkg.mAdoptPermissions = null;
2890 }
Kenny Root1c6e7642011-01-10 13:48:15 -08002891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 synchronized (mPackages) {
2893 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002894 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2895 if (mTmpSharedLibraries == null ||
2896 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2897 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2898 }
2899 int num = 0;
2900 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2901 for (int i=0; i<N; i++) {
2902 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002904 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002906 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2908 return null;
2909 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002910 mTmpSharedLibraries[num] = file;
2911 num++;
2912 }
2913 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2914 for (int i=0; i<N; i++) {
2915 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2916 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002917 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002918 + " desires unavailable shared library "
2919 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2920 } else {
2921 mTmpSharedLibraries[num] = file;
2922 num++;
2923 }
2924 }
2925 if (num > 0) {
2926 pkg.usesLibraryFiles = new String[num];
2927 System.arraycopy(mTmpSharedLibraries, 0,
2928 pkg.usesLibraryFiles, 0, num);
2929 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002930
Dianne Hackborn49237342009-08-27 20:08:01 -07002931 if (pkg.reqFeatures != null) {
2932 N = pkg.reqFeatures.size();
2933 for (int i=0; i<N; i++) {
2934 FeatureInfo fi = pkg.reqFeatures.get(i);
2935 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2936 // Don't care.
2937 continue;
2938 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002939
Dianne Hackborn49237342009-08-27 20:08:01 -07002940 if (fi.name != null) {
2941 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002942 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002943 + " requires unavailable feature "
2944 + fi.name + "; failing!");
2945 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2946 return null;
2947 }
2948 }
2949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 }
2951 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953 if (pkg.mSharedUserId != null) {
2954 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2955 pkg.applicationInfo.flags, true);
2956 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002957 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 + " for shared user failed");
2959 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2960 return null;
2961 }
2962 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2963 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2964 + suid.userId + "): packages=" + suid.packages);
2965 }
2966 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002967
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002968 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002969 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002970 Log.w(TAG, "WAITING FOR DEBUGGER");
2971 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002972 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2973 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002974 }
2975 }
2976
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002977 // Check if we are renaming from an original package name.
2978 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002979 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002980 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002981 // This package may need to be renamed to a previously
2982 // installed name. Let's check on that...
2983 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002984 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002985 // This package had originally been installed as the
2986 // original name, and we have already taken care of
2987 // transitioning to the new one. Just update the new
2988 // one to continue using the old name.
2989 realName = pkg.mRealPackage;
2990 if (!pkg.packageName.equals(renamed)) {
2991 // Callers into this function may have already taken
2992 // care of renaming the package; only do it here if
2993 // it is not already done.
2994 pkg.setPackageName(renamed);
2995 }
2996
Dianne Hackbornc1552392010-03-03 16:19:01 -08002997 } else {
2998 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2999 if ((origPackage=mSettings.peekPackageLP(
3000 pkg.mOriginalPackages.get(i))) != null) {
3001 // We do have the package already installed under its
3002 // original name... should we use it?
3003 if (!verifyPackageUpdate(origPackage, pkg)) {
3004 // New package is not compatible with original.
3005 origPackage = null;
3006 continue;
3007 } else if (origPackage.sharedUser != null) {
3008 // Make sure uid is compatible between packages.
3009 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003010 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003011 + " to " + pkg.packageName + ": old uid "
3012 + origPackage.sharedUser.name
3013 + " differs from " + pkg.mSharedUserId);
3014 origPackage = null;
3015 continue;
3016 }
3017 } else {
3018 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3019 + pkg.packageName + " to old name " + origPackage.name);
3020 }
3021 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003022 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003023 }
3024 }
3025 }
3026
3027 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003028 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003029 + " was transferred to another, but its .apk remains");
3030 }
3031
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003032 // Just create the setting, don't add it yet. For already existing packages
3033 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003034 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07003035 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3036 pkg.applicationInfo.flags, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003037 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003038 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003039 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3040 return null;
3041 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003042
3043 if (pkgSetting.origPackage != null) {
3044 // If we are first transitioning from an original package,
3045 // fix up the new package's name now. We need to do this after
3046 // looking up the package under its new name, so getPackageLP
3047 // can take care of fiddling things correctly.
3048 pkg.setPackageName(origPackage.name);
3049
3050 // File a report about this.
3051 String msg = "New package " + pkgSetting.realName
3052 + " renamed to replace old package " + pkgSetting.name;
3053 reportSettingsProblem(Log.WARN, msg);
3054
3055 // Make a note of it.
3056 mTransferedPackages.add(origPackage.name);
3057
3058 // No longer need to retain this.
3059 pkgSetting.origPackage = null;
3060 }
3061
3062 if (realName != null) {
3063 // Make a note of it.
3064 mTransferedPackages.add(pkg.packageName);
3065 }
3066
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003067 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003068 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3069 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003071 pkg.applicationInfo.uid = pkgSetting.userId;
3072 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003073
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003074 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003075 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076 return null;
3077 }
3078 // The signature has changed, but this package is in the system
3079 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003080 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003081 // However... if this package is part of a shared user, but it
3082 // doesn't match the signature of the shared user, let's fail.
3083 // What this means is that you can't change the signatures
3084 // associated with an overall shared user, which doesn't seem all
3085 // that unreasonable.
3086 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003087 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3088 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3089 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3091 return null;
3092 }
3093 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003094 // File a report about this.
3095 String msg = "System package " + pkg.packageName
3096 + " signature changed; retaining data.";
3097 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003099
The Android Open Source Project10592532009-03-18 17:39:46 -07003100 // Verify that this new package doesn't have any content providers
3101 // that conflict with existing packages. Only do this if the
3102 // package isn't already installed, since we don't want to break
3103 // things that are installed.
3104 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3105 int N = pkg.providers.size();
3106 int i;
3107 for (i=0; i<N; i++) {
3108 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003109 if (p.info.authority != null) {
3110 String names[] = p.info.authority.split(";");
3111 for (int j = 0; j < names.length; j++) {
3112 if (mProviders.containsKey(names[j])) {
3113 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003114 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003115 " (in package " + pkg.applicationInfo.packageName +
3116 ") is already used by "
3117 + ((other != null && other.getComponentName() != null)
3118 ? other.getComponentName().getPackageName() : "?"));
3119 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3120 return null;
3121 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003122 }
3123 }
3124 }
3125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 }
3127
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003128 final String pkgName = pkg.packageName;
3129
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003130 if (pkg.mAdoptPermissions != null) {
3131 // This package wants to adopt ownership of permissions from
3132 // another package.
3133 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3134 String origName = pkg.mAdoptPermissions.get(i);
3135 PackageSetting orig = mSettings.peekPackageLP(origName);
3136 if (orig != null) {
3137 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003138 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003139 + origName + " to " + pkg.packageName);
3140 mSettings.transferPermissions(origName, pkg.packageName);
3141 }
3142 }
3143 }
3144 }
3145
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003146 final long scanFileTime = scanFile.lastModified();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
Kenny Root7d794fb2010-09-13 16:29:49 -07003148 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003149 pkg.applicationInfo.processName = fixProcessName(
3150 pkg.applicationInfo.packageName,
3151 pkg.applicationInfo.processName,
3152 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003153
3154 File dataPath;
3155 if (mPlatformPackage == pkg) {
3156 // The system package is special.
3157 dataPath = new File (Environment.getDataDirectory(), "system");
3158 pkg.applicationInfo.dataDir = dataPath.getPath();
3159 } else {
3160 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003161 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003162 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003163
3164 boolean uidError = false;
3165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003166 if (dataPath.exists()) {
3167 mOutPermissions[1] = 0;
3168 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003169
3170 // If we have mismatched owners for the data path, we have a
3171 // problem (unless we're running in the simulator.)
3172 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003173 boolean recovered = false;
3174 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3175 // If this is a system app, we can at least delete its
3176 // current data so the application will still work.
3177 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003178 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003179 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 // Old data gone!
3181 String msg = "System package " + pkg.packageName
3182 + " has changed from uid: "
3183 + mOutPermissions[1] + " to "
3184 + pkg.applicationInfo.uid + "; old data erased";
3185 reportSettingsProblem(Log.WARN, msg);
3186 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003189 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 pkg.applicationInfo.uid);
3191 if (ret == -1) {
3192 // Ack should not happen!
3193 msg = "System package " + pkg.packageName
3194 + " could not have data directory re-created after delete.";
3195 reportSettingsProblem(Log.WARN, msg);
3196 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3197 return null;
3198 }
3199 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003201 if (!recovered) {
3202 mHasSystemUidErrors = true;
3203 }
3204 }
3205 if (!recovered) {
3206 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3207 + pkg.applicationInfo.uid + "/fs_"
3208 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003209 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 String msg = "Package " + pkg.packageName
3211 + " has mismatched uid: "
3212 + mOutPermissions[1] + " on disk, "
3213 + pkg.applicationInfo.uid + " in settings";
3214 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003215 mSettings.mReadMessages.append(msg);
3216 mSettings.mReadMessages.append('\n');
3217 uidError = true;
3218 if (!pkgSetting.uidError) {
3219 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 }
3222 }
3223 }
3224 pkg.applicationInfo.dataDir = dataPath.getPath();
3225 } else {
3226 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3227 Log.v(TAG, "Want this data dir: " + dataPath);
3228 //invoke installer to do the actual installation
3229 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003230 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003231 pkg.applicationInfo.uid);
3232 if(ret < 0) {
3233 // Error from installer
3234 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3235 return null;
3236 }
3237 } else {
3238 dataPath.mkdirs();
3239 if (dataPath.exists()) {
3240 FileUtils.setPermissions(
3241 dataPath.toString(),
3242 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3243 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3244 }
3245 }
3246 if (dataPath.exists()) {
3247 pkg.applicationInfo.dataDir = dataPath.getPath();
3248 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003249 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250 pkg.applicationInfo.dataDir = null;
3251 }
3252 }
Kenny Root85387d72010-08-26 10:13:11 -07003253
3254 /*
3255 * Set the data dir to the default "/data/data/<package name>/lib"
3256 * if we got here without anyone telling us different (e.g., apps
3257 * stored on SD card have their native libraries stored in the ASEC
3258 * container with the APK).
Kenny Root806cc132010-09-12 08:34:19 -07003259 *
3260 * This happens during an upgrade from a package settings file that
3261 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07003262 */
Kenny Rootbd135c12010-10-05 12:26:27 -07003263 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
3264 if (pkgSetting.nativeLibraryPathString == null) {
3265 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
3266 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
3267 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
3268 } else {
3269 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
3270 }
Kenny Root85387d72010-08-26 10:13:11 -07003271 }
3272
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003273 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274 }
3275
Kenny Root85387d72010-08-26 10:13:11 -07003276 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277 if (mInstaller != null) {
3278 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003279 /* Note: We don't want to unpack the native binaries for
3280 * system applications, unless they have been updated
3281 * (the binaries are already under /system/lib).
3282 * Also, don't unpack libs for apps on the external card
3283 * since they should have their libraries in the ASEC
3284 * container already.
3285 *
3286 * In other words, we're going to unpack the binaries
3287 * only for non-system apps and system app upgrades.
3288 */
Kenny Root831baa22010-10-05 12:29:25 -07003289 if (pkg.applicationInfo.nativeLibraryDir != null) {
Kenny Roote68d58a2010-10-18 16:08:54 -07003290 final File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
3291 final String dataPathString = dataPath.getPath();
3292
Kenny Root831baa22010-10-05 12:29:25 -07003293 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
3294 /*
3295 * Upgrading from a previous version of the OS sometimes
3296 * leaves native libraries in the /data/data/<app>/lib
3297 * directory for system apps even when they shouldn't be.
3298 * Recent changes in the JNI library search path
3299 * necessitates we remove those to match previous behavior.
3300 */
Kenny Roote68d58a2010-10-18 16:08:54 -07003301 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
Kenny Root831baa22010-10-05 12:29:25 -07003302 Log.i(TAG, "removed obsolete native libraries for system package " + path);
3303 }
Kenny Roote68d58a2010-10-18 16:08:54 -07003304 } else if (nativeLibraryDir.getParent().equals(dataPathString)) {
3305 /*
3306 * If this is an internal application or our
3307 * nativeLibraryPath points to our data directory, unpack
3308 * the libraries. The native library path pointing to the
3309 * data directory for an application in an ASEC container
3310 * can happen for older apps that existed before an OTA to
3311 * Gingerbread.
3312 */
3313 Slog.i(TAG, "Unpacking native libraries for " + path);
3314 mInstaller.unlinkNativeLibraryDirectory(dataPathString);
3315 NativeLibraryHelper.copyNativeBinariesLI(scanFile, nativeLibraryDir);
Kenny Root6a6b0072010-10-07 16:46:10 -07003316 } else {
Kenny Roote68d58a2010-10-18 16:08:54 -07003317 Slog.i(TAG, "Linking native library dir for " + path);
3318 mInstaller.linkNativeLibraryDirectory(dataPathString,
Kenny Root6a6b0072010-10-07 16:46:10 -07003319 pkg.applicationInfo.nativeLibraryDir);
Kenny Root831baa22010-10-05 12:29:25 -07003320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003322 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003323
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003324 if ((scanMode&SCAN_NO_DEX) == 0) {
3325 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3327 return null;
3328 }
3329 }
3330 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003332 if (mFactoryTest && pkg.requestedPermissions.contains(
3333 android.Manifest.permission.FACTORY_TEST)) {
3334 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3335 }
3336
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003337 // Request the ActivityManager to kill the process(only for existing packages)
3338 // so that we do not end up in a confused state while the user is still using the older
3339 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003340 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003341 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003342 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003343 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003346 // We don't expect installation to fail beyond this point,
3347 if ((scanMode&SCAN_MONITOR) != 0) {
3348 mAppDirs.put(pkg.mPath, pkg);
3349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003351 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003353 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003354 // Make sure we don't accidentally delete its data.
3355 mSettings.mPackagesToBeCleaned.remove(pkgName);
3356
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003357 // Take care of first install / last update times.
3358 if (currentTime != 0) {
3359 if (pkgSetting.firstInstallTime == 0) {
3360 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
3361 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
3362 pkgSetting.lastUpdateTime = currentTime;
3363 }
3364 } else if (pkgSetting.firstInstallTime == 0) {
3365 // We need *something*. Take time time stamp of the file.
3366 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
3367 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
3368 if (scanFileTime != pkgSetting.timeStamp) {
3369 // A package on the system image has changed; consider this
3370 // to be an update.
3371 pkgSetting.lastUpdateTime = scanFileTime;
3372 }
3373 }
3374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375 int N = pkg.providers.size();
3376 StringBuilder r = null;
3377 int i;
3378 for (i=0; i<N; i++) {
3379 PackageParser.Provider p = pkg.providers.get(i);
3380 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3381 p.info.processName, pkg.applicationInfo.uid);
3382 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3383 p.info.name), p);
3384 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003385 if (p.info.authority != null) {
3386 String names[] = p.info.authority.split(";");
3387 p.info.authority = null;
3388 for (int j = 0; j < names.length; j++) {
3389 if (j == 1 && p.syncable) {
3390 // We only want the first authority for a provider to possibly be
3391 // syncable, so if we already added this provider using a different
3392 // authority clear the syncable flag. We copy the provider before
3393 // changing it because the mProviders object contains a reference
3394 // to a provider that we don't want to change.
3395 // Only do this for the second authority since the resulting provider
3396 // object can be the same for all future authorities for this provider.
3397 p = new PackageParser.Provider(p);
3398 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003399 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003400 if (!mProviders.containsKey(names[j])) {
3401 mProviders.put(names[j], p);
3402 if (p.info.authority == null) {
3403 p.info.authority = names[j];
3404 } else {
3405 p.info.authority = p.info.authority + ";" + names[j];
3406 }
3407 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3408 Log.d(TAG, "Registered content provider: " + names[j] +
3409 ", className = " + p.info.name +
3410 ", isSyncable = " + p.info.isSyncable);
3411 } else {
3412 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003413 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003414 " (in package " + pkg.applicationInfo.packageName +
3415 "): name already used by "
3416 + ((other != null && other.getComponentName() != null)
3417 ? other.getComponentName().getPackageName() : "?"));
3418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419 }
3420 }
3421 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3422 if (r == null) {
3423 r = new StringBuilder(256);
3424 } else {
3425 r.append(' ');
3426 }
3427 r.append(p.info.name);
3428 }
3429 }
3430 if (r != null) {
3431 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3432 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003434 N = pkg.services.size();
3435 r = null;
3436 for (i=0; i<N; i++) {
3437 PackageParser.Service s = pkg.services.get(i);
3438 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3439 s.info.processName, pkg.applicationInfo.uid);
3440 mServices.addService(s);
3441 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3442 if (r == null) {
3443 r = new StringBuilder(256);
3444 } else {
3445 r.append(' ');
3446 }
3447 r.append(s.info.name);
3448 }
3449 }
3450 if (r != null) {
3451 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3452 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003454 N = pkg.receivers.size();
3455 r = null;
3456 for (i=0; i<N; i++) {
3457 PackageParser.Activity a = pkg.receivers.get(i);
3458 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3459 a.info.processName, pkg.applicationInfo.uid);
3460 mReceivers.addActivity(a, "receiver");
3461 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3462 if (r == null) {
3463 r = new StringBuilder(256);
3464 } else {
3465 r.append(' ');
3466 }
3467 r.append(a.info.name);
3468 }
3469 }
3470 if (r != null) {
3471 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3472 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 N = pkg.activities.size();
3475 r = null;
3476 for (i=0; i<N; i++) {
3477 PackageParser.Activity a = pkg.activities.get(i);
3478 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3479 a.info.processName, pkg.applicationInfo.uid);
3480 mActivities.addActivity(a, "activity");
3481 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3482 if (r == null) {
3483 r = new StringBuilder(256);
3484 } else {
3485 r.append(' ');
3486 }
3487 r.append(a.info.name);
3488 }
3489 }
3490 if (r != null) {
3491 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3492 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 N = pkg.permissionGroups.size();
3495 r = null;
3496 for (i=0; i<N; i++) {
3497 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3498 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3499 if (cur == null) {
3500 mPermissionGroups.put(pg.info.name, pg);
3501 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3502 if (r == null) {
3503 r = new StringBuilder(256);
3504 } else {
3505 r.append(' ');
3506 }
3507 r.append(pg.info.name);
3508 }
3509 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003510 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511 + pg.info.packageName + " ignored: original from "
3512 + cur.info.packageName);
3513 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3514 if (r == null) {
3515 r = new StringBuilder(256);
3516 } else {
3517 r.append(' ');
3518 }
3519 r.append("DUP:");
3520 r.append(pg.info.name);
3521 }
3522 }
3523 }
3524 if (r != null) {
3525 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3526 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528 N = pkg.permissions.size();
3529 r = null;
3530 for (i=0; i<N; i++) {
3531 PackageParser.Permission p = pkg.permissions.get(i);
3532 HashMap<String, BasePermission> permissionMap =
3533 p.tree ? mSettings.mPermissionTrees
3534 : mSettings.mPermissions;
3535 p.group = mPermissionGroups.get(p.info.group);
3536 if (p.info.group == null || p.group != null) {
3537 BasePermission bp = permissionMap.get(p.info.name);
3538 if (bp == null) {
3539 bp = new BasePermission(p.info.name, p.info.packageName,
3540 BasePermission.TYPE_NORMAL);
3541 permissionMap.put(p.info.name, bp);
3542 }
3543 if (bp.perm == null) {
3544 if (bp.sourcePackage == null
3545 || bp.sourcePackage.equals(p.info.packageName)) {
3546 BasePermission tree = findPermissionTreeLP(p.info.name);
3547 if (tree == null
3548 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003549 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003550 bp.perm = p;
3551 bp.uid = pkg.applicationInfo.uid;
3552 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3553 if (r == null) {
3554 r = new StringBuilder(256);
3555 } else {
3556 r.append(' ');
3557 }
3558 r.append(p.info.name);
3559 }
3560 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003561 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003562 + p.info.packageName + " ignored: base tree "
3563 + tree.name + " is from package "
3564 + tree.sourcePackage);
3565 }
3566 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003567 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 + p.info.packageName + " ignored: original from "
3569 + bp.sourcePackage);
3570 }
3571 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3572 if (r == null) {
3573 r = new StringBuilder(256);
3574 } else {
3575 r.append(' ');
3576 }
3577 r.append("DUP:");
3578 r.append(p.info.name);
3579 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003580 if (bp.perm == p) {
3581 bp.protectionLevel = p.info.protectionLevel;
3582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003583 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003584 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003585 + p.info.packageName + " ignored: no group "
3586 + p.group);
3587 }
3588 }
3589 if (r != null) {
3590 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3591 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003593 N = pkg.instrumentation.size();
3594 r = null;
3595 for (i=0; i<N; i++) {
3596 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3597 a.info.packageName = pkg.applicationInfo.packageName;
3598 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3599 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3600 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003601 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003602 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003603 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3604 if (r == null) {
3605 r = new StringBuilder(256);
3606 } else {
3607 r.append(' ');
3608 }
3609 r.append(a.info.name);
3610 }
3611 }
3612 if (r != null) {
3613 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3614 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003615
Dianne Hackborn854060af2009-07-09 18:14:31 -07003616 if (pkg.protectedBroadcasts != null) {
3617 N = pkg.protectedBroadcasts.size();
3618 for (i=0; i<N; i++) {
3619 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3620 }
3621 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003623 pkgSetting.setTimeStamp(scanFileTime);
3624 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 return pkg;
3627 }
3628
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003629 private void killApplication(String pkgName, int uid) {
3630 // Request the ActivityManager to kill the process(only for existing packages)
3631 // so that we do not end up in a confused state while the user is still using the older
3632 // version of the application while the new one gets installed.
3633 IActivityManager am = ActivityManagerNative.getDefault();
3634 if (am != null) {
3635 try {
3636 am.killApplicationWithUid(pkgName, uid);
3637 } catch (RemoteException e) {
3638 }
3639 }
3640 }
3641
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003642 // Return the path of the directory that will contain the native binaries
3643 // of a given installed package. This is relative to the data path.
3644 //
Kenny Root85387d72010-08-26 10:13:11 -07003645 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3646 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3647 if (nativeLibraryDir != null) {
3648 return new File(nativeLibraryDir);
3649 } else {
3650 // Fall back for old packages
3651 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3652 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003653 }
3654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003655 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3656 if (chatty && Config.LOGD) Log.d(
3657 TAG, "Removing package " + pkg.applicationInfo.packageName );
3658
3659 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003660 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662 mPackages.remove(pkg.applicationInfo.packageName);
3663 if (pkg.mPath != null) {
3664 mAppDirs.remove(pkg.mPath);
3665 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 int N = pkg.providers.size();
3668 StringBuilder r = null;
3669 int i;
3670 for (i=0; i<N; i++) {
3671 PackageParser.Provider p = pkg.providers.get(i);
3672 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3673 p.info.name));
3674 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 /* The is another ContentProvider with this authority when
3677 * this app was installed so this authority is null,
3678 * Ignore it as we don't have to unregister the provider.
3679 */
3680 continue;
3681 }
3682 String names[] = p.info.authority.split(";");
3683 for (int j = 0; j < names.length; j++) {
3684 if (mProviders.get(names[j]) == p) {
3685 mProviders.remove(names[j]);
3686 if (chatty && Config.LOGD) Log.d(
3687 TAG, "Unregistered content provider: " + names[j] +
3688 ", className = " + p.info.name +
3689 ", isSyncable = " + p.info.isSyncable);
3690 }
3691 }
3692 if (chatty) {
3693 if (r == null) {
3694 r = new StringBuilder(256);
3695 } else {
3696 r.append(' ');
3697 }
3698 r.append(p.info.name);
3699 }
3700 }
3701 if (r != null) {
3702 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3703 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 N = pkg.services.size();
3706 r = null;
3707 for (i=0; i<N; i++) {
3708 PackageParser.Service s = pkg.services.get(i);
3709 mServices.removeService(s);
3710 if (chatty) {
3711 if (r == null) {
3712 r = new StringBuilder(256);
3713 } else {
3714 r.append(' ');
3715 }
3716 r.append(s.info.name);
3717 }
3718 }
3719 if (r != null) {
3720 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3721 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723 N = pkg.receivers.size();
3724 r = null;
3725 for (i=0; i<N; i++) {
3726 PackageParser.Activity a = pkg.receivers.get(i);
3727 mReceivers.removeActivity(a, "receiver");
3728 if (chatty) {
3729 if (r == null) {
3730 r = new StringBuilder(256);
3731 } else {
3732 r.append(' ');
3733 }
3734 r.append(a.info.name);
3735 }
3736 }
3737 if (r != null) {
3738 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3739 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741 N = pkg.activities.size();
3742 r = null;
3743 for (i=0; i<N; i++) {
3744 PackageParser.Activity a = pkg.activities.get(i);
3745 mActivities.removeActivity(a, "activity");
3746 if (chatty) {
3747 if (r == null) {
3748 r = new StringBuilder(256);
3749 } else {
3750 r.append(' ');
3751 }
3752 r.append(a.info.name);
3753 }
3754 }
3755 if (r != null) {
3756 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3757 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003759 N = pkg.permissions.size();
3760 r = null;
3761 for (i=0; i<N; i++) {
3762 PackageParser.Permission p = pkg.permissions.get(i);
3763 boolean tree = false;
3764 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3765 if (bp == null) {
3766 tree = true;
3767 bp = mSettings.mPermissionTrees.get(p.info.name);
3768 }
3769 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003770 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003771 if (chatty) {
3772 if (r == null) {
3773 r = new StringBuilder(256);
3774 } else {
3775 r.append(' ');
3776 }
3777 r.append(p.info.name);
3778 }
3779 }
3780 }
3781 if (r != null) {
3782 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3783 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003785 N = pkg.instrumentation.size();
3786 r = null;
3787 for (i=0; i<N; i++) {
3788 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003789 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790 if (chatty) {
3791 if (r == null) {
3792 r = new StringBuilder(256);
3793 } else {
3794 r.append(' ');
3795 }
3796 r.append(a.info.name);
3797 }
3798 }
3799 if (r != null) {
3800 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3801 }
3802 }
3803 }
3804
3805 private static final boolean isPackageFilename(String name) {
3806 return name != null && name.endsWith(".apk");
3807 }
3808
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003809 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3810 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3811 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3812 return true;
3813 }
3814 }
3815 return false;
3816 }
3817
3818 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003819 PackageParser.Package pkgInfo, boolean grantPermissions,
3820 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003821 // Make sure there are no dangling permission trees.
3822 Iterator<BasePermission> it = mSettings.mPermissionTrees
3823 .values().iterator();
3824 while (it.hasNext()) {
3825 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003826 if (bp.packageSetting == null) {
3827 // We may not yet have parsed the package, so just see if
3828 // we still know about its settings.
3829 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3830 }
3831 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003832 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833 + " from package " + bp.sourcePackage);
3834 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003835 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3836 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3837 Slog.i(TAG, "Removing old permission tree: " + bp.name
3838 + " from package " + bp.sourcePackage);
3839 grantPermissions = true;
3840 it.remove();
3841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842 }
3843 }
3844
3845 // Make sure all dynamic permissions have been assigned to a package,
3846 // and make sure there are no dangling permissions.
3847 it = mSettings.mPermissions.values().iterator();
3848 while (it.hasNext()) {
3849 BasePermission bp = it.next();
3850 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3851 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3852 + bp.name + " pkg=" + bp.sourcePackage
3853 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003854 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003855 BasePermission tree = findPermissionTreeLP(bp.name);
3856 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003857 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003858 bp.perm = new PackageParser.Permission(tree.perm.owner,
3859 new PermissionInfo(bp.pendingInfo));
3860 bp.perm.info.packageName = tree.perm.info.packageName;
3861 bp.perm.info.name = bp.name;
3862 bp.uid = tree.uid;
3863 }
3864 }
3865 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003866 if (bp.packageSetting == null) {
3867 // We may not yet have parsed the package, so just see if
3868 // we still know about its settings.
3869 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3870 }
3871 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003872 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003873 + " from package " + bp.sourcePackage);
3874 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003875 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3876 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3877 Slog.i(TAG, "Removing old permission: " + bp.name
3878 + " from package " + bp.sourcePackage);
3879 grantPermissions = true;
3880 it.remove();
3881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 }
3883 }
3884
3885 // Now update the permissions for all packages, in particular
3886 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003887 if (grantPermissions) {
3888 for (PackageParser.Package pkg : mPackages.values()) {
3889 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003890 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003891 }
3892 }
3893 }
3894
3895 if (pkgInfo != null) {
3896 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897 }
3898 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3901 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3902 if (ps == null) {
3903 return;
3904 }
3905 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003906 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 if (replace) {
3909 ps.permissionsFixed = false;
3910 if (gp == ps) {
3911 gp.grantedPermissions.clear();
3912 gp.gids = mGlobalGids;
3913 }
3914 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003916 if (gp.gids == null) {
3917 gp.gids = mGlobalGids;
3918 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 final int N = pkg.requestedPermissions.size();
3921 for (int i=0; i<N; i++) {
3922 String name = pkg.requestedPermissions.get(i);
3923 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 if (false) {
3925 if (gp != ps) {
3926 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003927 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 }
3929 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003930 if (bp != null && bp.packageSetting != null) {
3931 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003932 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003933 boolean allowedSig = false;
3934 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3935 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003937 } else if (bp.packageSetting == null) {
3938 // This permission is invalid; skip it.
3939 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003940 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3941 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003942 allowed = (checkSignaturesLP(
3943 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003944 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003945 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 == PackageManager.SIGNATURE_MATCH);
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003947 if (!allowed && bp.protectionLevel
3948 == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003949 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950 // For updated system applications, the signatureOrSystem permission
3951 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003952 if (isUpdatedSystemApp(pkg)) {
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003953 PackageSetting sysPs = mSettings.getDisabledSystemPkg(
3954 pkg.packageName);
3955 final GrantedPermissions origGp = sysPs.sharedUser != null
3956 ? sysPs.sharedUser : sysPs;
3957 if (origGp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 allowed = true;
3959 } else {
3960 allowed = false;
3961 }
3962 } else {
3963 allowed = true;
3964 }
3965 }
3966 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003967 if (allowed) {
3968 allowedSig = true;
3969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970 } else {
3971 allowed = false;
3972 }
3973 if (false) {
3974 if (gp != ps) {
3975 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3976 }
3977 }
3978 if (allowed) {
3979 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3980 && ps.permissionsFixed) {
3981 // If this is an existing, non-system package, then
3982 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003983 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003985 // Except... if this is a permission that was added
3986 // to the platform (note: need to only do this when
3987 // updating the platform).
3988 final int NP = PackageParser.NEW_PERMISSIONS.length;
3989 for (int ip=0; ip<NP; ip++) {
3990 final PackageParser.NewPermissionInfo npi
3991 = PackageParser.NEW_PERMISSIONS[ip];
3992 if (npi.name.equals(perm)
3993 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3994 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003995 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003996 + pkg.packageName);
3997 break;
3998 }
3999 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 }
4001 }
4002 if (allowed) {
4003 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004004 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004005 gp.grantedPermissions.add(perm);
4006 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004007 } else if (!ps.haveGids) {
4008 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 }
4010 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004011 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 + " to package " + pkg.packageName
4013 + " because it was previously installed without");
4014 }
4015 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004016 if (gp.grantedPermissions.remove(perm)) {
4017 changedPermission = true;
4018 gp.gids = removeInts(gp.gids, bp.gids);
4019 Slog.i(TAG, "Un-granting permission " + perm
4020 + " from package " + pkg.packageName
4021 + " (protectionLevel=" + bp.protectionLevel
4022 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4023 + ")");
4024 } else {
4025 Slog.w(TAG, "Not granting permission " + perm
4026 + " to package " + pkg.packageName
4027 + " (protectionLevel=" + bp.protectionLevel
4028 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4029 + ")");
4030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 }
4032 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004033 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034 + " in package " + pkg.packageName);
4035 }
4036 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004037
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004038 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004039 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4040 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 // This is the first that we have heard about this package, so the
4042 // permissions we have now selected are fixed until explicitly
4043 // changed.
4044 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004046 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004047 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004049 private final class ActivityIntentResolver
4050 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004051 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004052 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004053 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004054 }
4055
Mihai Preda074edef2009-05-18 17:13:31 +02004056 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004057 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004058 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004059 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4060 }
4061
Mihai Predaeae850c2009-05-13 10:13:48 +02004062 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4063 ArrayList<PackageParser.Activity> packageActivities) {
4064 if (packageActivities == null) {
4065 return null;
4066 }
4067 mFlags = flags;
4068 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4069 int N = packageActivities.size();
4070 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4071 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004072
4073 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004074 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004075 intentFilters = packageActivities.get(i).intents;
4076 if (intentFilters != null && intentFilters.size() > 0) {
4077 listCut.add(intentFilters);
4078 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004079 }
4080 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4081 }
4082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004083 public final void addActivity(PackageParser.Activity a, String type) {
Kenny Root1c6e7642011-01-10 13:48:15 -08004084 final boolean systemApp = isSystemApp(a.info.applicationInfo);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004085 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 if (SHOW_INFO || Config.LOGV) Log.v(
4087 TAG, " " + type + " " +
4088 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4089 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4090 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004091 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004092 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
Kenny Root1c6e7642011-01-10 13:48:15 -08004093 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
4094 intent.setPriority(0);
4095 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
4096 + a.className + " with priority > 0, forcing to 0");
4097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 if (SHOW_INFO || Config.LOGV) {
4099 Log.v(TAG, " IntentFilter:");
4100 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4101 }
4102 if (!intent.debugCheck()) {
4103 Log.w(TAG, "==> For Activity " + a.info.name);
4104 }
4105 addFilter(intent);
4106 }
4107 }
4108
4109 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004110 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004111 if (SHOW_INFO || Config.LOGV) Log.v(
4112 TAG, " " + type + " " +
4113 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4114 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4115 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004116 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004117 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4118 if (SHOW_INFO || Config.LOGV) {
4119 Log.v(TAG, " IntentFilter:");
4120 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4121 }
4122 removeFilter(intent);
4123 }
4124 }
4125
4126 @Override
4127 protected boolean allowFilterResult(
4128 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4129 ActivityInfo filterAi = filter.activity.info;
4130 for (int i=dest.size()-1; i>=0; i--) {
4131 ActivityInfo destAi = dest.get(i).activityInfo;
4132 if (destAi.name == filterAi.name
4133 && destAi.packageName == filterAi.packageName) {
4134 return false;
4135 }
4136 }
4137 return true;
4138 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004140 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004141 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4142 return info.activity.owner.packageName;
4143 }
4144
4145 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004146 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4147 int match) {
4148 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4149 return null;
4150 }
4151 final PackageParser.Activity activity = info.activity;
4152 if (mSafeMode && (activity.info.applicationInfo.flags
4153 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4154 return null;
4155 }
4156 final ResolveInfo res = new ResolveInfo();
4157 res.activityInfo = PackageParser.generateActivityInfo(activity,
4158 mFlags);
4159 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4160 res.filter = info;
4161 }
4162 res.priority = info.getPriority();
4163 res.preferredOrder = activity.owner.mPreferredOrder;
4164 //System.out.println("Result: " + res.activityInfo.className +
4165 // " = " + res.priority);
4166 res.match = match;
4167 res.isDefault = info.hasDefault;
4168 res.labelRes = info.labelRes;
4169 res.nonLocalizedLabel = info.nonLocalizedLabel;
4170 res.icon = info.icon;
4171 return res;
4172 }
4173
4174 @Override
4175 protected void sortResults(List<ResolveInfo> results) {
4176 Collections.sort(results, mResolvePrioritySorter);
4177 }
4178
4179 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004180 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004181 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004182 out.print(prefix); out.print(
4183 Integer.toHexString(System.identityHashCode(filter.activity)));
4184 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004185 out.print(filter.activity.getComponentShortName());
4186 out.print(" filter ");
4187 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004188 }
4189
4190// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4191// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4192// final List<ResolveInfo> retList = Lists.newArrayList();
4193// while (i.hasNext()) {
4194// final ResolveInfo resolveInfo = i.next();
4195// if (isEnabledLP(resolveInfo.activityInfo)) {
4196// retList.add(resolveInfo);
4197// }
4198// }
4199// return retList;
4200// }
4201
4202 // Keys are String (activity class name), values are Activity.
4203 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4204 = new HashMap<ComponentName, PackageParser.Activity>();
4205 private int mFlags;
4206 }
4207
4208 private final class ServiceIntentResolver
4209 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004210 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004212 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004213 }
4214
Mihai Preda074edef2009-05-18 17:13:31 +02004215 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004217 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004218 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4219 }
4220
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004221 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4222 ArrayList<PackageParser.Service> packageServices) {
4223 if (packageServices == null) {
4224 return null;
4225 }
4226 mFlags = flags;
4227 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4228 int N = packageServices.size();
4229 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4230 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4231
4232 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4233 for (int i = 0; i < N; ++i) {
4234 intentFilters = packageServices.get(i).intents;
4235 if (intentFilters != null && intentFilters.size() > 0) {
4236 listCut.add(intentFilters);
4237 }
4238 }
4239 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4240 }
4241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004242 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004243 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004244 if (SHOW_INFO || Config.LOGV) Log.v(
4245 TAG, " " + (s.info.nonLocalizedLabel != null
4246 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4247 if (SHOW_INFO || Config.LOGV) Log.v(
4248 TAG, " Class=" + s.info.name);
4249 int NI = s.intents.size();
4250 int j;
4251 for (j=0; j<NI; j++) {
4252 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4253 if (SHOW_INFO || Config.LOGV) {
4254 Log.v(TAG, " IntentFilter:");
4255 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4256 }
4257 if (!intent.debugCheck()) {
4258 Log.w(TAG, "==> For Service " + s.info.name);
4259 }
4260 addFilter(intent);
4261 }
4262 }
4263
4264 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004265 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004266 if (SHOW_INFO || Config.LOGV) Log.v(
4267 TAG, " " + (s.info.nonLocalizedLabel != null
4268 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4269 if (SHOW_INFO || Config.LOGV) Log.v(
4270 TAG, " Class=" + s.info.name);
4271 int NI = s.intents.size();
4272 int j;
4273 for (j=0; j<NI; j++) {
4274 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4275 if (SHOW_INFO || Config.LOGV) {
4276 Log.v(TAG, " IntentFilter:");
4277 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4278 }
4279 removeFilter(intent);
4280 }
4281 }
4282
4283 @Override
4284 protected boolean allowFilterResult(
4285 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4286 ServiceInfo filterSi = filter.service.info;
4287 for (int i=dest.size()-1; i>=0; i--) {
4288 ServiceInfo destAi = dest.get(i).serviceInfo;
4289 if (destAi.name == filterSi.name
4290 && destAi.packageName == filterSi.packageName) {
4291 return false;
4292 }
4293 }
4294 return true;
4295 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004297 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004298 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4299 return info.service.owner.packageName;
4300 }
4301
4302 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004303 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4304 int match) {
4305 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4306 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4307 return null;
4308 }
4309 final PackageParser.Service service = info.service;
4310 if (mSafeMode && (service.info.applicationInfo.flags
4311 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4312 return null;
4313 }
4314 final ResolveInfo res = new ResolveInfo();
4315 res.serviceInfo = PackageParser.generateServiceInfo(service,
4316 mFlags);
4317 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4318 res.filter = filter;
4319 }
4320 res.priority = info.getPriority();
4321 res.preferredOrder = service.owner.mPreferredOrder;
4322 //System.out.println("Result: " + res.activityInfo.className +
4323 // " = " + res.priority);
4324 res.match = match;
4325 res.isDefault = info.hasDefault;
4326 res.labelRes = info.labelRes;
4327 res.nonLocalizedLabel = info.nonLocalizedLabel;
4328 res.icon = info.icon;
4329 return res;
4330 }
4331
4332 @Override
4333 protected void sortResults(List<ResolveInfo> results) {
4334 Collections.sort(results, mResolvePrioritySorter);
4335 }
4336
4337 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004338 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004339 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004340 out.print(prefix); out.print(
4341 Integer.toHexString(System.identityHashCode(filter.service)));
4342 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004343 out.print(filter.service.getComponentShortName());
4344 out.print(" filter ");
4345 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004346 }
4347
4348// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4349// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4350// final List<ResolveInfo> retList = Lists.newArrayList();
4351// while (i.hasNext()) {
4352// final ResolveInfo resolveInfo = (ResolveInfo) i;
4353// if (isEnabledLP(resolveInfo.serviceInfo)) {
4354// retList.add(resolveInfo);
4355// }
4356// }
4357// return retList;
4358// }
4359
4360 // Keys are String (activity class name), values are Activity.
4361 private final HashMap<ComponentName, PackageParser.Service> mServices
4362 = new HashMap<ComponentName, PackageParser.Service>();
4363 private int mFlags;
4364 };
4365
4366 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4367 new Comparator<ResolveInfo>() {
4368 public int compare(ResolveInfo r1, ResolveInfo r2) {
4369 int v1 = r1.priority;
4370 int v2 = r2.priority;
4371 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4372 if (v1 != v2) {
4373 return (v1 > v2) ? -1 : 1;
4374 }
4375 v1 = r1.preferredOrder;
4376 v2 = r2.preferredOrder;
4377 if (v1 != v2) {
4378 return (v1 > v2) ? -1 : 1;
4379 }
4380 if (r1.isDefault != r2.isDefault) {
4381 return r1.isDefault ? -1 : 1;
4382 }
4383 v1 = r1.match;
4384 v2 = r2.match;
4385 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4386 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4387 }
4388 };
4389
4390 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4391 new Comparator<ProviderInfo>() {
4392 public int compare(ProviderInfo p1, ProviderInfo p2) {
4393 final int v1 = p1.initOrder;
4394 final int v2 = p2.initOrder;
4395 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4396 }
4397 };
4398
Kenny Root93565c4b2010-06-18 15:46:06 -07004399 private static final boolean DEBUG_OBB = false;
4400
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004401 private static final void sendPackageBroadcast(String action, String pkg,
4402 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004403 IActivityManager am = ActivityManagerNative.getDefault();
4404 if (am != null) {
4405 try {
4406 final Intent intent = new Intent(action,
4407 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4408 if (extras != null) {
4409 intent.putExtras(extras);
4410 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004411 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004412 am.broadcastIntent(null, intent, null, finishedReceiver,
4413 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004414 } catch (RemoteException ex) {
4415 }
4416 }
4417 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004418
4419 public String nextPackageToClean(String lastPackage) {
4420 synchronized (mPackages) {
4421 if (!mMediaMounted) {
4422 // If the external storage is no longer mounted at this point,
4423 // the caller may not have been able to delete all of this
4424 // packages files and can not delete any more. Bail.
4425 return null;
4426 }
4427 if (lastPackage != null) {
4428 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4429 }
4430 return mSettings.mPackagesToBeCleaned.size() > 0
4431 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4432 }
4433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004434
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004435 void schedulePackageCleaning(String packageName) {
4436 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4437 }
4438
4439 void startCleaningPackages() {
4440 synchronized (mPackages) {
4441 if (!mMediaMounted) {
4442 return;
4443 }
4444 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4445 return;
4446 }
4447 }
4448 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4449 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4450 IActivityManager am = ActivityManagerNative.getDefault();
4451 if (am != null) {
4452 try {
4453 am.startService(null, intent, null);
4454 } catch (RemoteException e) {
4455 }
4456 }
4457 }
4458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004459 private final class AppDirObserver extends FileObserver {
4460 public AppDirObserver(String path, int mask, boolean isrom) {
4461 super(path, mask);
4462 mRootDir = path;
4463 mIsRom = isrom;
4464 }
4465
4466 public void onEvent(int event, String path) {
4467 String removedPackage = null;
4468 int removedUid = -1;
4469 String addedPackage = null;
4470 int addedUid = -1;
4471
4472 synchronized (mInstallLock) {
4473 String fullPathStr = null;
4474 File fullPath = null;
4475 if (path != null) {
4476 fullPath = new File(mRootDir, path);
4477 fullPathStr = fullPath.getPath();
4478 }
4479
4480 if (Config.LOGV) Log.v(
4481 TAG, "File " + fullPathStr + " changed: "
4482 + Integer.toHexString(event));
4483
4484 if (!isPackageFilename(path)) {
4485 if (Config.LOGV) Log.v(
4486 TAG, "Ignoring change of non-package file: " + fullPathStr);
4487 return;
4488 }
4489
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004490 // Ignore packages that are being installed or
4491 // have just been installed.
4492 if (ignoreCodePath(fullPathStr)) {
4493 return;
4494 }
4495 PackageParser.Package p = null;
4496 synchronized (mPackages) {
4497 p = mAppDirs.get(fullPathStr);
4498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004499 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004500 if (p != null) {
4501 removePackageLI(p, true);
4502 removedPackage = p.applicationInfo.packageName;
4503 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004504 }
4505 }
4506
4507 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004508 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004509 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004510 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4511 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004512 PackageParser.PARSE_CHATTY |
4513 PackageParser.PARSE_MUST_BE_APK,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07004514 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
4515 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004516 if (p != null) {
4517 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004518 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004519 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520 }
4521 addedPackage = p.applicationInfo.packageName;
4522 addedUid = p.applicationInfo.uid;
4523 }
4524 }
4525 }
4526
4527 synchronized (mPackages) {
4528 mSettings.writeLP();
4529 }
4530 }
4531
4532 if (removedPackage != null) {
4533 Bundle extras = new Bundle(1);
4534 extras.putInt(Intent.EXTRA_UID, removedUid);
4535 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004536 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4537 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004538 }
4539 if (addedPackage != null) {
4540 Bundle extras = new Bundle(1);
4541 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004542 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4543 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004544 }
4545 }
4546
4547 private final String mRootDir;
4548 private final boolean mIsRom;
4549 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004551 /* Called when a downloaded package installation has been confirmed by the user */
4552 public void installPackage(
4553 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004554 installPackage(packageURI, observer, flags, null);
4555 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004556
Jacek Surazski65e13172009-04-28 15:26:38 +02004557 /* Called when a downloaded package installation has been confirmed by the user */
4558 public void installPackage(
4559 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4560 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004561 mContext.enforceCallingOrSelfPermission(
4562 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004563
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004564 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004565 msg.obj = new InstallParams(packageURI, observer, flags,
4566 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004567 mHandler.sendMessage(msg);
4568 }
4569
Christopher Tate1bb69062010-02-19 17:02:12 -08004570 public void finishPackageInstall(int token) {
4571 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4572 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4573 mHandler.sendMessage(msg);
4574 }
4575
Kenny Root6c4d9042010-11-19 12:48:05 -08004576 public void setPackageObbPaths(String packageName, String[] paths) {
Kenny Root93565c4b2010-06-18 15:46:06 -07004577 if (DEBUG_OBB)
Kenny Root6c4d9042010-11-19 12:48:05 -08004578 Log.v(TAG, "Setting .obb paths for " + packageName + " to: " + Arrays.toString(paths));
4579 final int uid = Binder.getCallingUid();
4580 final int permission = mContext.checkCallingPermission(
4581 android.Manifest.permission.INSTALL_PACKAGES);
4582 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
4583 if (!allowedByPermission) {
4584 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4585 + Binder.getCallingPid());
4586 }
4587 synchronized (mPackages) {
4588 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
4589 if (pkgSetting == null) {
4590 throw new IllegalArgumentException("Unknown package: " + packageName);
4591 }
4592
4593 if (paths != null) {
4594 if (paths.length == 0) {
4595 // Don't bother storing an empty array.
4596 paths = null;
4597 } else {
4598 // Don't allow the caller to manipulate our copy of the
4599 // list.
4600 paths = paths.clone();
4601 }
4602 }
4603
4604 // Only write settings file if the new and old settings are not the
4605 // same.
4606 if (!Arrays.equals(paths, pkgSetting.obbPathStrings)) {
4607 pkgSetting.obbPathStrings = paths;
4608 mSettings.writeLP();
4609 }
4610 }
4611 }
4612
4613 public String[] getPackageObbPaths(String packageName) {
4614 if (DEBUG_OBB)
4615 Log.v(TAG, "Getting .obb paths for " + packageName);
Kenny Root93565c4b2010-06-18 15:46:06 -07004616 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004617 final int permission = mContext.checkCallingPermission(
4618 android.Manifest.permission.INSTALL_PACKAGES);
4619 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004620 synchronized (mPackages) {
Kenny Root6c4d9042010-11-19 12:48:05 -08004621 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
Kenny Root93565c4b2010-06-18 15:46:06 -07004622 if (pkgSetting == null) {
4623 throw new IllegalArgumentException("Unknown package: " + packageName);
4624 }
4625 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4626 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4627 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4628 + pkgSetting.userId);
4629 }
Kenny Root6c4d9042010-11-19 12:48:05 -08004630 return pkgSetting.obbPathStrings;
Kenny Root93565c4b2010-06-18 15:46:06 -07004631 }
4632 }
4633
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004634 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004635 // Queue up an async operation since the package installation may take a little while.
4636 mHandler.post(new Runnable() {
4637 public void run() {
4638 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004639 // Result object to be returned
4640 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004641 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004642 res.uid = -1;
4643 res.pkg = null;
4644 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004645 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004646 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004647 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004648 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004649 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004650 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004651 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004652
4653 // A restore should be performed at this point if (a) the install
4654 // succeeded, (b) the operation is not an update, and (c) the new
4655 // package has a backupAgent defined.
4656 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004657 boolean doRestore = (!update
4658 && res.pkg != null
4659 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004660
4661 // Set up the post-install work request bookkeeping. This will be used
4662 // and cleaned up by the post-install event handling regardless of whether
4663 // there's a restore pass performed. Token values are >= 1.
4664 int token;
4665 if (mNextInstallToken < 0) mNextInstallToken = 1;
4666 token = mNextInstallToken++;
4667
4668 PostInstallData data = new PostInstallData(args, res);
4669 mRunningInstalls.put(token, data);
4670 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4671
4672 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4673 // Pass responsibility to the Backup Manager. It will perform a
4674 // restore if appropriate, then pass responsibility back to the
4675 // Package Manager to run the post-install observer callbacks
4676 // and broadcasts.
4677 IBackupManager bm = IBackupManager.Stub.asInterface(
4678 ServiceManager.getService(Context.BACKUP_SERVICE));
4679 if (bm != null) {
4680 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4681 + " to BM for possible restore");
4682 try {
4683 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4684 } catch (RemoteException e) {
4685 // can't happen; the backup manager is local
4686 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004687 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004688 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004689 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004690 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004691 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004692 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004694 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004695
4696 if (!doRestore) {
4697 // No restore possible, or the Backup Manager was mysteriously not
4698 // available -- just fire the post-install work request directly.
4699 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4700 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4701 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004703 }
4704 });
4705 }
4706
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004707 abstract class HandlerParams {
4708 final static int MAX_RETRIES = 4;
4709 int retry = 0;
4710 final void startCopy() {
4711 try {
4712 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4713 retry++;
4714 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004715 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004716 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4717 handleServiceError();
4718 return;
4719 } else {
4720 handleStartCopy();
4721 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4722 mHandler.sendEmptyMessage(MCS_UNBIND);
4723 }
4724 } catch (RemoteException e) {
4725 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4726 mHandler.sendEmptyMessage(MCS_RECONNECT);
4727 }
4728 handleReturnCode();
4729 }
4730
4731 final void serviceError() {
4732 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4733 handleServiceError();
4734 handleReturnCode();
4735 }
4736 abstract void handleStartCopy() throws RemoteException;
4737 abstract void handleServiceError();
4738 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004739 }
4740
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004741 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004742 final IPackageInstallObserver observer;
4743 int flags;
4744 final Uri packageURI;
4745 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004746 private InstallArgs mArgs;
4747 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004748 InstallParams(Uri packageURI,
4749 IPackageInstallObserver observer, int flags,
4750 String installerPackageName) {
4751 this.packageURI = packageURI;
4752 this.flags = flags;
4753 this.observer = observer;
4754 this.installerPackageName = installerPackageName;
4755 }
4756
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004757 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4758 String packageName = pkgLite.packageName;
4759 int installLocation = pkgLite.installLocation;
4760 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4761 synchronized (mPackages) {
4762 PackageParser.Package pkg = mPackages.get(packageName);
4763 if (pkg != null) {
4764 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4765 // Check for updated system application.
4766 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4767 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004768 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004769 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4770 }
4771 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4772 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004773 if (onSd) {
4774 // Install flag overrides everything.
4775 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4776 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004777 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004778 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4779 // Application explicitly specified internal.
4780 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4781 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4782 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004783 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004784 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004785 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004786 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4787 }
4788 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004789 }
4790 }
4791 } else {
4792 // Invalid install. Return error code
4793 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4794 }
4795 }
4796 }
4797 // All the special cases have been taken care of.
4798 // Return result based on recommended install location.
4799 if (onSd) {
4800 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4801 }
4802 return pkgLite.recommendedInstallLocation;
4803 }
4804
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004805 /*
4806 * Invoke remote method to get package information and install
4807 * location values. Override install location based on default
4808 * policy if needed and then create install arguments based
4809 * on the install location.
4810 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004811 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004812 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004813 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4814 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004815 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4816 if (onInt && onSd) {
4817 // Check if both bits are set.
4818 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4819 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4820 } else if (fwdLocked && onSd) {
4821 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004822 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004823 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004824 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004825 // Remote call to find out default install location
Kenny Root11128572010-10-11 10:51:32 -07004826 final PackageInfoLite pkgLite;
4827 try {
4828 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
4829 Intent.FLAG_GRANT_READ_URI_PERMISSION);
4830 pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
4831 } finally {
4832 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
4833 }
4834
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004835 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004836 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4837 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4838 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4839 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4840 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004841 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4842 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4843 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004844 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4845 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004846 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004847 // Override with defaults if needed.
4848 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004849 if (!onSd && !onInt) {
4850 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004851 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4852 // Set the flag to install on external media.
4853 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004854 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004855 } else {
4856 // Make sure the flag for installing on external
4857 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004858 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004859 flags &= ~PackageManager.INSTALL_EXTERNAL;
4860 }
4861 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004862 }
4863 }
4864 // Create the file args now.
4865 mArgs = createInstallArgs(this);
4866 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4867 // Create copy only if we are not in an erroneous state.
4868 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004869 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004870 }
4871 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004872 }
4873
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004874 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004875 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004876 // If mArgs is null, then MCS couldn't be reached. When it
4877 // reconnects, it will try again to install. At that point, this
4878 // will succeed.
4879 if (mArgs != null) {
4880 processPendingInstall(mArgs, mRet);
4881 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004882 }
4883
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004884 @Override
4885 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004886 mArgs = createInstallArgs(this);
4887 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004888 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004889 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004890
4891 /*
4892 * Utility class used in movePackage api.
4893 * srcArgs and targetArgs are not set for invalid flags and make
4894 * sure to do null checks when invoking methods on them.
4895 * We probably want to return ErrorPrams for both failed installs
4896 * and moves.
4897 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004898 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004899 final IPackageMoveObserver observer;
4900 final int flags;
4901 final String packageName;
4902 final InstallArgs srcArgs;
4903 final InstallArgs targetArgs;
4904 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004905
4906 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4907 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004908 this.srcArgs = srcArgs;
4909 this.observer = observer;
4910 this.flags = flags;
4911 this.packageName = packageName;
4912 if (srcArgs != null) {
4913 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004914 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004915 } else {
4916 targetArgs = null;
4917 }
4918 }
4919
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004920 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004921 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4922 // Check for storage space on target medium
4923 if (!targetArgs.checkFreeStorage(mContainerService)) {
4924 Log.w(TAG, "Insufficient storage to install");
4925 return;
4926 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004927 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004928 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004929 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004930 if (DEBUG_SD_INSTALL) {
4931 StringBuilder builder = new StringBuilder();
4932 if (srcArgs != null) {
4933 builder.append("src: ");
4934 builder.append(srcArgs.getCodePath());
4935 }
4936 if (targetArgs != null) {
4937 builder.append(" target : ");
4938 builder.append(targetArgs.getCodePath());
4939 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004940 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004941 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004942 }
4943
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004944 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004945 void handleReturnCode() {
4946 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004947 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4948 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4949 currentStatus = PackageManager.MOVE_SUCCEEDED;
4950 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4951 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4952 }
4953 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004954 }
4955
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004956 @Override
4957 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004958 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004959 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004960 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004961
4962 private InstallArgs createInstallArgs(InstallParams params) {
4963 if (installOnSd(params.flags)) {
4964 return new SdInstallArgs(params);
4965 } else {
4966 return new FileInstallArgs(params);
4967 }
4968 }
4969
Kenny Root85387d72010-08-26 10:13:11 -07004970 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
4971 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004972 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07004973 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004974 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004975 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004976 }
4977 }
4978
Kenny Root85387d72010-08-26 10:13:11 -07004979 // Used by package mover
4980 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004981 if (installOnSd(flags)) {
4982 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4983 return new SdInstallArgs(packageURI, cid);
4984 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004985 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004986 }
4987 }
4988
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004989 static abstract class InstallArgs {
4990 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004991 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004992 final int flags;
4993 final Uri packageURI;
4994 final String installerPackageName;
4995
4996 InstallArgs(Uri packageURI,
4997 IPackageInstallObserver observer, int flags,
4998 String installerPackageName) {
4999 this.packageURI = packageURI;
5000 this.flags = flags;
5001 this.observer = observer;
5002 this.installerPackageName = installerPackageName;
5003 }
5004
5005 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005006 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005007 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005008 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005009 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005010 abstract String getCodePath();
5011 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07005012 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005013 // Need installer lock especially for dex file removal.
5014 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005015 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005016 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005017 }
5018
5019 class FileInstallArgs extends InstallArgs {
5020 File installDir;
5021 String codeFileName;
5022 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07005023 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005024 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005025
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005026 FileInstallArgs(InstallParams params) {
5027 super(params.packageURI, params.observer,
5028 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005029 }
5030
Kenny Root85387d72010-08-26 10:13:11 -07005031 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005032 super(null, null, 0, null);
5033 File codeFile = new File(fullCodePath);
5034 installDir = codeFile.getParentFile();
5035 codeFileName = fullCodePath;
5036 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07005037 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005038 }
5039
Kenny Root85387d72010-08-26 10:13:11 -07005040 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005041 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07005042 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005043 String apkName = getNextCodePath(null, pkgName, ".apk");
5044 codeFileName = new File(installDir, apkName + ".apk").getPath();
5045 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07005046 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005047 }
5048
Kenny Root11128572010-10-11 10:51:32 -07005049 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5050 try {
5051 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5052 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5053 return imcs.checkFreeStorage(false, packageURI);
5054 } finally {
5055 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5056 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005057 }
5058
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005059 String getCodePath() {
5060 return codeFileName;
5061 }
5062
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005063 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07005064 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005065 codeFileName = createTempPackageFile(installDir).getPath();
5066 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005067 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005068 }
5069
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005070 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005071 if (temp) {
5072 // Generate temp file name
5073 createCopyFile();
5074 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005075 // Get a ParcelFileDescriptor to write to the output file
5076 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005077 if (!created) {
5078 try {
5079 codeFile.createNewFile();
5080 // Set permissions
5081 if (!setPermissions()) {
5082 // Failed setting permissions.
5083 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5084 }
5085 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005086 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005087 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5088 }
5089 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005090 ParcelFileDescriptor out = null;
5091 try {
Kenny Root85387d72010-08-26 10:13:11 -07005092 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005093 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005094 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005095 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5096 }
5097 // Copy the resource now
5098 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5099 try {
Kenny Root11128572010-10-11 10:51:32 -07005100 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5101 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005102 if (imcs.copyResource(packageURI, out)) {
5103 ret = PackageManager.INSTALL_SUCCEEDED;
5104 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005105 } finally {
5106 try { if (out != null) out.close(); } catch (IOException e) {}
Kenny Root11128572010-10-11 10:51:32 -07005107 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005108 }
Kenny Root85387d72010-08-26 10:13:11 -07005109
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005110 return ret;
5111 }
5112
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005113 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005114 if (status != PackageManager.INSTALL_SUCCEEDED) {
5115 cleanUp();
5116 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005117 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005118 }
5119
5120 boolean doRename(int status, final String pkgName, String oldCodePath) {
5121 if (status != PackageManager.INSTALL_SUCCEEDED) {
5122 cleanUp();
5123 return false;
5124 } else {
5125 // Rename based on packageName
5126 File codeFile = new File(getCodePath());
5127 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5128 File desFile = new File(installDir, apkName + ".apk");
5129 if (!codeFile.renameTo(desFile)) {
5130 return false;
5131 }
5132 // Reset paths since the file has been renamed.
5133 codeFileName = desFile.getPath();
5134 resourceFileName = getResourcePathFromCodePath();
5135 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005136 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005137 // Failed setting permissions.
5138 return false;
5139 }
5140 return true;
5141 }
5142 }
5143
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005144 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005145 if (status != PackageManager.INSTALL_SUCCEEDED) {
5146 cleanUp();
5147 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005148 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005149 }
5150
5151 String getResourcePath() {
5152 return resourceFileName;
5153 }
5154
5155 String getResourcePathFromCodePath() {
5156 String codePath = getCodePath();
5157 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5158 String apkNameOnly = getApkName(codePath);
5159 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5160 } else {
5161 return codePath;
5162 }
5163 }
5164
Kenny Root85387d72010-08-26 10:13:11 -07005165 @Override
5166 String getNativeLibraryPath() {
5167 return libraryPath;
5168 }
5169
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005170 private boolean cleanUp() {
5171 boolean ret = true;
5172 String sourceDir = getCodePath();
5173 String publicSourceDir = getResourcePath();
5174 if (sourceDir != null) {
5175 File sourceFile = new File(sourceDir);
5176 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005177 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005178 ret = false;
5179 }
5180 // Delete application's code and resources
5181 sourceFile.delete();
5182 }
5183 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5184 final File publicSourceFile = new File(publicSourceDir);
5185 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005186 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005187 }
5188 if (publicSourceFile.exists()) {
5189 publicSourceFile.delete();
5190 }
5191 }
5192 return ret;
5193 }
5194
5195 void cleanUpResourcesLI() {
5196 String sourceDir = getCodePath();
5197 if (cleanUp() && mInstaller != null) {
5198 int retCode = mInstaller.rmdex(sourceDir);
5199 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005200 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005201 + " at location "
5202 + sourceDir + ", retcode=" + retCode);
5203 // we don't consider this to be a failure of the core package deletion
5204 }
5205 }
5206 }
5207
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005208 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005209 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005210 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005211 final int filePermissions =
5212 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5213 |FileUtils.S_IROTH;
5214 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5215 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005216 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005217 getCodePath()
5218 + ". The return code was: " + retCode);
5219 // TODO Define new internal error
5220 return false;
5221 }
5222 return true;
5223 }
5224 return true;
5225 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005226
5227 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005228 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005229 cleanUpResourcesLI();
5230 return true;
5231 }
Kenny Root85387d72010-08-26 10:13:11 -07005232
5233 private boolean isFwdLocked() {
5234 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5235 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005236 }
5237
5238 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005239 static final String RES_FILE_NAME = "pkg.apk";
5240
Kenny Root85387d72010-08-26 10:13:11 -07005241 String cid;
5242 String packagePath;
5243 String libraryPath;
5244
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005245 SdInstallArgs(InstallParams params) {
5246 super(params.packageURI, params.observer,
5247 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005248 }
5249
Kenny Root85387d72010-08-26 10:13:11 -07005250 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005251 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005252 // Extract cid from fullCodePath
5253 int eidx = fullCodePath.lastIndexOf("/");
5254 String subStr1 = fullCodePath.substring(0, eidx);
5255 int sidx = subStr1.lastIndexOf("/");
5256 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005257 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005258 }
5259
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005260 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005261 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5262 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005263 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005264 }
5265
5266 SdInstallArgs(Uri packageURI, String cid) {
5267 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005268 this.cid = cid;
5269 }
5270
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005271 void createCopyFile() {
5272 cid = getTempContainerId();
5273 }
5274
Kenny Root11128572010-10-11 10:51:32 -07005275 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5276 try {
5277 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5278 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5279 return imcs.checkFreeStorage(true, packageURI);
5280 } finally {
5281 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5282 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005283 }
5284
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005285 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005286 if (temp) {
5287 createCopyFile();
5288 }
Kenny Root11128572010-10-11 10:51:32 -07005289
5290 final String newCachePath;
5291 try {
5292 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5293 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5294 newCachePath = imcs.copyResourceToContainer(packageURI, cid,
5295 getEncryptKey(), RES_FILE_NAME);
5296 } finally {
5297 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5298 }
5299
Kenny Root85387d72010-08-26 10:13:11 -07005300 if (newCachePath != null) {
5301 setCachePath(newCachePath);
5302 return PackageManager.INSTALL_SUCCEEDED;
5303 } else {
5304 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5305 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005306 }
5307
5308 @Override
5309 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005310 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005311 }
5312
5313 @Override
5314 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005315 return packagePath;
5316 }
5317
5318 @Override
5319 String getNativeLibraryPath() {
5320 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005321 }
5322
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005323 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005324 if (status != PackageManager.INSTALL_SUCCEEDED) {
5325 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005326 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005327 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005328 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005329 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005330 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5331 Process.SYSTEM_UID);
5332 if (newCachePath != null) {
5333 setCachePath(newCachePath);
5334 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005335 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5336 }
5337 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005338 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005339 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005340 }
5341
5342 boolean doRename(int status, final String pkgName,
5343 String oldCodePath) {
5344 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005345 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005346 if (PackageHelper.isContainerMounted(cid)) {
5347 // Unmount the container
5348 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005349 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005350 return false;
5351 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005352 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005353 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005354 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5355 " which might be stale. Will try to clean up.");
5356 // Clean up the stale container and proceed to recreate.
5357 if (!PackageHelper.destroySdDir(newCacheId)) {
5358 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5359 return false;
5360 }
5361 // Successfully cleaned up stale container. Try to rename again.
5362 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5363 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5364 + " inspite of cleaning it up.");
5365 return false;
5366 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005367 }
5368 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005369 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005370 newCachePath = PackageHelper.mountSdDir(newCacheId,
5371 getEncryptKey(), Process.SYSTEM_UID);
5372 } else {
5373 newCachePath = PackageHelper.getSdDir(newCacheId);
5374 }
5375 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005376 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005377 return false;
5378 }
5379 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005380 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005381 " at new path: " + newCachePath);
5382 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005383 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005384 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005385 }
5386
Kenny Root85387d72010-08-26 10:13:11 -07005387 private void setCachePath(String newCachePath) {
5388 File cachePath = new File(newCachePath);
5389 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5390 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5391 }
5392
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005393 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005394 if (status != PackageManager.INSTALL_SUCCEEDED) {
5395 cleanUp();
5396 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005397 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005398 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005399 PackageHelper.mountSdDir(cid,
5400 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005401 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005402 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005403 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005404 }
5405
5406 private void cleanUp() {
5407 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005408 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005409 }
5410
5411 void cleanUpResourcesLI() {
5412 String sourceFile = getCodePath();
5413 // Remove dex file
5414 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005415 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005416 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005417 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005418 + " at location "
5419 + sourceFile.toString() + ", retcode=" + retCode);
5420 // we don't consider this to be a failure of the core package deletion
5421 }
5422 }
5423 cleanUp();
5424 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005425
5426 boolean matchContainer(String app) {
5427 if (cid.startsWith(app)) {
5428 return true;
5429 }
5430 return false;
5431 }
5432
5433 String getPackageName() {
5434 int idx = cid.lastIndexOf("-");
5435 if (idx == -1) {
5436 return cid;
5437 }
5438 return cid.substring(0, idx);
5439 }
5440
5441 boolean doPostDeleteLI(boolean delete) {
5442 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005443 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005444 if (mounted) {
5445 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005446 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005447 }
5448 if (ret && delete) {
5449 cleanUpResourcesLI();
5450 }
5451 return ret;
5452 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005453 };
5454
5455 // Utility method used to create code paths based on package name and available index.
5456 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5457 String idxStr = "";
5458 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005459 // Fall back to default value of idx=1 if prefix is not
5460 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005461 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005462 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005463 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005464 if (subStr.endsWith(suffix)) {
5465 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005466 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005467 // If oldCodePath already contains prefix find out the
5468 // ending index to either increment or decrement.
5469 int sidx = subStr.lastIndexOf(prefix);
5470 if (sidx != -1) {
5471 subStr = subStr.substring(sidx + prefix.length());
5472 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005473 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5474 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005475 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005476 try {
5477 idx = Integer.parseInt(subStr);
5478 if (idx <= 1) {
5479 idx++;
5480 } else {
5481 idx--;
5482 }
5483 } catch(NumberFormatException e) {
5484 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005485 }
5486 }
5487 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005488 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005489 return prefix + idxStr;
5490 }
5491
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005492 // Utility method used to ignore ADD/REMOVE events
5493 // by directory observer.
5494 private static boolean ignoreCodePath(String fullPathStr) {
5495 String apkName = getApkName(fullPathStr);
5496 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5497 if (idx != -1 && ((idx+1) < apkName.length())) {
5498 // Make sure the package ends with a numeral
5499 String version = apkName.substring(idx+1);
5500 try {
5501 Integer.parseInt(version);
5502 return true;
5503 } catch (NumberFormatException e) {}
5504 }
5505 return false;
5506 }
5507
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005508 // Utility method that returns the relative package path with respect
5509 // to the installation directory. Like say for /data/data/com.test-1.apk
5510 // string com.test-1 is returned.
5511 static String getApkName(String codePath) {
5512 if (codePath == null) {
5513 return null;
5514 }
5515 int sidx = codePath.lastIndexOf("/");
5516 int eidx = codePath.lastIndexOf(".");
5517 if (eidx == -1) {
5518 eidx = codePath.length();
5519 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005520 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005521 return null;
5522 }
5523 return codePath.substring(sidx+1, eidx);
5524 }
5525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005526 class PackageInstalledInfo {
5527 String name;
5528 int uid;
5529 PackageParser.Package pkg;
5530 int returnCode;
5531 PackageRemovedInfo removedInfo;
5532 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005534 /*
5535 * Install a non-existing package.
5536 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005537 private void installNewPackageLI(PackageParser.Package pkg,
5538 int parseFlags,
5539 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005540 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005541 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005542 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005543
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005544 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005545 res.name = pkgName;
5546 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005547 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5548 // A package with the same name is already installed, though
5549 // it has been renamed to an older name. The package we
5550 // are trying to install should be installed as an update to
5551 // the existing one, but that has not been requested, so bail.
5552 Slog.w(TAG, "Attempt to re-install " + pkgName
5553 + " without first uninstalling package running as "
5554 + mSettings.mRenamedPackages.get(pkgName));
5555 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5556 return;
5557 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005558 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005559 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005560 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005561 + " without first uninstalling.");
5562 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5563 return;
5564 }
5565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005566 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005567 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
5568 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005569 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005570 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005571 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5572 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5573 }
5574 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005575 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005576 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 res);
5578 // delete the partially installed application. the data directory will have to be
5579 // restored if it was already existing
5580 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5581 // remove package from internal structures. Note that we want deletePackageX to
5582 // delete the package data and cache directories that it created in
5583 // scanPackageLocked, unless those directories existed before we even tried to
5584 // install.
5585 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005586 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005587 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005588 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005589 }
5590 }
5591 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005592
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005593 private void replacePackageLI(PackageParser.Package pkg,
5594 int parseFlags,
5595 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005596 String installerPackageName, PackageInstalledInfo res) {
5597
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005598 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005599 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005600 // First find the old package info and check signatures
5601 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005602 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005603 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005604 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005605 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5606 return;
5607 }
5608 }
Kenny Root85387d72010-08-26 10:13:11 -07005609 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005610 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005611 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005612 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005613 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005614 }
5615 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005617 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005618 PackageParser.Package pkg,
5619 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005620 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005621 PackageParser.Package newPackage = null;
5622 String pkgName = deletedPackage.packageName;
5623 boolean deletedPkg = true;
5624 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005625
Jacek Surazski65e13172009-04-28 15:26:38 +02005626 String oldInstallerPackageName = null;
5627 synchronized (mPackages) {
5628 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5629 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005630
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005631 long origUpdateTime;
5632 if (pkg.mExtras != null) {
5633 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
5634 } else {
5635 origUpdateTime = 0;
5636 }
5637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005638 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005639 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005640 res.removedInfo, true)) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005641 // If the existing package wasn't successfully deleted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5643 deletedPkg = false;
5644 } else {
5645 // Successfully deleted the old package. Now proceed with re-installation
5646 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005647 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
5648 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005650 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5652 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005653 }
5654 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005655 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005656 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005657 res);
5658 updatedSettings = true;
5659 }
5660 }
5661
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005662 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005663 // remove package from internal structures. Note that we want deletePackageX to
5664 // delete the package data and cache directories that it created in
5665 // scanPackageLocked, unless those directories existed before we even tried to
5666 // install.
5667 if(updatedSettings) {
5668 deletePackageLI(
5669 pkgName, true,
5670 PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005671 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005672 }
5673 // Since we failed to install the new package we need to restore the old
5674 // package that we deleted.
5675 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005676 File restoreFile = new File(deletedPackage.mPath);
5677 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005678 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005679 return;
5680 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005681 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005682 boolean oldOnSd = isExternal(deletedPackage);
5683 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5684 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5685 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005686 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
5687 | SCAN_UPDATE_TIME;
5688 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
5689 origUpdateTime) == null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005690 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5691 return;
5692 }
5693 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005694 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005695 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005696 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005697 mSettings.writeLP();
5698 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005699 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005700 }
5701 }
5702 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005704 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005705 PackageParser.Package pkg,
5706 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005707 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005708 PackageParser.Package newPackage = null;
5709 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005710 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005711 PackageParser.PARSE_IS_SYSTEM;
5712 String packageName = deletedPackage.packageName;
5713 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5714 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005715 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005716 return;
5717 }
5718 PackageParser.Package oldPkg;
5719 PackageSetting oldPkgSetting;
5720 synchronized (mPackages) {
5721 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005722 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005723 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5724 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005725 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 return;
5727 }
5728 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08005729
5730 killApplication(packageName, oldPkg.applicationInfo.uid);
5731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005732 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5733 res.removedInfo.removedPackage = packageName;
5734 // Remove existing system package
5735 removePackageLI(oldPkg, true);
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08005736 synchronized (mPackages) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08005737 if (!mSettings.disableSystemPackageLP(packageName) && deletedPackage != null) {
5738 // We didn't need to disable the .apk as a current system package,
5739 // which means we are replacing another update that is already
5740 // installed. We need to make sure to delete the older one's .apk.
5741 res.removedInfo.args = createInstallArgs(isExternal(pkg)
5742 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL,
5743 deletedPackage.applicationInfo.sourceDir,
5744 deletedPackage.applicationInfo.publicSourceDir,
5745 deletedPackage.applicationInfo.nativeLibraryDir);
5746 } else {
5747 res.removedInfo.args = null;
5748 }
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08005749 }
5750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005751 // Successfully disabled the old package. Now proceed with re-installation
5752 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5753 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005754 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005755 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005756 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005757 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5758 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5759 }
5760 } else {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005761 if (newPackage.mExtras != null) {
5762 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
5763 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
5764 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
5765 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005766 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005767 updatedSettings = true;
5768 }
5769
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005770 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005771 // Re installation failed. Restore old information
5772 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005773 if (newPackage != null) {
5774 removePackageLI(newPackage, true);
5775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005776 // Add back the old system package
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005777 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005778 // Restore the old system information in Settings
5779 synchronized(mPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005780 if (updatedSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005781 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005782 mSettings.setInstallerPackageName(packageName,
5783 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005784 }
5785 mSettings.writeLP();
5786 }
5787 }
5788 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005789
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005790 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005791 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005792 int retCode;
5793 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5794 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5795 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005796 if (mNoDexOpt) {
5797 /*
5798 * If we're in an engineering build, programs are lazily run
5799 * through dexopt. If the .dex file doesn't exist yet, it
5800 * will be created when the program is run next.
5801 */
5802 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5803 } else {
5804 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5805 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5806 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005807 }
5808 }
5809 return PackageManager.INSTALL_SUCCEEDED;
5810 }
5811
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005812 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005813 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005814 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005815 synchronized (mPackages) {
5816 //write settings. the installStatus will be incomplete at this stage.
5817 //note that the new package setting would have already been
5818 //added to mPackages. It hasn't been persisted yet.
5819 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5820 mSettings.writeLP();
5821 }
5822
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005823 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005824 != PackageManager.INSTALL_SUCCEEDED) {
5825 // Discontinue if moving dex files failed.
5826 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005827 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005828 if((res.returnCode = setPermissionsLI(newPackage))
5829 != PackageManager.INSTALL_SUCCEEDED) {
5830 if (mInstaller != null) {
5831 mInstaller.rmdex(newPackage.mScanPath);
5832 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005833 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005834 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005835 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005837 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005838 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005839 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005840 res.name = pkgName;
5841 res.uid = newPackage.applicationInfo.uid;
5842 res.pkg = newPackage;
5843 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005844 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5846 //to update install status
5847 mSettings.writeLP();
5848 }
5849 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005850
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005851 private void installPackageLI(InstallArgs args,
5852 boolean newInstall, PackageInstalledInfo res) {
5853 int pFlags = args.flags;
5854 String installerPackageName = args.installerPackageName;
5855 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005856 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005857 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005858 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005859 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005860 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005861 // Result object to be returned
5862 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5863
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005864 // Retrieve PackageSettings and parse package
5865 int parseFlags = PackageParser.PARSE_CHATTY |
5866 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5867 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5868 parseFlags |= mDefParseFlags;
5869 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5870 pp.setSeparateProcesses(mSeparateProcesses);
5871 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5872 null, mMetrics, parseFlags);
5873 if (pkg == null) {
5874 res.returnCode = pp.getParseError();
5875 return;
5876 }
5877 String pkgName = res.name = pkg.packageName;
5878 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5879 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5880 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5881 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005882 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005883 }
5884 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5885 res.returnCode = pp.getParseError();
5886 return;
5887 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005888 // Get rid of all references to package scan path via parser.
5889 pp = null;
5890 String oldCodePath = null;
5891 boolean systemApp = false;
5892 synchronized (mPackages) {
5893 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005894 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5895 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005896 if (pkg.mOriginalPackages != null
5897 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005898 && mPackages.containsKey(oldName)) {
5899 // This package is derived from an original package,
5900 // and this device has been updating from that original
5901 // name. We must continue using the original name, so
5902 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005903 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005904 pkgName = pkg.packageName;
5905 replace = true;
5906 } else if (mPackages.containsKey(pkgName)) {
5907 // This package, under its official name, already exists
5908 // on the device; we should replace it.
5909 replace = true;
5910 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005911 }
5912 PackageSetting ps = mSettings.mPackages.get(pkgName);
5913 if (ps != null) {
5914 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5915 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5916 systemApp = (ps.pkg.applicationInfo.flags &
5917 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005918 }
5919 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005920 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005921
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005922 if (systemApp && onSd) {
5923 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005924 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005925 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5926 return;
5927 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005928
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005929 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5930 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5931 return;
5932 }
5933 // Set application objects path explicitly after the rename
5934 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005935 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005936 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005937 replacePackageLI(pkg, parseFlags, scanMode,
5938 installerPackageName, res);
5939 } else {
5940 installNewPackageLI(pkg, parseFlags, scanMode,
5941 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942 }
5943 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005944
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005945 private int setPermissionsLI(PackageParser.Package newPackage) {
5946 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005947 int retCode = 0;
5948 // TODO Gross hack but fix later. Ideally move this to be a post installation
5949 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005950 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005951 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005952 try {
5953 extractPublicFiles(newPackage, destResourceFile);
5954 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005955 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 -08005956 " forward-locked app.");
5957 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5958 } finally {
5959 //TODO clean up the extracted public files
5960 }
5961 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005962 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963 newPackage.applicationInfo.uid);
5964 } else {
5965 final int filePermissions =
5966 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005967 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005968 newPackage.applicationInfo.uid);
5969 }
5970 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005971 // The permissions on the resource file was set when it was copied for
5972 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005973 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005975 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005976 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005977 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005978 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005979 // TODO Define new internal error
5980 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005981 }
5982 return PackageManager.INSTALL_SUCCEEDED;
5983 }
5984
Kenny Root85387d72010-08-26 10:13:11 -07005985 private static boolean isForwardLocked(PackageParser.Package pkg) {
5986 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005987 }
5988
Kenny Root85387d72010-08-26 10:13:11 -07005989 private static boolean isExternal(PackageParser.Package pkg) {
5990 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
5991 }
5992
5993 private static boolean isSystemApp(PackageParser.Package pkg) {
5994 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5995 }
5996
Kenny Root1c6e7642011-01-10 13:48:15 -08005997 private static boolean isSystemApp(ApplicationInfo info) {
5998 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5999 }
6000
Kenny Root85387d72010-08-26 10:13:11 -07006001 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
6002 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07006003 }
6004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006005 private void extractPublicFiles(PackageParser.Package newPackage,
6006 File publicZipFile) throws IOException {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006007 final FileOutputStream fstr = new FileOutputStream(publicZipFile);
6008 final ZipOutputStream publicZipOutStream = new ZipOutputStream(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 final ZipFile privateZip = new ZipFile(newPackage.mPath);
6010
6011 // Copy manifest, resources.arsc and res directory to public zip
6012
6013 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
6014 while (privateZipEntries.hasMoreElements()) {
6015 final ZipEntry zipEntry = privateZipEntries.nextElement();
6016 final String zipEntryName = zipEntry.getName();
6017 if ("AndroidManifest.xml".equals(zipEntryName)
6018 || "resources.arsc".equals(zipEntryName)
6019 || zipEntryName.startsWith("res/")) {
6020 try {
6021 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
6022 } catch (IOException e) {
6023 try {
6024 publicZipOutStream.close();
6025 throw e;
6026 } finally {
6027 publicZipFile.delete();
6028 }
6029 }
6030 }
6031 }
6032
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006033 publicZipOutStream.finish();
6034 publicZipOutStream.flush();
6035 FileUtils.sync(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006036 publicZipOutStream.close();
6037 FileUtils.setPermissions(
6038 publicZipFile.getAbsolutePath(),
6039 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
6040 -1, -1);
6041 }
6042
6043 private static void copyZipEntry(ZipEntry zipEntry,
6044 ZipFile inZipFile,
6045 ZipOutputStream outZipStream) throws IOException {
6046 byte[] buffer = new byte[4096];
6047 int num;
6048
6049 ZipEntry newEntry;
6050 if (zipEntry.getMethod() == ZipEntry.STORED) {
6051 // Preserve the STORED method of the input entry.
6052 newEntry = new ZipEntry(zipEntry);
6053 } else {
6054 // Create a new entry so that the compressed len is recomputed.
6055 newEntry = new ZipEntry(zipEntry.getName());
6056 }
6057 outZipStream.putNextEntry(newEntry);
6058
6059 InputStream data = inZipFile.getInputStream(zipEntry);
6060 while ((num = data.read(buffer)) > 0) {
6061 outZipStream.write(buffer, 0, num);
6062 }
6063 outZipStream.flush();
6064 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 private void deleteTempPackageFiles() {
6067 FilenameFilter filter = new FilenameFilter() {
6068 public boolean accept(File dir, String name) {
6069 return name.startsWith("vmdl") && name.endsWith(".tmp");
6070 }
6071 };
6072 String tmpFilesList[] = mAppInstallDir.list(filter);
6073 if(tmpFilesList == null) {
6074 return;
6075 }
6076 for(int i = 0; i < tmpFilesList.length; i++) {
6077 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
6078 tmpFile.delete();
6079 }
6080 }
6081
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006082 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006083 File tmpPackageFile;
6084 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006085 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006086 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006087 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 return null;
6089 }
6090 try {
6091 FileUtils.setPermissions(
6092 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6093 -1, -1);
6094 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006095 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006096 return null;
6097 }
6098 return tmpPackageFile;
6099 }
6100
6101 public void deletePackage(final String packageName,
6102 final IPackageDeleteObserver observer,
6103 final int flags) {
6104 mContext.enforceCallingOrSelfPermission(
6105 android.Manifest.permission.DELETE_PACKAGES, null);
6106 // Queue up an async operation since the package deletion may take a little while.
6107 mHandler.post(new Runnable() {
6108 public void run() {
6109 mHandler.removeCallbacks(this);
6110 final boolean succeded = deletePackageX(packageName, true, true, flags);
6111 if (observer != null) {
6112 try {
6113 observer.packageDeleted(succeded);
6114 } catch (RemoteException e) {
6115 Log.i(TAG, "Observer no longer exists.");
6116 } //end catch
6117 } //end if
6118 } //end run
6119 });
6120 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006122 /**
6123 * This method is an internal method that could be get invoked either
6124 * to delete an installed package or to clean up a failed installation.
6125 * After deleting an installed package, a broadcast is sent to notify any
6126 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006127 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006128 * installation wouldn't have sent the initial broadcast either
6129 * The key steps in deleting a package are
6130 * deleting the package information in internal structures like mPackages,
6131 * deleting the packages base directories through installd
6132 * updating mSettings to reflect current status
6133 * persisting settings for later use
6134 * sending a broadcast if necessary
6135 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006136 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6137 boolean deleteCodeAndResources, int flags) {
6138 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006139 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006140
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006141 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6142 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6143 try {
6144 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006145 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006146 return false;
6147 }
6148 } catch (RemoteException e) {
6149 }
6150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006151 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006152 res = deletePackageLI(packageName, deleteCodeAndResources,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006153 flags | REMOVE_CHATTY, info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006154 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006156 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006157 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006158 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006159
6160 // If the removed package was a system update, the old system packaged
6161 // was re-enabled; we need to broadcast this information
6162 if (systemUpdate) {
6163 Bundle extras = new Bundle(1);
6164 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6165 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6166
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006167 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6168 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006170 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006171 // Force a gc here.
6172 Runtime.getRuntime().gc();
6173 // Delete the resources here after sending the broadcast to let
6174 // other processes clean up before deleting resources.
6175 if (info.args != null) {
6176 synchronized (mInstallLock) {
6177 info.args.doPostDeleteLI(deleteCodeAndResources);
6178 }
6179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006180 return res;
6181 }
6182
6183 static class PackageRemovedInfo {
6184 String removedPackage;
6185 int uid = -1;
6186 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006187 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006188 // Clean up resources deleted packages.
6189 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006190
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006191 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 Bundle extras = new Bundle(1);
6193 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6194 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6195 if (replacing) {
6196 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6197 }
6198 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006199 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006200 }
6201 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006202 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203 }
6204 }
6205 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006207 /*
6208 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6209 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006210 * 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 -08006211 * delete a partially installed application.
6212 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006213 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006214 int flags, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006216 if (outInfo != null) {
6217 outInfo.removedPackage = packageName;
6218 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006219 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006220 // Retrieve object to delete permissions for shared user later on
6221 PackageSetting deletedPs;
6222 synchronized (mPackages) {
6223 deletedPs = mSettings.mPackages.get(packageName);
6224 }
6225 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006226 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006227 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006228 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006229 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006230 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006231 + packageName + ", retcode=" + retCode);
6232 // we don't consider this to be a failure of the core package deletion
6233 }
6234 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006235 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006236 PackageParser.Package pkg = mPackages.get(packageName);
6237 File dataDir = new File(pkg.applicationInfo.dataDir);
6238 dataDir.delete();
6239 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006240 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006241 }
6242 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006243 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006244 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6245 if (outInfo != null) {
6246 outInfo.removedUid = mSettings.removePackageLP(packageName);
6247 }
6248 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006249 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006250 if (deletedPs.sharedUser != null) {
6251 // remove permissions associated with package
6252 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6253 }
6254 }
6255 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006256 // remove from preferred activities.
6257 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6258 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6259 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6260 removed.add(pa);
6261 }
6262 }
6263 for (PreferredActivity pa : removed) {
6264 mSettings.mPreferredActivities.removeFilter(pa);
6265 }
6266 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006267 if (writeSettings) {
6268 // Save settings now
6269 mSettings.writeLP();
6270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 }
6272 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 /*
6275 * Tries to delete system package.
6276 */
6277 private boolean deleteSystemPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006278 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 ApplicationInfo applicationInfo = p.applicationInfo;
6280 //applicable for non-partially installed applications only
6281 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006282 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006283 return false;
6284 }
6285 PackageSetting ps = null;
6286 // Confirm if the system package has been updated
6287 // An updated system app can be deleted. This will also have to restore
6288 // the system pkg from system partition
6289 synchronized (mPackages) {
6290 ps = mSettings.getDisabledSystemPkg(p.packageName);
6291 }
6292 if (ps == null) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08006293 Slog.w(TAG, "Attempt to delete unknown system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006294 return false;
6295 } else {
6296 Log.i(TAG, "Deleting system pkg from data partition");
6297 }
6298 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006299 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006300 if (ps.versionCode < p.mVersionCode) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08006301 // Delete data for downgrades
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006302 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006303 } else {
6304 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006305 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006306 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08006307 boolean ret = deleteInstalledPackageLI(p, true, flags, outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006308 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006309 if (!ret) {
6310 return false;
6311 }
6312 synchronized (mPackages) {
6313 // Reinstate the old system package
6314 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07006315 // Remove any native libraries from the upgraded package.
6316 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006317 }
6318 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006319 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006320 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006321 SCAN_MONITOR | SCAN_NO_PATHS, 0);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006324 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006325 return false;
6326 }
6327 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006328 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006329 if (writeSettings) {
6330 mSettings.writeLP();
6331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 }
6333 return true;
6334 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 private boolean deleteInstalledPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006337 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6338 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006339 ApplicationInfo applicationInfo = p.applicationInfo;
6340 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006341 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006342 return false;
6343 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006344 if (outInfo != null) {
6345 outInfo.uid = applicationInfo.uid;
6346 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006347
6348 // Delete package data from internal structures and also remove data if flag is set
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006349 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006350
6351 // Delete application code and resources
6352 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006353 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006354 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6355 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6356 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6357 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006358 }
6359 return true;
6360 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006362 /*
6363 * This method handles package deletion in general
6364 */
6365 private boolean deletePackageLI(String packageName,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006366 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6367 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006368 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006369 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 return false;
6371 }
6372 PackageParser.Package p;
6373 boolean dataOnly = false;
6374 synchronized (mPackages) {
6375 p = mPackages.get(packageName);
6376 if (p == null) {
6377 //this retrieves partially installed apps
6378 dataOnly = true;
6379 PackageSetting ps = mSettings.mPackages.get(packageName);
6380 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006381 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006382 return false;
6383 }
6384 p = ps.pkg;
6385 }
6386 }
6387 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006388 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006389 return false;
6390 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006392 if (dataOnly) {
6393 // Delete application data first
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006394 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 return true;
6396 }
6397 // At this point the package should have ApplicationInfo associated with it
6398 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006399 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006400 return false;
6401 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006402 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006403 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 Log.i(TAG, "Removing system package:"+p.packageName);
6405 // When an updated system application is deleted we delete the existing resources as well and
6406 // fall back to existing code in system partition
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006407 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006408 } else {
6409 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006410 // Kill application pre-emptively especially for apps on sd.
6411 killApplication(packageName, p.applicationInfo.uid);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006412 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6413 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006414 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006415 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006418 public void clearApplicationUserData(final String packageName,
6419 final IPackageDataObserver observer) {
6420 mContext.enforceCallingOrSelfPermission(
6421 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6422 // Queue up an async operation since the package deletion may take a little while.
6423 mHandler.post(new Runnable() {
6424 public void run() {
6425 mHandler.removeCallbacks(this);
6426 final boolean succeeded;
6427 synchronized (mInstallLock) {
6428 succeeded = clearApplicationUserDataLI(packageName);
6429 }
6430 if (succeeded) {
6431 // invoke DeviceStorageMonitor's update method to clear any notifications
6432 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6433 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6434 if (dsm != null) {
6435 dsm.updateMemory();
6436 }
6437 }
6438 if(observer != null) {
6439 try {
6440 observer.onRemoveCompleted(packageName, succeeded);
6441 } catch (RemoteException e) {
6442 Log.i(TAG, "Observer no longer exists.");
6443 }
6444 } //end if observer
6445 } //end run
6446 });
6447 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006449 private boolean clearApplicationUserDataLI(String packageName) {
6450 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006451 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006452 return false;
6453 }
6454 PackageParser.Package p;
6455 boolean dataOnly = false;
6456 synchronized (mPackages) {
6457 p = mPackages.get(packageName);
6458 if(p == null) {
6459 dataOnly = true;
6460 PackageSetting ps = mSettings.mPackages.get(packageName);
6461 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006462 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006463 return false;
6464 }
6465 p = ps.pkg;
6466 }
6467 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006468 boolean useEncryptedFSDir = false;
6469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006470 if(!dataOnly) {
6471 //need to check this only for fully installed applications
6472 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006473 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006474 return false;
6475 }
6476 final ApplicationInfo applicationInfo = p.applicationInfo;
6477 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006478 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006479 return false;
6480 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006481 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006482 }
6483 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006484 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006485 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006486 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 + packageName);
6488 return false;
6489 }
6490 }
6491 return true;
6492 }
6493
6494 public void deleteApplicationCacheFiles(final String packageName,
6495 final IPackageDataObserver observer) {
6496 mContext.enforceCallingOrSelfPermission(
6497 android.Manifest.permission.DELETE_CACHE_FILES, null);
6498 // Queue up an async operation since the package deletion may take a little while.
6499 mHandler.post(new Runnable() {
6500 public void run() {
6501 mHandler.removeCallbacks(this);
6502 final boolean succeded;
6503 synchronized (mInstallLock) {
6504 succeded = deleteApplicationCacheFilesLI(packageName);
6505 }
6506 if(observer != null) {
6507 try {
6508 observer.onRemoveCompleted(packageName, succeded);
6509 } catch (RemoteException e) {
6510 Log.i(TAG, "Observer no longer exists.");
6511 }
6512 } //end if observer
6513 } //end run
6514 });
6515 }
6516
6517 private boolean deleteApplicationCacheFilesLI(String packageName) {
6518 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006519 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006520 return false;
6521 }
6522 PackageParser.Package p;
6523 synchronized (mPackages) {
6524 p = mPackages.get(packageName);
6525 }
6526 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006527 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006528 return false;
6529 }
6530 final ApplicationInfo applicationInfo = p.applicationInfo;
6531 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006532 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006533 return false;
6534 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006535 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006537 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006538 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006539 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006540 + packageName);
6541 return false;
6542 }
6543 }
6544 return true;
6545 }
6546
6547 public void getPackageSizeInfo(final String packageName,
6548 final IPackageStatsObserver observer) {
6549 mContext.enforceCallingOrSelfPermission(
6550 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6551 // Queue up an async operation since the package deletion may take a little while.
6552 mHandler.post(new Runnable() {
6553 public void run() {
6554 mHandler.removeCallbacks(this);
6555 PackageStats lStats = new PackageStats(packageName);
6556 final boolean succeded;
6557 synchronized (mInstallLock) {
6558 succeded = getPackageSizeInfoLI(packageName, lStats);
6559 }
6560 if(observer != null) {
6561 try {
6562 observer.onGetStatsCompleted(lStats, succeded);
6563 } catch (RemoteException e) {
6564 Log.i(TAG, "Observer no longer exists.");
6565 }
6566 } //end if observer
6567 } //end run
6568 });
6569 }
6570
6571 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6572 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006573 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006574 return false;
6575 }
6576 PackageParser.Package p;
6577 boolean dataOnly = false;
6578 synchronized (mPackages) {
6579 p = mPackages.get(packageName);
6580 if(p == null) {
6581 dataOnly = true;
6582 PackageSetting ps = mSettings.mPackages.get(packageName);
6583 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006584 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006585 return false;
6586 }
6587 p = ps.pkg;
6588 }
6589 }
6590 String publicSrcDir = null;
6591 if(!dataOnly) {
6592 final ApplicationInfo applicationInfo = p.applicationInfo;
6593 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006594 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006595 return false;
6596 }
6597 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6598 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006599 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006600 if (mInstaller != null) {
6601 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006602 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006603 if (res < 0) {
6604 return false;
6605 } else {
6606 return true;
6607 }
6608 }
6609 return true;
6610 }
6611
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006613 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006614 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006615 }
6616
6617 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006618 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006619 }
6620
6621 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006622 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006623 }
6624
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006625 int getUidTargetSdkVersionLockedLP(int uid) {
6626 Object obj = mSettings.getUserIdLP(uid);
6627 if (obj instanceof SharedUserSetting) {
6628 SharedUserSetting sus = (SharedUserSetting)obj;
6629 final int N = sus.packages.size();
6630 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6631 Iterator<PackageSetting> it = sus.packages.iterator();
6632 int i=0;
6633 while (it.hasNext()) {
6634 PackageSetting ps = it.next();
6635 if (ps.pkg != null) {
6636 int v = ps.pkg.applicationInfo.targetSdkVersion;
6637 if (v < vers) vers = v;
6638 }
6639 }
6640 return vers;
6641 } else if (obj instanceof PackageSetting) {
6642 PackageSetting ps = (PackageSetting)obj;
6643 if (ps.pkg != null) {
6644 return ps.pkg.applicationInfo.targetSdkVersion;
6645 }
6646 }
6647 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6648 }
6649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006650 public void addPreferredActivity(IntentFilter filter, int match,
6651 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006652 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006653 if (mContext.checkCallingOrSelfPermission(
6654 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6655 != PackageManager.PERMISSION_GRANTED) {
6656 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6657 < Build.VERSION_CODES.FROYO) {
6658 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6659 + Binder.getCallingUid());
6660 return;
6661 }
6662 mContext.enforceCallingOrSelfPermission(
6663 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6664 }
6665
6666 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6668 mSettings.mPreferredActivities.addFilter(
6669 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006670 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006671 }
6672 }
6673
Satish Sampath8dbe6122009-06-02 23:35:54 +01006674 public void replacePreferredActivity(IntentFilter filter, int match,
6675 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006676 if (filter.countActions() != 1) {
6677 throw new IllegalArgumentException(
6678 "replacePreferredActivity expects filter to have only 1 action.");
6679 }
6680 if (filter.countCategories() != 1) {
6681 throw new IllegalArgumentException(
6682 "replacePreferredActivity expects filter to have only 1 category.");
6683 }
6684 if (filter.countDataAuthorities() != 0
6685 || filter.countDataPaths() != 0
6686 || filter.countDataSchemes() != 0
6687 || filter.countDataTypes() != 0) {
6688 throw new IllegalArgumentException(
6689 "replacePreferredActivity expects filter to have no data authorities, " +
6690 "paths, schemes or types.");
6691 }
6692 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006693 if (mContext.checkCallingOrSelfPermission(
6694 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6695 != PackageManager.PERMISSION_GRANTED) {
6696 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6697 < Build.VERSION_CODES.FROYO) {
6698 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6699 + Binder.getCallingUid());
6700 return;
6701 }
6702 mContext.enforceCallingOrSelfPermission(
6703 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6704 }
6705
Satish Sampath8dbe6122009-06-02 23:35:54 +01006706 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6707 String action = filter.getAction(0);
6708 String category = filter.getCategory(0);
6709 while (it.hasNext()) {
6710 PreferredActivity pa = it.next();
6711 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6712 it.remove();
6713 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6714 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6715 }
6716 }
6717 addPreferredActivity(filter, match, set, activity);
6718 }
6719 }
6720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006721 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006722 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006723 int uid = Binder.getCallingUid();
6724 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006725 if (pkg == null || pkg.applicationInfo.uid != uid) {
6726 if (mContext.checkCallingOrSelfPermission(
6727 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6728 != PackageManager.PERMISSION_GRANTED) {
6729 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6730 < Build.VERSION_CODES.FROYO) {
6731 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6732 + Binder.getCallingUid());
6733 return;
6734 }
6735 mContext.enforceCallingOrSelfPermission(
6736 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6737 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006738 }
6739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006740 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006741 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006742 }
6743 }
6744 }
6745
6746 boolean clearPackagePreferredActivitiesLP(String packageName) {
6747 boolean changed = false;
6748 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6749 while (it.hasNext()) {
6750 PreferredActivity pa = it.next();
6751 if (pa.mActivity.getPackageName().equals(packageName)) {
6752 it.remove();
6753 changed = true;
6754 }
6755 }
6756 return changed;
6757 }
6758
6759 public int getPreferredActivities(List<IntentFilter> outFilters,
6760 List<ComponentName> outActivities, String packageName) {
6761
6762 int num = 0;
6763 synchronized (mPackages) {
6764 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6765 while (it.hasNext()) {
6766 PreferredActivity pa = it.next();
6767 if (packageName == null
6768 || pa.mActivity.getPackageName().equals(packageName)) {
6769 if (outFilters != null) {
6770 outFilters.add(new IntentFilter(pa));
6771 }
6772 if (outActivities != null) {
6773 outActivities.add(pa.mActivity);
6774 }
6775 }
6776 }
6777 }
6778
6779 return num;
6780 }
6781
6782 public void setApplicationEnabledSetting(String appPackageName,
6783 int newState, int flags) {
6784 setEnabledSetting(appPackageName, null, newState, flags);
6785 }
6786
6787 public void setComponentEnabledSetting(ComponentName componentName,
6788 int newState, int flags) {
6789 setEnabledSetting(componentName.getPackageName(),
6790 componentName.getClassName(), newState, flags);
6791 }
6792
6793 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006794 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006795 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6796 || newState == COMPONENT_ENABLED_STATE_ENABLED
6797 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6798 throw new IllegalArgumentException("Invalid new component state: "
6799 + newState);
6800 }
6801 PackageSetting pkgSetting;
6802 final int uid = Binder.getCallingUid();
6803 final int permission = mContext.checkCallingPermission(
6804 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6805 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006806 boolean sendNow = false;
6807 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006808 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006809 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006810 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006811 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006812 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006813 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006814 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006815 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006816 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006817 }
6818 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006819 "Unknown component: " + packageName
6820 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006821 }
6822 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6823 throw new SecurityException(
6824 "Permission Denial: attempt to change component state from pid="
6825 + Binder.getCallingPid()
6826 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6827 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006828 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006829 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006830 if (pkgSetting.enabled == newState) {
6831 // Nothing to do
6832 return;
6833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006834 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006835 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006836 } else {
6837 // We're dealing with a component level state change
6838 switch (newState) {
6839 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006840 if (!pkgSetting.enableComponentLP(className)) {
6841 return;
6842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006843 break;
6844 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006845 if (!pkgSetting.disableComponentLP(className)) {
6846 return;
6847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006848 break;
6849 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006850 if (!pkgSetting.restoreComponentLP(className)) {
6851 return;
6852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006853 break;
6854 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006855 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006856 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006857 }
6858 }
6859 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006860 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006861 components = mPendingBroadcasts.get(packageName);
6862 boolean newPackage = components == null;
6863 if (newPackage) {
6864 components = new ArrayList<String>();
6865 }
6866 if (!components.contains(componentName)) {
6867 components.add(componentName);
6868 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006869 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6870 sendNow = true;
6871 // Purge entry from pending broadcast list if another one exists already
6872 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006873 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006874 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006875 if (newPackage) {
6876 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006877 }
6878 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6879 // Schedule a message
6880 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6881 }
6882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006883 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006885 long callingId = Binder.clearCallingIdentity();
6886 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006887 if (sendNow) {
6888 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006889 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006891 } finally {
6892 Binder.restoreCallingIdentity(callingId);
6893 }
6894 }
6895
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006896 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006897 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6898 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6899 + " components=" + componentNames);
6900 Bundle extras = new Bundle(4);
6901 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6902 String nameList[] = new String[componentNames.size()];
6903 componentNames.toArray(nameList);
6904 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006905 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6906 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006907 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006908 }
6909
Jacek Surazski65e13172009-04-28 15:26:38 +02006910 public String getInstallerPackageName(String packageName) {
6911 synchronized (mPackages) {
6912 PackageSetting pkg = mSettings.mPackages.get(packageName);
6913 if (pkg == null) {
6914 throw new IllegalArgumentException("Unknown package: " + packageName);
6915 }
6916 return pkg.installerPackageName;
6917 }
6918 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006920 public int getApplicationEnabledSetting(String appPackageName) {
6921 synchronized (mPackages) {
6922 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6923 if (pkg == null) {
6924 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6925 }
6926 return pkg.enabled;
6927 }
6928 }
6929
6930 public int getComponentEnabledSetting(ComponentName componentName) {
6931 synchronized (mPackages) {
6932 final String packageNameStr = componentName.getPackageName();
6933 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6934 if (pkg == null) {
6935 throw new IllegalArgumentException("Unknown component: " + componentName);
6936 }
6937 final String classNameStr = componentName.getClassName();
6938 return pkg.currentEnabledStateLP(classNameStr);
6939 }
6940 }
6941
6942 public void enterSafeMode() {
6943 if (!mSystemReady) {
6944 mSafeMode = true;
6945 }
6946 }
6947
6948 public void systemReady() {
6949 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006950
6951 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006952 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006953 mContext.getContentResolver(),
6954 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006955 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006956 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006957 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006959 }
6960
6961 public boolean isSafeMode() {
6962 return mSafeMode;
6963 }
6964
6965 public boolean hasSystemUidErrors() {
6966 return mHasSystemUidErrors;
6967 }
6968
6969 static String arrayToString(int[] array) {
6970 StringBuffer buf = new StringBuffer(128);
6971 buf.append('[');
6972 if (array != null) {
6973 for (int i=0; i<array.length; i++) {
6974 if (i > 0) buf.append(", ");
6975 buf.append(array[i]);
6976 }
6977 }
6978 buf.append(']');
6979 return buf.toString();
6980 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006982 @Override
6983 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6984 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6985 != PackageManager.PERMISSION_GRANTED) {
6986 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6987 + Binder.getCallingPid()
6988 + ", uid=" + Binder.getCallingUid()
6989 + " without permission "
6990 + android.Manifest.permission.DUMP);
6991 return;
6992 }
6993
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006994 boolean dumpStar = true;
6995 boolean dumpLibs = false;
6996 boolean dumpFeatures = false;
6997 boolean dumpResolvers = false;
6998 boolean dumpPermissions = false;
6999 boolean dumpPackages = false;
7000 boolean dumpSharedUsers = false;
7001 boolean dumpMessages = false;
7002 boolean dumpProviders = false;
7003
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007004 String packageName = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007005 boolean showFilters = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007006
7007 int opti = 0;
7008 while (opti < args.length) {
7009 String opt = args[opti];
7010 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
7011 break;
7012 }
7013 opti++;
7014 if ("-a".equals(opt)) {
7015 // Right now we only know how to print all.
7016 } else if ("-h".equals(opt)) {
7017 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007018 pw.println(" [-h] [-f] [cmd] ...");
7019 pw.println(" -f: print details of intent filters");
7020 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007021 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007022 pw.println(" l[ibraries]: list known shared libraries");
7023 pw.println(" f[ibraries]: list device features");
7024 pw.println(" r[esolvers]: dump intent resolvers");
7025 pw.println(" perm[issions]: dump permissions");
7026 pw.println(" prov[iders]: dump content providers");
7027 pw.println(" p[ackages]: dump installed packages");
7028 pw.println(" s[hared-users]: dump shared user IDs");
7029 pw.println(" m[essages]: print collected runtime messages");
7030 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007031 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007032 } else if ("-f".equals(opt)) {
7033 showFilters = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007034 } else {
7035 pw.println("Unknown argument: " + opt + "; use -h for help");
7036 }
7037 }
7038
7039 // Is the caller requesting to dump a particular piece of data?
7040 if (opti < args.length) {
7041 String cmd = args[opti];
7042 opti++;
7043 // Is this a package name?
7044 if ("android".equals(cmd) || cmd.contains(".")) {
7045 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007046 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
7047 dumpStar = false;
7048 dumpLibs = true;
7049 } else if ("f".equals(cmd) || "features".equals(cmd)) {
7050 dumpStar = false;
7051 dumpFeatures = true;
7052 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
7053 dumpStar = false;
7054 dumpResolvers = true;
7055 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
7056 dumpStar = false;
7057 dumpPermissions = true;
7058 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
7059 dumpStar = false;
7060 dumpPackages = true;
7061 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
7062 dumpStar = false;
7063 dumpSharedUsers = true;
7064 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
7065 dumpStar = false;
7066 dumpProviders = true;
7067 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
7068 dumpStar = false;
7069 dumpMessages = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007070 }
7071 }
7072
7073 boolean printedTitle = false;
7074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007075 synchronized (mPackages) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007076 if ((dumpStar || dumpLibs) && packageName == null) {
7077 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007078 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007079 pw.println("Libraries:");
7080 Iterator<String> it = mSharedLibraries.keySet().iterator();
7081 while (it.hasNext()) {
7082 String name = it.next();
7083 pw.print(" ");
7084 pw.print(name);
7085 pw.print(" -> ");
7086 pw.println(mSharedLibraries.get(name));
7087 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007088 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007089
7090 if ((dumpStar || dumpFeatures) && packageName == null) {
7091 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007092 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007093 pw.println("Features:");
7094 Iterator<String> it = mAvailableFeatures.keySet().iterator();
7095 while (it.hasNext()) {
7096 String name = it.next();
7097 pw.print(" ");
7098 pw.println(name);
7099 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007100 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007101
7102 if (dumpStar || dumpResolvers) {
7103 if (mActivities.dump(pw, printedTitle
7104 ? "\nActivity Resolver Table:" : "Activity Resolver Table:",
7105 " ", packageName, showFilters)) {
7106 printedTitle = true;
7107 }
7108 if (mReceivers.dump(pw, printedTitle
7109 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
7110 " ", packageName, showFilters)) {
7111 printedTitle = true;
7112 }
7113 if (mServices.dump(pw, printedTitle
7114 ? "\nService Resolver Table:" : "Service Resolver Table:",
7115 " ", packageName, showFilters)) {
7116 printedTitle = true;
7117 }
7118 if (mSettings.mPreferredActivities.dump(pw, printedTitle
7119 ? "\nPreferred Activities:" : "Preferred Activities:",
7120 " ", packageName, showFilters)) {
7121 printedTitle = true;
7122 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007123 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007124
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007125 boolean printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007126 if (dumpStar || dumpPermissions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007127 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007128 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7129 continue;
7130 }
7131 if (!printedSomething) {
7132 if (printedTitle) pw.println(" ");
7133 pw.println("Permissions:");
7134 printedSomething = true;
7135 printedTitle = true;
7136 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007137 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7138 pw.print(Integer.toHexString(System.identityHashCode(p)));
7139 pw.println("):");
7140 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7141 pw.print(" uid="); pw.print(p.uid);
7142 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007143 pw.print(" type="); pw.print(p.type);
7144 pw.print(" prot="); pw.println(p.protectionLevel);
7145 if (p.packageSetting != null) {
7146 pw.print(" packageSetting="); pw.println(p.packageSetting);
7147 }
7148 if (p.perm != null) {
7149 pw.print(" perm="); pw.println(p.perm);
7150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007151 }
7152 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007153
7154 if (dumpStar || dumpProviders) {
7155 printedSomething = false;
7156 for (PackageParser.Provider p : mProviders.values()) {
7157 if (packageName != null && !packageName.equals(p.info.packageName)) {
7158 continue;
7159 }
7160 if (!printedSomething) {
7161 if (printedTitle) pw.println(" ");
7162 pw.println("Registered ContentProviders:");
7163 printedSomething = true;
7164 printedTitle = true;
7165 }
7166 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
7167 pw.println(p.toString());
7168 }
7169 }
7170
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007171 printedSomething = false;
7172 SharedUserSetting packageSharedUser = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007173 if (dumpStar || dumpPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007174 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
7175 Date date = new Date();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007176 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007177 if (packageName != null && !packageName.equals(ps.realName)
7178 && !packageName.equals(ps.name)) {
7179 continue;
7180 }
7181 if (!printedSomething) {
7182 if (printedTitle) pw.println(" ");
7183 pw.println("Packages:");
7184 printedSomething = true;
7185 printedTitle = true;
7186 }
7187 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007188 pw.print(" Package [");
7189 pw.print(ps.realName != null ? ps.realName : ps.name);
7190 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007191 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7192 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007193 if (ps.realName != null) {
7194 pw.print(" compat name="); pw.println(ps.name);
7195 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007196 pw.print(" userId="); pw.print(ps.userId);
7197 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7198 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7199 pw.print(" pkg="); pw.println(ps.pkg);
7200 pw.print(" codePath="); pw.println(ps.codePathString);
7201 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07007202 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root6c4d9042010-11-19 12:48:05 -08007203 pw.print(" obbPaths="); pw.println(Arrays.toString(ps.obbPathStrings));
Kenny Root70fc04c2010-10-22 10:07:11 -07007204 pw.print(" versionCode="); pw.println(ps.versionCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007205 if (ps.pkg != null) {
Kenny Root70fc04c2010-10-22 10:07:11 -07007206 pw.print(" versionName="); pw.println(ps.pkg.mVersionName);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007207 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007208 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07007209 if (ps.pkg.mOperationPending) {
7210 pw.println(" mOperationPending=true");
7211 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007212 pw.print(" supportsScreens=[");
7213 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007214 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007215 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7216 if (!first) pw.print(", ");
7217 first = false;
7218 pw.print("small");
7219 }
7220 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007221 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007222 if (!first) pw.print(", ");
7223 first = false;
7224 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007225 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007226 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007227 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007228 if (!first) pw.print(", ");
7229 first = false;
7230 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007231 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007232 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007233 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007234 if (!first) pw.print(", ");
7235 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007236 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007237 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007238 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007239 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007240 if (!first) pw.print(", ");
7241 first = false;
7242 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007243 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007244 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007245 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7246 if (!first) pw.print(", ");
7247 first = false;
7248 pw.print("anyDensity");
7249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007250 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007251 pw.println("]");
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007252 pw.print(" timeStamp=");
7253 date.setTime(ps.timeStamp); pw.println(sdf.format(date));
7254 pw.print(" firstInstallTime=");
7255 date.setTime(ps.firstInstallTime); pw.println(sdf.format(date));
7256 pw.print(" lastUpdateTime=");
7257 date.setTime(ps.lastUpdateTime); pw.println(sdf.format(date));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007258 pw.print(" signatures="); pw.println(ps.signatures);
7259 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007260 pw.print(" haveGids="); pw.println(ps.haveGids);
7261 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007262 pw.print(" installStatus="); pw.print(ps.installStatus);
7263 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007264 if (ps.disabledComponents.size() > 0) {
7265 pw.println(" disabledComponents:");
7266 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007267 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007268 }
7269 }
7270 if (ps.enabledComponents.size() > 0) {
7271 pw.println(" enabledComponents:");
7272 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007273 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007274 }
7275 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007276 if (ps.grantedPermissions.size() > 0) {
7277 pw.println(" grantedPermissions:");
7278 for (String s : ps.grantedPermissions) {
7279 pw.print(" "); pw.println(s);
7280 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007282 }
7283 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007284 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007285 if (dumpStar || dumpPackages) {
7286 if (mSettings.mRenamedPackages.size() > 0) {
7287 for (HashMap.Entry<String, String> e
7288 : mSettings.mRenamedPackages.entrySet()) {
7289 if (packageName != null && !packageName.equals(e.getKey())
7290 && !packageName.equals(e.getValue())) {
7291 continue;
7292 }
7293 if (!printedSomething) {
7294 if (printedTitle) pw.println(" ");
7295 pw.println("Renamed packages:");
7296 printedSomething = true;
7297 printedTitle = true;
7298 }
7299 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7300 pw.println(e.getValue());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007301 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007302 }
7303 printedSomething = false;
7304 if (mSettings.mDisabledSysPackages.size() > 0) {
7305 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
7306 if (packageName != null && !packageName.equals(ps.realName)
7307 && !packageName.equals(ps.name)) {
7308 continue;
7309 }
7310 if (!printedSomething) {
7311 if (printedTitle) pw.println(" ");
7312 pw.println("Hidden system packages:");
7313 printedSomething = true;
7314 printedTitle = true;
7315 }
7316 pw.print(" Package [");
7317 pw.print(ps.realName != null ? ps.realName : ps.name);
7318 pw.print("] (");
7319 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7320 pw.println("):");
7321 if (ps.realName != null) {
7322 pw.print(" compat name="); pw.println(ps.name);
7323 }
7324 pw.print(" userId="); pw.println(ps.userId);
7325 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7326 pw.print(" codePath="); pw.println(ps.codePathString);
7327 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007328 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007329 }
7330 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007331 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007332 if (dumpStar || dumpSharedUsers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007333 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007334 if (packageName != null && su != packageSharedUser) {
7335 continue;
7336 }
7337 if (!printedSomething) {
7338 if (printedTitle) pw.println(" ");
7339 pw.println("Shared users:");
7340 printedSomething = true;
7341 printedTitle = true;
7342 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007343 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7344 pw.print(Integer.toHexString(System.identityHashCode(su)));
7345 pw.println("):");
7346 pw.print(" userId="); pw.print(su.userId);
7347 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007348 pw.println(" grantedPermissions:");
7349 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007350 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007352 }
7353 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007354
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007355 if ((dumpStar || dumpMessages) && packageName == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007356 if (printedTitle) pw.println(" ");
7357 printedTitle = true;
7358 pw.println("Settings parse messages:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007359 pw.print(mSettings.mReadMessages.toString());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007360
7361 pw.println(" ");
7362 pw.println("Package warning messages:");
7363 File fname = getSettingsProblemFile();
7364 FileInputStream in;
7365 try {
7366 in = new FileInputStream(fname);
7367 int avail = in.available();
7368 byte[] data = new byte[avail];
7369 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007370 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007371 } catch (FileNotFoundException e) {
7372 } catch (IOException e) {
7373 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007375 }
7376 }
7377
7378 static final class BasePermission {
7379 final static int TYPE_NORMAL = 0;
7380 final static int TYPE_BUILTIN = 1;
7381 final static int TYPE_DYNAMIC = 2;
7382
7383 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007384 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007385 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007386 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007387 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007388 PackageParser.Permission perm;
7389 PermissionInfo pendingInfo;
7390 int uid;
7391 int[] gids;
7392
7393 BasePermission(String _name, String _sourcePackage, int _type) {
7394 name = _name;
7395 sourcePackage = _sourcePackage;
7396 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007397 // Default to most conservative protection level.
7398 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7399 }
7400
7401 public String toString() {
7402 return "BasePermission{"
7403 + Integer.toHexString(System.identityHashCode(this))
7404 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007405 }
7406 }
7407
7408 static class PackageSignatures {
7409 private Signature[] mSignatures;
7410
Kenny Rootea6bf362011-01-13 14:53:17 -08007411 PackageSignatures(PackageSignatures orig) {
7412 if (orig != null && orig.mSignatures != null) {
7413 mSignatures = orig.mSignatures.clone();
7414 }
7415 }
7416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007417 PackageSignatures(Signature[] sigs) {
7418 assignSignatures(sigs);
7419 }
7420
7421 PackageSignatures() {
7422 }
7423
7424 void writeXml(XmlSerializer serializer, String tagName,
7425 ArrayList<Signature> pastSignatures) throws IOException {
7426 if (mSignatures == null) {
7427 return;
7428 }
7429 serializer.startTag(null, tagName);
7430 serializer.attribute(null, "count",
7431 Integer.toString(mSignatures.length));
7432 for (int i=0; i<mSignatures.length; i++) {
7433 serializer.startTag(null, "cert");
7434 final Signature sig = mSignatures[i];
7435 final int sigHash = sig.hashCode();
7436 final int numPast = pastSignatures.size();
7437 int j;
7438 for (j=0; j<numPast; j++) {
7439 Signature pastSig = pastSignatures.get(j);
7440 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7441 serializer.attribute(null, "index", Integer.toString(j));
7442 break;
7443 }
7444 }
7445 if (j >= numPast) {
7446 pastSignatures.add(sig);
7447 serializer.attribute(null, "index", Integer.toString(numPast));
7448 serializer.attribute(null, "key", sig.toCharsString());
7449 }
7450 serializer.endTag(null, "cert");
7451 }
7452 serializer.endTag(null, tagName);
7453 }
7454
7455 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7456 throws IOException, XmlPullParserException {
7457 String countStr = parser.getAttributeValue(null, "count");
7458 if (countStr == null) {
7459 reportSettingsProblem(Log.WARN,
7460 "Error in package manager settings: <signatures> has"
7461 + " no count at " + parser.getPositionDescription());
7462 XmlUtils.skipCurrentTag(parser);
7463 }
7464 final int count = Integer.parseInt(countStr);
7465 mSignatures = new Signature[count];
7466 int pos = 0;
7467
7468 int outerDepth = parser.getDepth();
7469 int type;
7470 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7471 && (type != XmlPullParser.END_TAG
7472 || parser.getDepth() > outerDepth)) {
7473 if (type == XmlPullParser.END_TAG
7474 || type == XmlPullParser.TEXT) {
7475 continue;
7476 }
7477
7478 String tagName = parser.getName();
7479 if (tagName.equals("cert")) {
7480 if (pos < count) {
7481 String index = parser.getAttributeValue(null, "index");
7482 if (index != null) {
7483 try {
7484 int idx = Integer.parseInt(index);
7485 String key = parser.getAttributeValue(null, "key");
7486 if (key == null) {
7487 if (idx >= 0 && idx < pastSignatures.size()) {
7488 Signature sig = pastSignatures.get(idx);
7489 if (sig != null) {
7490 mSignatures[pos] = pastSignatures.get(idx);
7491 pos++;
7492 } else {
7493 reportSettingsProblem(Log.WARN,
7494 "Error in package manager settings: <cert> "
7495 + "index " + index + " is not defined at "
7496 + parser.getPositionDescription());
7497 }
7498 } else {
7499 reportSettingsProblem(Log.WARN,
7500 "Error in package manager settings: <cert> "
7501 + "index " + index + " is out of bounds at "
7502 + parser.getPositionDescription());
7503 }
7504 } else {
7505 while (pastSignatures.size() <= idx) {
7506 pastSignatures.add(null);
7507 }
7508 Signature sig = new Signature(key);
7509 pastSignatures.set(idx, sig);
7510 mSignatures[pos] = sig;
7511 pos++;
7512 }
7513 } catch (NumberFormatException e) {
7514 reportSettingsProblem(Log.WARN,
7515 "Error in package manager settings: <cert> "
7516 + "index " + index + " is not a number at "
7517 + parser.getPositionDescription());
7518 }
7519 } else {
7520 reportSettingsProblem(Log.WARN,
7521 "Error in package manager settings: <cert> has"
7522 + " no index at " + parser.getPositionDescription());
7523 }
7524 } else {
7525 reportSettingsProblem(Log.WARN,
7526 "Error in package manager settings: too "
7527 + "many <cert> tags, expected " + count
7528 + " at " + parser.getPositionDescription());
7529 }
7530 } else {
7531 reportSettingsProblem(Log.WARN,
7532 "Unknown element under <cert>: "
7533 + parser.getName());
7534 }
7535 XmlUtils.skipCurrentTag(parser);
7536 }
7537
7538 if (pos < count) {
7539 // Should never happen -- there is an error in the written
7540 // settings -- but if it does we don't want to generate
7541 // a bad array.
7542 Signature[] newSigs = new Signature[pos];
7543 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7544 mSignatures = newSigs;
7545 }
7546 }
7547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007548 private void assignSignatures(Signature[] sigs) {
7549 if (sigs == null) {
7550 mSignatures = null;
7551 return;
7552 }
7553 mSignatures = new Signature[sigs.length];
7554 for (int i=0; i<sigs.length; i++) {
7555 mSignatures[i] = sigs[i];
7556 }
7557 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007559 @Override
7560 public String toString() {
7561 StringBuffer buf = new StringBuffer(128);
7562 buf.append("PackageSignatures{");
7563 buf.append(Integer.toHexString(System.identityHashCode(this)));
7564 buf.append(" [");
7565 if (mSignatures != null) {
7566 for (int i=0; i<mSignatures.length; i++) {
7567 if (i > 0) buf.append(", ");
7568 buf.append(Integer.toHexString(
7569 System.identityHashCode(mSignatures[i])));
7570 }
7571 }
7572 buf.append("]}");
7573 return buf.toString();
7574 }
7575 }
7576
7577 static class PreferredActivity extends IntentFilter {
7578 final int mMatch;
7579 final String[] mSetPackages;
7580 final String[] mSetClasses;
7581 final String[] mSetComponents;
7582 final ComponentName mActivity;
7583 final String mShortActivity;
7584 String mParseError;
7585
7586 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7587 ComponentName activity) {
7588 super(filter);
7589 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7590 mActivity = activity;
7591 mShortActivity = activity.flattenToShortString();
7592 mParseError = null;
7593 if (set != null) {
7594 final int N = set.length;
7595 String[] myPackages = new String[N];
7596 String[] myClasses = new String[N];
7597 String[] myComponents = new String[N];
7598 for (int i=0; i<N; i++) {
7599 ComponentName cn = set[i];
7600 if (cn == null) {
7601 mSetPackages = null;
7602 mSetClasses = null;
7603 mSetComponents = null;
7604 return;
7605 }
7606 myPackages[i] = cn.getPackageName().intern();
7607 myClasses[i] = cn.getClassName().intern();
7608 myComponents[i] = cn.flattenToShortString().intern();
7609 }
7610 mSetPackages = myPackages;
7611 mSetClasses = myClasses;
7612 mSetComponents = myComponents;
7613 } else {
7614 mSetPackages = null;
7615 mSetClasses = null;
7616 mSetComponents = null;
7617 }
7618 }
7619
7620 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7621 IOException {
7622 mShortActivity = parser.getAttributeValue(null, "name");
7623 mActivity = ComponentName.unflattenFromString(mShortActivity);
7624 if (mActivity == null) {
7625 mParseError = "Bad activity name " + mShortActivity;
7626 }
7627 String matchStr = parser.getAttributeValue(null, "match");
7628 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7629 String setCountStr = parser.getAttributeValue(null, "set");
7630 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7631
7632 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7633 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7634 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7635
7636 int setPos = 0;
7637
7638 int outerDepth = parser.getDepth();
7639 int type;
7640 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7641 && (type != XmlPullParser.END_TAG
7642 || parser.getDepth() > outerDepth)) {
7643 if (type == XmlPullParser.END_TAG
7644 || type == XmlPullParser.TEXT) {
7645 continue;
7646 }
7647
7648 String tagName = parser.getName();
7649 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7650 // + parser.getDepth() + " tag=" + tagName);
7651 if (tagName.equals("set")) {
7652 String name = parser.getAttributeValue(null, "name");
7653 if (name == null) {
7654 if (mParseError == null) {
7655 mParseError = "No name in set tag in preferred activity "
7656 + mShortActivity;
7657 }
7658 } else if (setPos >= setCount) {
7659 if (mParseError == null) {
7660 mParseError = "Too many set tags in preferred activity "
7661 + mShortActivity;
7662 }
7663 } else {
7664 ComponentName cn = ComponentName.unflattenFromString(name);
7665 if (cn == null) {
7666 if (mParseError == null) {
7667 mParseError = "Bad set name " + name + " in preferred activity "
7668 + mShortActivity;
7669 }
7670 } else {
7671 myPackages[setPos] = cn.getPackageName();
7672 myClasses[setPos] = cn.getClassName();
7673 myComponents[setPos] = name;
7674 setPos++;
7675 }
7676 }
7677 XmlUtils.skipCurrentTag(parser);
7678 } else if (tagName.equals("filter")) {
7679 //Log.i(TAG, "Starting to parse filter...");
7680 readFromXml(parser);
7681 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7682 // + parser.getDepth() + " tag=" + parser.getName());
7683 } else {
7684 reportSettingsProblem(Log.WARN,
7685 "Unknown element under <preferred-activities>: "
7686 + parser.getName());
7687 XmlUtils.skipCurrentTag(parser);
7688 }
7689 }
7690
7691 if (setPos != setCount) {
7692 if (mParseError == null) {
7693 mParseError = "Not enough set tags (expected " + setCount
7694 + " but found " + setPos + ") in " + mShortActivity;
7695 }
7696 }
7697
7698 mSetPackages = myPackages;
7699 mSetClasses = myClasses;
7700 mSetComponents = myComponents;
7701 }
7702
7703 public void writeToXml(XmlSerializer serializer) throws IOException {
7704 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7705 serializer.attribute(null, "name", mShortActivity);
7706 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7707 serializer.attribute(null, "set", Integer.toString(NS));
7708 for (int s=0; s<NS; s++) {
7709 serializer.startTag(null, "set");
7710 serializer.attribute(null, "name", mSetComponents[s]);
7711 serializer.endTag(null, "set");
7712 }
7713 serializer.startTag(null, "filter");
7714 super.writeToXml(serializer);
7715 serializer.endTag(null, "filter");
7716 }
7717
7718 boolean sameSet(List<ResolveInfo> query, int priority) {
7719 if (mSetPackages == null) return false;
7720 final int NQ = query.size();
7721 final int NS = mSetPackages.length;
7722 int numMatch = 0;
7723 for (int i=0; i<NQ; i++) {
7724 ResolveInfo ri = query.get(i);
7725 if (ri.priority != priority) continue;
7726 ActivityInfo ai = ri.activityInfo;
7727 boolean good = false;
7728 for (int j=0; j<NS; j++) {
7729 if (mSetPackages[j].equals(ai.packageName)
7730 && mSetClasses[j].equals(ai.name)) {
7731 numMatch++;
7732 good = true;
7733 break;
7734 }
7735 }
7736 if (!good) return false;
7737 }
7738 return numMatch == NS;
7739 }
7740 }
7741
7742 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007743 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007745 HashSet<String> grantedPermissions = new HashSet<String>();
7746 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007748 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007749 setFlags(pkgFlags);
7750 }
7751
Kenny Rootea6bf362011-01-13 14:53:17 -08007752 GrantedPermissions(GrantedPermissions base) {
7753 pkgFlags = base.pkgFlags;
7754 grantedPermissions = (HashSet<String>) base.grantedPermissions.clone();
7755
7756 if (base.gids != null) {
7757 gids = base.gids.clone();
7758 }
7759 }
7760
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007761 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007762 this.pkgFlags = pkgFlags & (
7763 ApplicationInfo.FLAG_SYSTEM |
7764 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007765 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007766 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007767 }
7768 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007770 /**
7771 * Settings base class for pending and resolved classes.
7772 */
7773 static class PackageSettingBase extends GrantedPermissions {
7774 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007775 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007776 File codePath;
7777 String codePathString;
7778 File resourcePath;
7779 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007780 String nativeLibraryPathString;
Kenny Root6c4d9042010-11-19 12:48:05 -08007781 String[] obbPathStrings;
Kenny Root7d794fb2010-09-13 16:29:49 -07007782 long timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007783 long firstInstallTime;
7784 long lastUpdateTime;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007785 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007786
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007787 boolean uidError;
Kenny Rootea6bf362011-01-13 14:53:17 -08007788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007789 PackageSignatures signatures = new PackageSignatures();
7790
7791 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007792 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007794 /* Explicitly disabled components */
7795 HashSet<String> disabledComponents = new HashSet<String>(0);
7796 /* Explicitly enabled components */
7797 HashSet<String> enabledComponents = new HashSet<String>(0);
7798 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7799 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007800
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007801 PackageSettingBase origPackage;
7802
Jacek Surazski65e13172009-04-28 15:26:38 +02007803 /* package name of the app that installed this package */
7804 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007805
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007806 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007807 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007808 super(pkgFlags);
7809 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007810 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007811 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007812 }
7813
Kenny Rootea6bf362011-01-13 14:53:17 -08007814 /**
7815 * New instance of PackageSetting with one-level-deep cloning.
7816 */
7817 PackageSettingBase(PackageSettingBase base) {
7818 super(base);
7819
7820 name = base.name;
7821 realName = base.realName;
7822 codePath = base.codePath;
7823 codePathString = base.codePathString;
7824 resourcePath = base.resourcePath;
7825 resourcePathString = base.resourcePathString;
7826 nativeLibraryPathString = base.nativeLibraryPathString;
7827
7828 if (base.obbPathStrings != null) {
7829 obbPathStrings = base.obbPathStrings.clone();
7830 }
7831
7832 timeStamp = base.timeStamp;
7833 firstInstallTime = base.firstInstallTime;
7834 lastUpdateTime = base.lastUpdateTime;
7835 versionCode = base.versionCode;
7836
7837 uidError = base.uidError;
7838
7839 signatures = new PackageSignatures(base.signatures);
7840
7841 permissionsFixed = base.permissionsFixed;
7842 haveGids = base.haveGids;
7843
7844 disabledComponents = (HashSet<String>) base.disabledComponents.clone();
7845
7846 enabledComponents = (HashSet<String>) base.enabledComponents.clone();
7847
7848 enabled = base.enabled;
7849 installStatus = base.installStatus;
7850
7851 origPackage = base.origPackage;
7852
7853 installerPackageName = base.installerPackageName;
7854 }
7855
Kenny Root806cc132010-09-12 08:34:19 -07007856 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7857 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007858 this.codePath = codePath;
7859 this.codePathString = codePath.toString();
7860 this.resourcePath = resourcePath;
7861 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07007862 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007863 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007864 }
Kenny Root85387d72010-08-26 10:13:11 -07007865
Jacek Surazski65e13172009-04-28 15:26:38 +02007866 public void setInstallerPackageName(String packageName) {
7867 installerPackageName = packageName;
7868 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007869
Jacek Surazski65e13172009-04-28 15:26:38 +02007870 String getInstallerPackageName() {
7871 return installerPackageName;
7872 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007874 public void setInstallStatus(int newStatus) {
7875 installStatus = newStatus;
7876 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007878 public int getInstallStatus() {
7879 return installStatus;
7880 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007882 public void setTimeStamp(long newStamp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007883 timeStamp = newStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007884 }
7885
Kenny Rootea6bf362011-01-13 14:53:17 -08007886 /**
7887 * Make a shallow copy of this package settings.
7888 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007889 public void copyFrom(PackageSettingBase base) {
7890 grantedPermissions = base.grantedPermissions;
7891 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007893 timeStamp = base.timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007894 firstInstallTime = base.firstInstallTime;
7895 lastUpdateTime = base.lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007896 signatures = base.signatures;
7897 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007898 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007899 disabledComponents = base.disabledComponents;
7900 enabledComponents = base.enabledComponents;
7901 enabled = base.enabled;
7902 installStatus = base.installStatus;
7903 }
7904
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007905 boolean enableComponentLP(String componentClassName) {
7906 boolean changed = disabledComponents.remove(componentClassName);
7907 changed |= enabledComponents.add(componentClassName);
7908 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 }
7910
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007911 boolean disableComponentLP(String componentClassName) {
7912 boolean changed = enabledComponents.remove(componentClassName);
7913 changed |= disabledComponents.add(componentClassName);
7914 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007915 }
7916
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007917 boolean restoreComponentLP(String componentClassName) {
7918 boolean changed = enabledComponents.remove(componentClassName);
7919 changed |= disabledComponents.remove(componentClassName);
7920 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007921 }
7922
7923 int currentEnabledStateLP(String componentName) {
7924 if (enabledComponents.contains(componentName)) {
7925 return COMPONENT_ENABLED_STATE_ENABLED;
7926 } else if (disabledComponents.contains(componentName)) {
7927 return COMPONENT_ENABLED_STATE_DISABLED;
7928 } else {
7929 return COMPONENT_ENABLED_STATE_DEFAULT;
7930 }
7931 }
7932 }
7933
7934 /**
7935 * Settings data for a particular package we know about.
7936 */
7937 static final class PackageSetting extends PackageSettingBase {
7938 int userId;
7939 PackageParser.Package pkg;
7940 SharedUserSetting sharedUser;
7941
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007942 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007943 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
7944 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
7945 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007946 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007947
Kenny Rootea6bf362011-01-13 14:53:17 -08007948 /**
7949 * New instance of PackageSetting replicating the original settings.
7950 * Note that it keeps the same PackageParser.Package instance.
7951 */
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007952 PackageSetting(PackageSetting orig) {
Kenny Rootea6bf362011-01-13 14:53:17 -08007953 super(orig);
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007954
Kenny Rootea6bf362011-01-13 14:53:17 -08007955 userId = orig.userId;
7956 pkg = orig.pkg;
7957 sharedUser = orig.sharedUser;
Kenny Root91c459e2011-01-11 10:08:01 -08007958 }
7959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007960 @Override
7961 public String toString() {
7962 return "PackageSetting{"
7963 + Integer.toHexString(System.identityHashCode(this))
7964 + " " + name + "/" + userId + "}";
7965 }
7966 }
7967
7968 /**
7969 * Settings data for a particular shared user ID we know about.
7970 */
7971 static final class SharedUserSetting extends GrantedPermissions {
7972 final String name;
7973 int userId;
7974 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7975 final PackageSignatures signatures = new PackageSignatures();
7976
7977 SharedUserSetting(String _name, int _pkgFlags) {
7978 super(_pkgFlags);
7979 name = _name;
7980 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007982 @Override
7983 public String toString() {
7984 return "SharedUserSetting{"
7985 + Integer.toHexString(System.identityHashCode(this))
7986 + " " + name + "/" + userId + "}";
7987 }
7988 }
7989
7990 /**
7991 * Holds information about dynamic settings.
7992 */
7993 private static final class Settings {
7994 private final File mSettingsFilename;
7995 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007996 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007997 private final HashMap<String, PackageSetting> mPackages =
7998 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007999 // List of replaced system applications
8000 final HashMap<String, PackageSetting> mDisabledSysPackages =
8001 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008002
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008003 // These are the last platform API version we were using for
8004 // the apps installed on internal and external storage. It is
8005 // used to grant newer permissions one time during a system upgrade.
8006 int mInternalSdkPlatform;
8007 int mExternalSdkPlatform;
8008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008009 // The user's preferred activities associated with particular intent
8010 // filters.
8011 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
8012 new IntentResolver<PreferredActivity, PreferredActivity>() {
8013 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008014 protected String packageForFilter(PreferredActivity filter) {
8015 return filter.mActivity.getPackageName();
8016 }
8017 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008018 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008019 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008020 out.print(prefix); out.print(
8021 Integer.toHexString(System.identityHashCode(filter)));
8022 out.print(' ');
8023 out.print(filter.mActivity.flattenToShortString());
8024 out.print(" match=0x");
8025 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008026 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008027 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008028 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008029 out.print(prefix); out.print(" ");
8030 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008031 }
8032 }
8033 }
8034 };
8035 private final HashMap<String, SharedUserSetting> mSharedUsers =
8036 new HashMap<String, SharedUserSetting>();
8037 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
8038 private final SparseArray<Object> mOtherUserIds =
8039 new SparseArray<Object>();
8040
8041 // For reading/writing settings file.
8042 private final ArrayList<Signature> mPastSignatures =
8043 new ArrayList<Signature>();
8044
8045 // Mapping from permission names to info about them.
8046 final HashMap<String, BasePermission> mPermissions =
8047 new HashMap<String, BasePermission>();
8048
8049 // Mapping from permission tree names to info about them.
8050 final HashMap<String, BasePermission> mPermissionTrees =
8051 new HashMap<String, BasePermission>();
8052
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008053 // Packages that have been uninstalled and still need their external
8054 // storage data deleted.
8055 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
8056
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008057 // Packages that have been renamed since they were first installed.
8058 // Keys are the new names of the packages, values are the original
8059 // names. The packages appear everwhere else under their original
8060 // names.
8061 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
8062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008063 private final StringBuilder mReadMessages = new StringBuilder();
8064
8065 private static final class PendingPackage extends PackageSettingBase {
8066 final int sharedId;
8067
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008068 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008069 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
8070 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
8071 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008072 this.sharedId = sharedId;
8073 }
8074 }
8075 private final ArrayList<PendingPackage> mPendingPackages
8076 = new ArrayList<PendingPackage>();
8077
8078 Settings() {
8079 File dataDir = Environment.getDataDirectory();
8080 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08008081 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
8082 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008083 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008084 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008085 FileUtils.setPermissions(systemDir.toString(),
8086 FileUtils.S_IRWXU|FileUtils.S_IRWXG
8087 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
8088 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08008089 FileUtils.setPermissions(systemSecureDir.toString(),
8090 FileUtils.S_IRWXU|FileUtils.S_IRWXG
8091 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
8092 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008093 mSettingsFilename = new File(systemDir, "packages.xml");
8094 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008095 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008096 }
8097
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008098 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008099 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008100 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008101 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008102 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07008103 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008104 return p;
8105 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008106
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008107 PackageSetting peekPackageLP(String name) {
8108 return mPackages.get(name);
8109 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008110 PackageSetting p = mPackages.get(name);
8111 if (p != null && p.codePath.getPath().equals(codePath)) {
8112 return p;
8113 }
8114 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008115 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008116 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008118 void setInstallStatus(String pkgName, int status) {
8119 PackageSetting p = mPackages.get(pkgName);
8120 if(p != null) {
8121 if(p.getInstallStatus() != status) {
8122 p.setInstallStatus(status);
8123 }
8124 }
8125 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008126
Jacek Surazski65e13172009-04-28 15:26:38 +02008127 void setInstallerPackageName(String pkgName,
8128 String installerPkgName) {
8129 PackageSetting p = mPackages.get(pkgName);
8130 if(p != null) {
8131 p.setInstallerPackageName(installerPkgName);
8132 }
8133 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008134
Jacek Surazski65e13172009-04-28 15:26:38 +02008135 String getInstallerPackageName(String pkgName) {
8136 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008137 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02008138 }
8139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008140 int getInstallStatus(String pkgName) {
8141 PackageSetting p = mPackages.get(pkgName);
8142 if(p != null) {
8143 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008145 return -1;
8146 }
8147
8148 SharedUserSetting getSharedUserLP(String name,
8149 int pkgFlags, boolean create) {
8150 SharedUserSetting s = mSharedUsers.get(name);
8151 if (s == null) {
8152 if (!create) {
8153 return null;
8154 }
8155 s = new SharedUserSetting(name, pkgFlags);
8156 if (MULTIPLE_APPLICATION_UIDS) {
8157 s.userId = newUserIdLP(s);
8158 } else {
8159 s.userId = FIRST_APPLICATION_UID;
8160 }
8161 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
8162 // < 0 means we couldn't assign a userid; fall out and return
8163 // s, which is currently null
8164 if (s.userId >= 0) {
8165 mSharedUsers.put(name, s);
8166 }
8167 }
8168
8169 return s;
8170 }
8171
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008172 boolean disableSystemPackageLP(String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008173 PackageSetting p = mPackages.get(name);
8174 if(p == null) {
8175 Log.w(TAG, "Package:"+name+" is not an installed package");
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008176 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008177 }
8178 PackageSetting dp = mDisabledSysPackages.get(name);
8179 // always make sure the system package code and resource paths dont change
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008180 if (dp == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008181 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8182 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8183 }
8184 mDisabledSysPackages.put(name, p);
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008185
8186 // a little trick... when we install the new package, we don't
8187 // want to modify the existing PackageSetting for the built-in
8188 // version. so at this point we need a new PackageSetting that
Kenny Rootea6bf362011-01-13 14:53:17 -08008189 // is okay to muck with.
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008190 PackageSetting newp = new PackageSetting(p);
8191 replacePackageLP(name, newp);
8192 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008193 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008194 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008195 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008197 PackageSetting enableSystemPackageLP(String name) {
8198 PackageSetting p = mDisabledSysPackages.get(name);
8199 if(p == null) {
8200 Log.w(TAG, "Package:"+name+" is not disabled");
8201 return null;
8202 }
8203 // Reset flag in ApplicationInfo object
8204 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8205 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8206 }
Kenny Root806cc132010-09-12 08:34:19 -07008207 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
8208 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008209 mDisabledSysPackages.remove(name);
8210 return ret;
8211 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008212
Kenny Root806cc132010-09-12 08:34:19 -07008213 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
8214 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008215 PackageSetting p = mPackages.get(name);
8216 if (p != null) {
8217 if (p.userId == uid) {
8218 return p;
8219 }
8220 reportSettingsProblem(Log.ERROR,
8221 "Adding duplicate package, keeping first: " + name);
8222 return null;
8223 }
Kenny Root806cc132010-09-12 08:34:19 -07008224 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
8225 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008226 p.userId = uid;
8227 if (addUserIdLP(uid, p, name)) {
8228 mPackages.put(name, p);
8229 return p;
8230 }
8231 return null;
8232 }
8233
8234 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8235 SharedUserSetting s = mSharedUsers.get(name);
8236 if (s != null) {
8237 if (s.userId == uid) {
8238 return s;
8239 }
8240 reportSettingsProblem(Log.ERROR,
8241 "Adding duplicate shared user, keeping first: " + name);
8242 return null;
8243 }
8244 s = new SharedUserSetting(name, pkgFlags);
8245 s.userId = uid;
8246 if (addUserIdLP(uid, s, name)) {
8247 mSharedUsers.put(name, s);
8248 return s;
8249 }
8250 return null;
8251 }
8252
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008253 // Transfer ownership of permissions from one package to another.
8254 private void transferPermissions(String origPkg, String newPkg) {
8255 // Transfer ownership of permissions to the new package.
8256 for (int i=0; i<2; i++) {
8257 HashMap<String, BasePermission> permissions =
8258 i == 0 ? mPermissionTrees : mPermissions;
8259 for (BasePermission bp : permissions.values()) {
8260 if (origPkg.equals(bp.sourcePackage)) {
8261 if (DEBUG_UPGRADE) Log.v(TAG,
8262 "Moving permission " + bp.name
8263 + " from pkg " + bp.sourcePackage
8264 + " to " + newPkg);
8265 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008266 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008267 bp.perm = null;
8268 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008269 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008270 }
8271 bp.uid = 0;
8272 bp.gids = null;
8273 }
8274 }
8275 }
8276 }
8277
8278 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008279 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008280 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008281 PackageSetting p = mPackages.get(name);
8282 if (p != null) {
8283 if (!p.codePath.equals(codePath)) {
8284 // Check to see if its a disabled system app
Kenny Rootbd135c12010-10-05 12:26:27 -07008285 if ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008286 // This is an updated system app with versions in both system
8287 // and data partition. Just let the most recent version
8288 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008289 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008290 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008291 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008292 // Just a change in the code path is not an issue, but
8293 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008294 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008295 + " to " + codePath + "; Retaining data and using new");
Kenny Rootbd135c12010-10-05 12:26:27 -07008296 /*
8297 * Since we've changed paths, we need to prefer the new
8298 * native library path over the one stored in the
8299 * package settings since we might have moved from
8300 * internal to external storage or vice versa.
8301 */
8302 p.nativeLibraryPathString = nativeLibraryPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008303 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008304 }
8305 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008306 reportSettingsProblem(Log.WARN,
8307 "Package " + name + " shared user changed from "
8308 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8309 + " to "
8310 + (sharedUser != null ? sharedUser.name : "<nothing>")
8311 + "; replacing with new");
8312 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008313 } else {
8314 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8315 // If what we are scanning is a system package, then
8316 // make it so, regardless of whether it was previously
8317 // installed only in the data partition.
8318 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8319 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008320 }
8321 }
8322 if (p == null) {
8323 // Create a new PackageSettings entry. this can end up here because
8324 // of code path mismatch or user id mismatch of an updated system partition
8325 if (!create) {
8326 return null;
8327 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008328 if (origPackage != null) {
8329 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008330 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8331 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008332 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8333 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008334 // Note that we will retain the new package's signature so
8335 // that we can keep its data.
8336 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008337 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008338 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008339 p.sharedUser = origPackage.sharedUser;
8340 p.userId = origPackage.userId;
8341 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008342 mRenamedPackages.put(name, origPackage.name);
8343 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008344 // Update new package state.
8345 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008346 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008347 p = new PackageSetting(name, realName, codePath, resourcePath,
8348 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008349 p.setTimeStamp(codePath.lastModified());
8350 p.sharedUser = sharedUser;
8351 if (sharedUser != null) {
8352 p.userId = sharedUser.userId;
8353 } else if (MULTIPLE_APPLICATION_UIDS) {
8354 // Clone the setting here for disabled system packages
8355 PackageSetting dis = mDisabledSysPackages.get(name);
8356 if (dis != null) {
8357 // For disabled packages a new setting is created
8358 // from the existing user id. This still has to be
8359 // added to list of user id's
8360 // Copy signatures from previous setting
8361 if (dis.signatures.mSignatures != null) {
8362 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8363 }
8364 p.userId = dis.userId;
8365 // Clone permissions
8366 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008367 // Clone component info
8368 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8369 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8370 // Add new setting to list of user ids
8371 addUserIdLP(p.userId, p, name);
8372 } else {
8373 // Assign new user id
8374 p.userId = newUserIdLP(p);
8375 }
8376 } else {
8377 p.userId = FIRST_APPLICATION_UID;
8378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008379 }
8380 if (p.userId < 0) {
8381 reportSettingsProblem(Log.WARN,
8382 "Package " + name + " could not be assigned a valid uid");
8383 return null;
8384 }
8385 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008386 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008387 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008388 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008389 }
8390 }
8391 return p;
8392 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008393
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008394 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008395 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008396 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008397 final String codePath = pkg.applicationInfo.sourceDir;
8398 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008399 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008400 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008401 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008402 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008403 p.codePath = new File(codePath);
8404 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008405 }
8406 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008407 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008408 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008409 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008410 p.resourcePath = new File(resourcePath);
8411 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008412 }
Kenny Root85387d72010-08-26 10:13:11 -07008413 // Update the native library path if needed
8414 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8415 if (nativeLibraryPath != null
8416 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8417 p.nativeLibraryPathString = nativeLibraryPath;
8418 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008419 // Update version code if needed
8420 if (pkg.mVersionCode != p.versionCode) {
8421 p.versionCode = pkg.mVersionCode;
8422 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008423 // Update signatures if needed.
8424 if (p.signatures.mSignatures == null) {
8425 p.signatures.assignSignatures(pkg.mSignatures);
8426 }
8427 // If this app defines a shared user id initialize
8428 // the shared user signatures as well.
8429 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8430 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8431 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008432 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8433 }
8434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008435 // Utility method that adds a PackageSetting to mPackages and
8436 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008437 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008438 SharedUserSetting sharedUser) {
8439 mPackages.put(name, p);
8440 if (sharedUser != null) {
8441 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8442 reportSettingsProblem(Log.ERROR,
8443 "Package " + p.name + " was user "
8444 + p.sharedUser + " but is now " + sharedUser
8445 + "; I am not changing its files so it will probably fail!");
8446 p.sharedUser.packages.remove(p);
8447 } else if (p.userId != sharedUser.userId) {
8448 reportSettingsProblem(Log.ERROR,
8449 "Package " + p.name + " was user id " + p.userId
8450 + " but is now user " + sharedUser
8451 + " with id " + sharedUser.userId
8452 + "; I am not changing its files so it will probably fail!");
8453 }
8454
8455 sharedUser.packages.add(p);
8456 p.sharedUser = sharedUser;
8457 p.userId = sharedUser.userId;
8458 }
8459 }
8460
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008461 /*
8462 * Update the shared user setting when a package using
8463 * specifying the shared user id is removed. The gids
8464 * associated with each permission of the deleted package
8465 * are removed from the shared user's gid list only if its
8466 * not in use by other permissions of packages in the
8467 * shared user setting.
8468 */
8469 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008470 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008471 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008472 return;
8473 }
8474 // No sharedUserId
8475 if (deletedPs.sharedUser == null) {
8476 return;
8477 }
8478 SharedUserSetting sus = deletedPs.sharedUser;
8479 // Update permissions
8480 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8481 boolean used = false;
8482 if (!sus.grantedPermissions.contains (eachPerm)) {
8483 continue;
8484 }
8485 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008486 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008487 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008488 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008489 used = true;
8490 break;
8491 }
8492 }
8493 if (!used) {
8494 // can safely delete this permission from list
8495 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008496 }
8497 }
8498 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008499 int newGids[] = globalGids;
8500 for (String eachPerm : sus.grantedPermissions) {
8501 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008502 if (bp != null) {
8503 newGids = appendInts(newGids, bp.gids);
8504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008505 }
8506 sus.gids = newGids;
8507 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008509 private int removePackageLP(String name) {
8510 PackageSetting p = mPackages.get(name);
8511 if (p != null) {
8512 mPackages.remove(name);
8513 if (p.sharedUser != null) {
8514 p.sharedUser.packages.remove(p);
8515 if (p.sharedUser.packages.size() == 0) {
8516 mSharedUsers.remove(p.sharedUser.name);
8517 removeUserIdLP(p.sharedUser.userId);
8518 return p.sharedUser.userId;
8519 }
8520 } else {
8521 removeUserIdLP(p.userId);
8522 return p.userId;
8523 }
8524 }
8525 return -1;
8526 }
8527
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008528 private void replacePackageLP(String name, PackageSetting newp) {
8529 PackageSetting p = mPackages.get(name);
8530 if (p != null) {
8531 if (p.sharedUser != null) {
8532 p.sharedUser.packages.remove(p);
8533 p.sharedUser.packages.add(newp);
8534 } else {
8535 replaceUserIdLP(p.userId, newp);
8536 }
8537 }
8538 mPackages.put(name, newp);
8539 }
8540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008541 private boolean addUserIdLP(int uid, Object obj, Object name) {
8542 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8543 return false;
8544 }
8545
8546 if (uid >= FIRST_APPLICATION_UID) {
8547 int N = mUserIds.size();
8548 final int index = uid - FIRST_APPLICATION_UID;
8549 while (index >= N) {
8550 mUserIds.add(null);
8551 N++;
8552 }
8553 if (mUserIds.get(index) != null) {
8554 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008555 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008556 + " name=" + name);
8557 return false;
8558 }
8559 mUserIds.set(index, obj);
8560 } else {
8561 if (mOtherUserIds.get(uid) != null) {
8562 reportSettingsProblem(Log.ERROR,
8563 "Adding duplicate shared id: " + uid
8564 + " name=" + name);
8565 return false;
8566 }
8567 mOtherUserIds.put(uid, obj);
8568 }
8569 return true;
8570 }
8571
8572 public Object getUserIdLP(int uid) {
8573 if (uid >= FIRST_APPLICATION_UID) {
8574 int N = mUserIds.size();
8575 final int index = uid - FIRST_APPLICATION_UID;
8576 return index < N ? mUserIds.get(index) : null;
8577 } else {
8578 return mOtherUserIds.get(uid);
8579 }
8580 }
8581
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008582 private Set<String> findPackagesWithFlag(int flag) {
8583 Set<String> ret = new HashSet<String>();
8584 for (PackageSetting ps : mPackages.values()) {
8585 // Has to match atleast all the flag bits set on flag
8586 if ((ps.pkgFlags & flag) == flag) {
8587 ret.add(ps.name);
8588 }
8589 }
8590 return ret;
8591 }
8592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008593 private void removeUserIdLP(int uid) {
8594 if (uid >= FIRST_APPLICATION_UID) {
8595 int N = mUserIds.size();
8596 final int index = uid - FIRST_APPLICATION_UID;
8597 if (index < N) mUserIds.set(index, null);
8598 } else {
8599 mOtherUserIds.remove(uid);
8600 }
8601 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008602
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008603 private void replaceUserIdLP(int uid, Object obj) {
8604 if (uid >= FIRST_APPLICATION_UID) {
8605 int N = mUserIds.size();
8606 final int index = uid - FIRST_APPLICATION_UID;
8607 if (index < N) mUserIds.set(index, obj);
8608 } else {
8609 mOtherUserIds.put(uid, obj);
8610 }
8611 }
8612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008613 void writeLP() {
8614 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8615
8616 // Keep the old settings around until we know the new ones have
8617 // been successfully written.
8618 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008619 // Presence of backup settings file indicates that we failed
8620 // to persist settings earlier. So preserve the older
8621 // backup for future reference since the current settings
8622 // might have been corrupted.
8623 if (!mBackupSettingsFilename.exists()) {
8624 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008625 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008626 return;
8627 }
8628 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008629 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008630 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008632 }
8633
8634 mPastSignatures.clear();
8635
8636 try {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008637 FileOutputStream fstr = new FileOutputStream(mSettingsFilename);
8638 BufferedOutputStream str = new BufferedOutputStream(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008639
8640 //XmlSerializer serializer = XmlUtils.serializerInstance();
8641 XmlSerializer serializer = new FastXmlSerializer();
8642 serializer.setOutput(str, "utf-8");
8643 serializer.startDocument(null, true);
8644 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8645
8646 serializer.startTag(null, "packages");
8647
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008648 serializer.startTag(null, "last-platform-version");
8649 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8650 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8651 serializer.endTag(null, "last-platform-version");
8652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008653 serializer.startTag(null, "permission-trees");
8654 for (BasePermission bp : mPermissionTrees.values()) {
8655 writePermission(serializer, bp);
8656 }
8657 serializer.endTag(null, "permission-trees");
8658
8659 serializer.startTag(null, "permissions");
8660 for (BasePermission bp : mPermissions.values()) {
8661 writePermission(serializer, bp);
8662 }
8663 serializer.endTag(null, "permissions");
8664
8665 for (PackageSetting pkg : mPackages.values()) {
8666 writePackage(serializer, pkg);
8667 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008669 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8670 writeDisabledSysPackage(serializer, pkg);
8671 }
8672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008673 serializer.startTag(null, "preferred-activities");
8674 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8675 serializer.startTag(null, "item");
8676 pa.writeToXml(serializer);
8677 serializer.endTag(null, "item");
8678 }
8679 serializer.endTag(null, "preferred-activities");
8680
8681 for (SharedUserSetting usr : mSharedUsers.values()) {
8682 serializer.startTag(null, "shared-user");
8683 serializer.attribute(null, "name", usr.name);
8684 serializer.attribute(null, "userId",
8685 Integer.toString(usr.userId));
8686 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8687 serializer.startTag(null, "perms");
8688 for (String name : usr.grantedPermissions) {
8689 serializer.startTag(null, "item");
8690 serializer.attribute(null, "name", name);
8691 serializer.endTag(null, "item");
8692 }
8693 serializer.endTag(null, "perms");
8694 serializer.endTag(null, "shared-user");
8695 }
8696
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008697 if (mPackagesToBeCleaned.size() > 0) {
8698 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8699 serializer.startTag(null, "cleaning-package");
8700 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8701 serializer.endTag(null, "cleaning-package");
8702 }
8703 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008704
8705 if (mRenamedPackages.size() > 0) {
8706 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8707 serializer.startTag(null, "renamed-package");
8708 serializer.attribute(null, "new", e.getKey());
8709 serializer.attribute(null, "old", e.getValue());
8710 serializer.endTag(null, "renamed-package");
8711 }
8712 }
8713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008714 serializer.endTag(null, "packages");
8715
8716 serializer.endDocument();
8717
8718 str.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008719 FileUtils.sync(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008720 str.close();
8721
8722 // New settings successfully written, old ones are no longer
8723 // needed.
8724 mBackupSettingsFilename.delete();
8725 FileUtils.setPermissions(mSettingsFilename.toString(),
8726 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8727 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8728 |FileUtils.S_IROTH,
8729 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008730
8731 // Write package list file now, use a JournaledFile.
8732 //
8733 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8734 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8735
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008736 fstr = new FileOutputStream(journal.chooseForWrite());
8737 str = new BufferedOutputStream(fstr);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008738 try {
8739 StringBuilder sb = new StringBuilder();
8740 for (PackageSetting pkg : mPackages.values()) {
8741 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008742 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008743 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8744
8745 // Avoid any application that has a space in its path
8746 // or that is handled by the system.
8747 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8748 continue;
8749
8750 // we store on each line the following information for now:
8751 //
8752 // pkgName - package name
8753 // userId - application-specific user id
8754 // debugFlag - 0 or 1 if the package is debuggable.
8755 // dataPath - path to package's data path
8756 //
8757 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8758 //
8759 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8760 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8761 // system/core/run-as/run-as.c
8762 //
8763 sb.setLength(0);
8764 sb.append(ai.packageName);
8765 sb.append(" ");
8766 sb.append((int)ai.uid);
8767 sb.append(isDebug ? " 1 " : " 0 ");
8768 sb.append(dataPath);
8769 sb.append("\n");
8770 str.write(sb.toString().getBytes());
8771 }
8772 str.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008773 FileUtils.sync(fstr);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008774 str.close();
8775 journal.commit();
8776 }
8777 catch (Exception e) {
8778 journal.rollback();
8779 }
8780
8781 FileUtils.setPermissions(mPackageListFilename.toString(),
8782 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8783 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8784 |FileUtils.S_IROTH,
8785 -1, -1);
8786
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008787 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008788
8789 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008790 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 -08008791 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008792 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 -08008793 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008794 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008795 if (mSettingsFilename.exists()) {
8796 if (!mSettingsFilename.delete()) {
8797 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8798 }
8799 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008800 //Debug.stopMethodTracing();
8801 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008802
8803 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008804 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008805 serializer.startTag(null, "updated-package");
8806 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008807 if (pkg.realName != null) {
8808 serializer.attribute(null, "realName", pkg.realName);
8809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008810 serializer.attribute(null, "codePath", pkg.codePathString);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008811 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8812 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8813 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008814 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008815 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8816 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8817 }
Kenny Root85387d72010-08-26 10:13:11 -07008818 if (pkg.nativeLibraryPathString != null) {
8819 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008821 if (pkg.sharedUser == null) {
8822 serializer.attribute(null, "userId",
8823 Integer.toString(pkg.userId));
8824 } else {
8825 serializer.attribute(null, "sharedUserId",
8826 Integer.toString(pkg.userId));
8827 }
8828 serializer.startTag(null, "perms");
8829 if (pkg.sharedUser == null) {
8830 // If this is a shared user, the permissions will
8831 // be written there. We still need to write an
8832 // empty permissions list so permissionsFixed will
8833 // be set.
8834 for (final String name : pkg.grantedPermissions) {
8835 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008836 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008837 // We only need to write signature or system permissions but this wont
8838 // match the semantics of grantedPermissions. So write all permissions.
8839 serializer.startTag(null, "item");
8840 serializer.attribute(null, "name", name);
8841 serializer.endTag(null, "item");
8842 }
8843 }
8844 }
8845 serializer.endTag(null, "perms");
8846 serializer.endTag(null, "updated-package");
8847 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008848
8849 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008850 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008851 serializer.startTag(null, "package");
8852 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008853 if (pkg.realName != null) {
8854 serializer.attribute(null, "realName", pkg.realName);
8855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008856 serializer.attribute(null, "codePath", pkg.codePathString);
8857 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8858 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8859 }
Kenny Root85387d72010-08-26 10:13:11 -07008860 if (pkg.nativeLibraryPathString != null) {
8861 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8862 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008863 serializer.attribute(null, "flags",
8864 Integer.toString(pkg.pkgFlags));
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008865 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8866 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8867 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008868 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008869 if (pkg.sharedUser == null) {
8870 serializer.attribute(null, "userId",
8871 Integer.toString(pkg.userId));
8872 } else {
8873 serializer.attribute(null, "sharedUserId",
8874 Integer.toString(pkg.userId));
8875 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008876 if (pkg.uidError) {
8877 serializer.attribute(null, "uidError", "true");
8878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008879 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8880 serializer.attribute(null, "enabled",
8881 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8882 ? "true" : "false");
8883 }
8884 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8885 serializer.attribute(null, "installStatus", "false");
8886 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008887 if (pkg.installerPackageName != null) {
8888 serializer.attribute(null, "installer", pkg.installerPackageName);
8889 }
Kenny Root6c4d9042010-11-19 12:48:05 -08008890 if (pkg.obbPathStrings != null && pkg.obbPathStrings.length > 0) {
8891 int N = pkg.obbPathStrings.length;
8892 serializer.startTag(null, "obbs");
8893 for (int i = 0; i < N; i++) {
8894 serializer.startTag(null, "obb");
8895 serializer.attribute(null, "path", pkg.obbPathStrings[i]);
8896 serializer.endTag(null, "obb");
8897 }
8898 serializer.endTag(null, "obbs");
Kenny Root93565c4b2010-06-18 15:46:06 -07008899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008900 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8901 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8902 serializer.startTag(null, "perms");
8903 if (pkg.sharedUser == null) {
8904 // If this is a shared user, the permissions will
8905 // be written there. We still need to write an
8906 // empty permissions list so permissionsFixed will
8907 // be set.
8908 for (final String name : pkg.grantedPermissions) {
8909 serializer.startTag(null, "item");
8910 serializer.attribute(null, "name", name);
8911 serializer.endTag(null, "item");
8912 }
8913 }
8914 serializer.endTag(null, "perms");
8915 }
8916 if (pkg.disabledComponents.size() > 0) {
8917 serializer.startTag(null, "disabled-components");
8918 for (final String name : pkg.disabledComponents) {
8919 serializer.startTag(null, "item");
8920 serializer.attribute(null, "name", name);
8921 serializer.endTag(null, "item");
8922 }
8923 serializer.endTag(null, "disabled-components");
8924 }
8925 if (pkg.enabledComponents.size() > 0) {
8926 serializer.startTag(null, "enabled-components");
8927 for (final String name : pkg.enabledComponents) {
8928 serializer.startTag(null, "item");
8929 serializer.attribute(null, "name", name);
8930 serializer.endTag(null, "item");
8931 }
8932 serializer.endTag(null, "enabled-components");
8933 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008935 serializer.endTag(null, "package");
8936 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008938 void writePermission(XmlSerializer serializer, BasePermission bp)
8939 throws XmlPullParserException, java.io.IOException {
8940 if (bp.type != BasePermission.TYPE_BUILTIN
8941 && bp.sourcePackage != null) {
8942 serializer.startTag(null, "item");
8943 serializer.attribute(null, "name", bp.name);
8944 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008945 if (bp.protectionLevel !=
8946 PermissionInfo.PROTECTION_NORMAL) {
8947 serializer.attribute(null, "protection",
8948 Integer.toString(bp.protectionLevel));
8949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008950 if (DEBUG_SETTINGS) Log.v(TAG,
8951 "Writing perm: name=" + bp.name + " type=" + bp.type);
8952 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8953 PermissionInfo pi = bp.perm != null ? bp.perm.info
8954 : bp.pendingInfo;
8955 if (pi != null) {
8956 serializer.attribute(null, "type", "dynamic");
8957 if (pi.icon != 0) {
8958 serializer.attribute(null, "icon",
8959 Integer.toString(pi.icon));
8960 }
8961 if (pi.nonLocalizedLabel != null) {
8962 serializer.attribute(null, "label",
8963 pi.nonLocalizedLabel.toString());
8964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008965 }
8966 }
8967 serializer.endTag(null, "item");
8968 }
8969 }
8970
8971 String getReadMessagesLP() {
8972 return mReadMessages.toString();
8973 }
8974
Oscar Montemayora8529f62009-11-18 10:14:20 -08008975 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008976 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8977 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008978 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008979 while(its.hasNext()) {
8980 String key = its.next();
8981 PackageSetting ps = mPackages.get(key);
8982 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008983 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008984 }
8985 }
8986 return ret;
8987 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008989 boolean readLP() {
8990 FileInputStream str = null;
8991 if (mBackupSettingsFilename.exists()) {
8992 try {
8993 str = new FileInputStream(mBackupSettingsFilename);
8994 mReadMessages.append("Reading from backup settings file\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07008995 reportSettingsProblem(Log.INFO, "Need to read from backup settings file");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008996 if (mSettingsFilename.exists()) {
8997 // If both the backup and settings file exist, we
8998 // ignore the settings since it might have been
8999 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009000 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07009001 mSettingsFilename.delete();
9002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009003 } catch (java.io.IOException e) {
9004 // We'll try for the normal settings file.
9005 }
9006 }
9007
9008 mPastSignatures.clear();
9009
9010 try {
9011 if (str == null) {
9012 if (!mSettingsFilename.exists()) {
9013 mReadMessages.append("No settings file found\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07009014 reportSettingsProblem(Log.INFO, "No settings file; creating initial state");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009015 return false;
9016 }
9017 str = new FileInputStream(mSettingsFilename);
9018 }
9019 XmlPullParser parser = Xml.newPullParser();
9020 parser.setInput(str, null);
9021
9022 int type;
9023 while ((type=parser.next()) != XmlPullParser.START_TAG
9024 && type != XmlPullParser.END_DOCUMENT) {
9025 ;
9026 }
9027
9028 if (type != XmlPullParser.START_TAG) {
9029 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07009030 reportSettingsProblem(Log.WARN, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009031 return false;
9032 }
9033
9034 int outerDepth = parser.getDepth();
9035 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9036 && (type != XmlPullParser.END_TAG
9037 || parser.getDepth() > outerDepth)) {
9038 if (type == XmlPullParser.END_TAG
9039 || type == XmlPullParser.TEXT) {
9040 continue;
9041 }
9042
9043 String tagName = parser.getName();
9044 if (tagName.equals("package")) {
9045 readPackageLP(parser);
9046 } else if (tagName.equals("permissions")) {
9047 readPermissionsLP(mPermissions, parser);
9048 } else if (tagName.equals("permission-trees")) {
9049 readPermissionsLP(mPermissionTrees, parser);
9050 } else if (tagName.equals("shared-user")) {
9051 readSharedUserLP(parser);
9052 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08009053 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009054 } else if (tagName.equals("preferred-activities")) {
9055 readPreferredActivitiesLP(parser);
9056 } else if(tagName.equals("updated-package")) {
9057 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009058 } else if (tagName.equals("cleaning-package")) {
9059 String name = parser.getAttributeValue(null, "name");
9060 if (name != null) {
9061 mPackagesToBeCleaned.add(name);
9062 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009063 } else if (tagName.equals("renamed-package")) {
9064 String nname = parser.getAttributeValue(null, "new");
9065 String oname = parser.getAttributeValue(null, "old");
9066 if (nname != null && oname != null) {
9067 mRenamedPackages.put(nname, oname);
9068 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009069 } else if (tagName.equals("last-platform-version")) {
9070 mInternalSdkPlatform = mExternalSdkPlatform = 0;
9071 try {
9072 String internal = parser.getAttributeValue(null, "internal");
9073 if (internal != null) {
9074 mInternalSdkPlatform = Integer.parseInt(internal);
9075 }
9076 String external = parser.getAttributeValue(null, "external");
9077 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01009078 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009079 }
9080 } catch (NumberFormatException e) {
9081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009082 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009083 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009084 + parser.getName());
9085 XmlUtils.skipCurrentTag(parser);
9086 }
9087 }
9088
9089 str.close();
9090
9091 } catch(XmlPullParserException e) {
9092 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackbornefb58102010-10-14 16:47:34 -07009093 reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009094 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009095
9096 } catch(java.io.IOException e) {
9097 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackbornefb58102010-10-14 16:47:34 -07009098 reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009099 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009100
9101 }
9102
9103 int N = mPendingPackages.size();
9104 for (int i=0; i<N; i++) {
9105 final PendingPackage pp = mPendingPackages.get(i);
9106 Object idObj = getUserIdLP(pp.sharedId);
9107 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009108 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07009109 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
9110 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009111 if (p == null) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07009112 reportSettingsProblem(Log.WARN, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009113 + pp.name);
9114 continue;
9115 }
9116 p.copyFrom(pp);
9117 } else if (idObj != null) {
9118 String msg = "Bad package setting: package " + pp.name
9119 + " has shared uid " + pp.sharedId
9120 + " that is not a shared uid\n";
9121 mReadMessages.append(msg);
Dianne Hackbornefb58102010-10-14 16:47:34 -07009122 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009123 } else {
9124 String msg = "Bad package setting: package " + pp.name
9125 + " has shared uid " + pp.sharedId
9126 + " that is not defined\n";
9127 mReadMessages.append(msg);
Dianne Hackbornefb58102010-10-14 16:47:34 -07009128 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009129 }
9130 }
9131 mPendingPackages.clear();
9132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009133 mReadMessages.append("Read completed successfully: "
9134 + mPackages.size() + " packages, "
9135 + mSharedUsers.size() + " shared uids\n");
9136
9137 return true;
9138 }
9139
9140 private int readInt(XmlPullParser parser, String ns, String name,
9141 int defValue) {
9142 String v = parser.getAttributeValue(ns, name);
9143 try {
9144 if (v == null) {
9145 return defValue;
9146 }
9147 return Integer.parseInt(v);
9148 } catch (NumberFormatException e) {
9149 reportSettingsProblem(Log.WARN,
9150 "Error in package manager settings: attribute " +
9151 name + " has bad integer value " + v + " at "
9152 + parser.getPositionDescription());
9153 }
9154 return defValue;
9155 }
9156
9157 private void readPermissionsLP(HashMap<String, BasePermission> out,
9158 XmlPullParser parser)
9159 throws IOException, XmlPullParserException {
9160 int outerDepth = parser.getDepth();
9161 int type;
9162 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9163 && (type != XmlPullParser.END_TAG
9164 || parser.getDepth() > outerDepth)) {
9165 if (type == XmlPullParser.END_TAG
9166 || type == XmlPullParser.TEXT) {
9167 continue;
9168 }
9169
9170 String tagName = parser.getName();
9171 if (tagName.equals("item")) {
9172 String name = parser.getAttributeValue(null, "name");
9173 String sourcePackage = parser.getAttributeValue(null, "package");
9174 String ptype = parser.getAttributeValue(null, "type");
9175 if (name != null && sourcePackage != null) {
9176 boolean dynamic = "dynamic".equals(ptype);
9177 BasePermission bp = new BasePermission(name, sourcePackage,
9178 dynamic
9179 ? BasePermission.TYPE_DYNAMIC
9180 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009181 bp.protectionLevel = readInt(parser, null, "protection",
9182 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009183 if (dynamic) {
9184 PermissionInfo pi = new PermissionInfo();
9185 pi.packageName = sourcePackage.intern();
9186 pi.name = name.intern();
9187 pi.icon = readInt(parser, null, "icon", 0);
9188 pi.nonLocalizedLabel = parser.getAttributeValue(
9189 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009190 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009191 bp.pendingInfo = pi;
9192 }
9193 out.put(bp.name, bp);
9194 } else {
9195 reportSettingsProblem(Log.WARN,
9196 "Error in package manager settings: permissions has"
9197 + " no name at " + parser.getPositionDescription());
9198 }
9199 } else {
9200 reportSettingsProblem(Log.WARN,
9201 "Unknown element reading permissions: "
9202 + parser.getName() + " at "
9203 + parser.getPositionDescription());
9204 }
9205 XmlUtils.skipCurrentTag(parser);
9206 }
9207 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009209 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009210 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009211 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009212 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009213 String codePathStr = parser.getAttributeValue(null, "codePath");
9214 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07009215 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009216 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009217 resourcePathStr = codePathStr;
9218 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009219 String version = parser.getAttributeValue(null, "version");
9220 int versionCode = 0;
9221 if (version != null) {
9222 try {
9223 versionCode = Integer.parseInt(version);
9224 } catch (NumberFormatException e) {
9225 }
9226 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009228 int pkgFlags = 0;
9229 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07009230 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
9231 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009232 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009233 if (timeStampStr != null) {
9234 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009235 long timeStamp = Long.parseLong(timeStampStr, 16);
Kenny Root7d794fb2010-09-13 16:29:49 -07009236 ps.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009237 } catch (NumberFormatException e) {
9238 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009239 } else {
9240 timeStampStr = parser.getAttributeValue(null, "ts");
9241 if (timeStampStr != null) {
9242 try {
9243 long timeStamp = Long.parseLong(timeStampStr);
9244 ps.setTimeStamp(timeStamp);
9245 } catch (NumberFormatException e) {
9246 }
9247 }
9248 }
9249 timeStampStr = parser.getAttributeValue(null, "it");
9250 if (timeStampStr != null) {
9251 try {
9252 ps.firstInstallTime = Long.parseLong(timeStampStr, 16);
9253 } catch (NumberFormatException e) {
9254 }
9255 }
9256 timeStampStr = parser.getAttributeValue(null, "ut");
9257 if (timeStampStr != null) {
9258 try {
9259 ps.lastUpdateTime = Long.parseLong(timeStampStr, 16);
9260 } catch (NumberFormatException e) {
9261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009262 }
9263 String idStr = parser.getAttributeValue(null, "userId");
9264 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
9265 if(ps.userId <= 0) {
9266 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9267 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
9268 }
9269 int outerDepth = parser.getDepth();
9270 int type;
9271 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9272 && (type != XmlPullParser.END_TAG
9273 || parser.getDepth() > outerDepth)) {
9274 if (type == XmlPullParser.END_TAG
9275 || type == XmlPullParser.TEXT) {
9276 continue;
9277 }
9278
9279 String tagName = parser.getName();
9280 if (tagName.equals("perms")) {
9281 readGrantedPermissionsLP(parser,
9282 ps.grantedPermissions);
9283 } else {
9284 reportSettingsProblem(Log.WARN,
9285 "Unknown element under <updated-package>: "
9286 + parser.getName());
9287 XmlUtils.skipCurrentTag(parser);
9288 }
9289 }
9290 mDisabledSysPackages.put(name, ps);
9291 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009293 private void readPackageLP(XmlPullParser parser)
9294 throws XmlPullParserException, IOException {
9295 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009296 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009297 String idStr = null;
9298 String sharedIdStr = null;
9299 String codePathStr = null;
9300 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07009301 String nativeLibraryPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009302 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009303 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009304 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009305 int pkgFlags = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009306 long timeStamp = 0;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009307 long firstInstallTime = 0;
9308 long lastUpdateTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009309 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009310 String version = null;
9311 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009312 try {
9313 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009314 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009315 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009316 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009317 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9318 codePathStr = parser.getAttributeValue(null, "codePath");
9319 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07009320 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009321 version = parser.getAttributeValue(null, "version");
9322 if (version != null) {
9323 try {
9324 versionCode = Integer.parseInt(version);
9325 } catch (NumberFormatException e) {
9326 }
9327 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009328 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009329
9330 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009331 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009332 try {
9333 pkgFlags = Integer.parseInt(systemStr);
9334 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009335 }
9336 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009337 // For backward compatibility
9338 systemStr = parser.getAttributeValue(null, "system");
9339 if (systemStr != null) {
9340 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9341 } else {
9342 // Old settings that don't specify system... just treat
9343 // them as system, good enough.
9344 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9345 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009346 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009347 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009348 if (timeStampStr != null) {
9349 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009350 timeStamp = Long.parseLong(timeStampStr, 16);
9351 } catch (NumberFormatException e) {
9352 }
9353 } else {
9354 timeStampStr = parser.getAttributeValue(null, "ts");
9355 if (timeStampStr != null) {
9356 try {
9357 timeStamp = Long.parseLong(timeStampStr);
9358 } catch (NumberFormatException e) {
9359 }
9360 }
9361 }
9362 timeStampStr = parser.getAttributeValue(null, "it");
9363 if (timeStampStr != null) {
9364 try {
9365 firstInstallTime = Long.parseLong(timeStampStr, 16);
9366 } catch (NumberFormatException e) {
9367 }
9368 }
9369 timeStampStr = parser.getAttributeValue(null, "ut");
9370 if (timeStampStr != null) {
9371 try {
9372 lastUpdateTime = Long.parseLong(timeStampStr, 16);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009373 } catch (NumberFormatException e) {
9374 }
9375 }
9376 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9377 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9378 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9379 if (resourcePathStr == null) {
9380 resourcePathStr = codePathStr;
9381 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009382 if (realName != null) {
9383 realName = realName.intern();
9384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009385 if (name == null) {
9386 reportSettingsProblem(Log.WARN,
9387 "Error in package manager settings: <package> has no name at "
9388 + parser.getPositionDescription());
9389 } else if (codePathStr == null) {
9390 reportSettingsProblem(Log.WARN,
9391 "Error in package manager settings: <package> has no codePath at "
9392 + parser.getPositionDescription());
9393 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009394 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9395 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9396 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009397 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9398 + ": userId=" + userId + " pkg=" + packageSetting);
9399 if (packageSetting == null) {
9400 reportSettingsProblem(Log.ERROR,
9401 "Failure adding uid " + userId
9402 + " while parsing settings at "
9403 + parser.getPositionDescription());
9404 } else {
Kenny Root7d794fb2010-09-13 16:29:49 -07009405 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009406 packageSetting.firstInstallTime = firstInstallTime;
9407 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009408 }
9409 } else if (sharedIdStr != null) {
9410 userId = sharedIdStr != null
9411 ? Integer.parseInt(sharedIdStr) : 0;
9412 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009413 packageSetting = new PendingPackage(name.intern(), realName,
9414 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009415 nativeLibraryPathStr, userId, versionCode, pkgFlags);
Kenny Root7d794fb2010-09-13 16:29:49 -07009416 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009417 packageSetting.firstInstallTime = firstInstallTime;
9418 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009419 mPendingPackages.add((PendingPackage) packageSetting);
9420 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9421 + ": sharedUserId=" + userId + " pkg="
9422 + packageSetting);
9423 } else {
9424 reportSettingsProblem(Log.WARN,
9425 "Error in package manager settings: package "
9426 + name + " has bad sharedId " + sharedIdStr
9427 + " at " + parser.getPositionDescription());
9428 }
9429 } else {
9430 reportSettingsProblem(Log.WARN,
9431 "Error in package manager settings: package "
9432 + name + " has bad userId " + idStr + " at "
9433 + parser.getPositionDescription());
9434 }
9435 } catch (NumberFormatException e) {
9436 reportSettingsProblem(Log.WARN,
9437 "Error in package manager settings: package "
9438 + name + " has bad userId " + idStr + " at "
9439 + parser.getPositionDescription());
9440 }
9441 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009442 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009443 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009444 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009445 final String enabledStr = parser.getAttributeValue(null, "enabled");
9446 if (enabledStr != null) {
9447 if (enabledStr.equalsIgnoreCase("true")) {
9448 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9449 } else if (enabledStr.equalsIgnoreCase("false")) {
9450 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9451 } else if (enabledStr.equalsIgnoreCase("default")) {
9452 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9453 } else {
9454 reportSettingsProblem(Log.WARN,
9455 "Error in package manager settings: package "
9456 + name + " has bad enabled value: " + idStr
9457 + " at " + parser.getPositionDescription());
9458 }
9459 } else {
9460 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9461 }
9462 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9463 if (installStatusStr != null) {
9464 if (installStatusStr.equalsIgnoreCase("false")) {
9465 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9466 } else {
9467 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9468 }
9469 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009471 int outerDepth = parser.getDepth();
9472 int type;
9473 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9474 && (type != XmlPullParser.END_TAG
9475 || parser.getDepth() > outerDepth)) {
9476 if (type == XmlPullParser.END_TAG
9477 || type == XmlPullParser.TEXT) {
9478 continue;
9479 }
9480
9481 String tagName = parser.getName();
9482 if (tagName.equals("disabled-components")) {
9483 readDisabledComponentsLP(packageSetting, parser);
9484 } else if (tagName.equals("enabled-components")) {
9485 readEnabledComponentsLP(packageSetting, parser);
9486 } else if (tagName.equals("sigs")) {
9487 packageSetting.signatures.readXml(parser, mPastSignatures);
9488 } else if (tagName.equals("perms")) {
9489 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009490 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009491 packageSetting.permissionsFixed = true;
Kenny Root6c4d9042010-11-19 12:48:05 -08009492 } else if (tagName.equals("obbs")) {
9493 readObbPathsLP(packageSetting, parser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009494 } else {
9495 reportSettingsProblem(Log.WARN,
9496 "Unknown element under <package>: "
9497 + parser.getName());
9498 XmlUtils.skipCurrentTag(parser);
9499 }
9500 }
9501 } else {
9502 XmlUtils.skipCurrentTag(parser);
9503 }
9504 }
9505
9506 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9507 XmlPullParser parser)
9508 throws IOException, XmlPullParserException {
9509 int outerDepth = parser.getDepth();
9510 int type;
9511 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9512 && (type != XmlPullParser.END_TAG
9513 || parser.getDepth() > outerDepth)) {
9514 if (type == XmlPullParser.END_TAG
9515 || type == XmlPullParser.TEXT) {
9516 continue;
9517 }
9518
9519 String tagName = parser.getName();
9520 if (tagName.equals("item")) {
9521 String name = parser.getAttributeValue(null, "name");
9522 if (name != null) {
9523 packageSetting.disabledComponents.add(name.intern());
9524 } else {
9525 reportSettingsProblem(Log.WARN,
9526 "Error in package manager settings: <disabled-components> has"
9527 + " no name at " + parser.getPositionDescription());
9528 }
9529 } else {
9530 reportSettingsProblem(Log.WARN,
9531 "Unknown element under <disabled-components>: "
9532 + parser.getName());
9533 }
9534 XmlUtils.skipCurrentTag(parser);
9535 }
9536 }
9537
9538 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9539 XmlPullParser parser)
9540 throws IOException, XmlPullParserException {
9541 int outerDepth = parser.getDepth();
9542 int type;
9543 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9544 && (type != XmlPullParser.END_TAG
9545 || parser.getDepth() > outerDepth)) {
9546 if (type == XmlPullParser.END_TAG
9547 || type == XmlPullParser.TEXT) {
9548 continue;
9549 }
9550
9551 String tagName = parser.getName();
9552 if (tagName.equals("item")) {
9553 String name = parser.getAttributeValue(null, "name");
9554 if (name != null) {
9555 packageSetting.enabledComponents.add(name.intern());
9556 } else {
9557 reportSettingsProblem(Log.WARN,
9558 "Error in package manager settings: <enabled-components> has"
9559 + " no name at " + parser.getPositionDescription());
9560 }
9561 } else {
9562 reportSettingsProblem(Log.WARN,
9563 "Unknown element under <enabled-components>: "
9564 + parser.getName());
9565 }
9566 XmlUtils.skipCurrentTag(parser);
9567 }
9568 }
9569
9570 private void readSharedUserLP(XmlPullParser parser)
9571 throws XmlPullParserException, IOException {
9572 String name = null;
9573 String idStr = null;
9574 int pkgFlags = 0;
9575 SharedUserSetting su = null;
9576 try {
9577 name = parser.getAttributeValue(null, "name");
9578 idStr = parser.getAttributeValue(null, "userId");
9579 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9580 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9581 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9582 }
9583 if (name == null) {
9584 reportSettingsProblem(Log.WARN,
9585 "Error in package manager settings: <shared-user> has no name at "
9586 + parser.getPositionDescription());
9587 } else if (userId == 0) {
9588 reportSettingsProblem(Log.WARN,
9589 "Error in package manager settings: shared-user "
9590 + name + " has bad userId " + idStr + " at "
9591 + parser.getPositionDescription());
9592 } else {
9593 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9594 reportSettingsProblem(Log.ERROR,
9595 "Occurred while parsing settings at "
9596 + parser.getPositionDescription());
9597 }
9598 }
9599 } catch (NumberFormatException e) {
9600 reportSettingsProblem(Log.WARN,
9601 "Error in package manager settings: package "
9602 + name + " has bad userId " + idStr + " at "
9603 + parser.getPositionDescription());
9604 };
9605
9606 if (su != null) {
9607 int outerDepth = parser.getDepth();
9608 int type;
9609 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9610 && (type != XmlPullParser.END_TAG
9611 || parser.getDepth() > outerDepth)) {
9612 if (type == XmlPullParser.END_TAG
9613 || type == XmlPullParser.TEXT) {
9614 continue;
9615 }
9616
9617 String tagName = parser.getName();
9618 if (tagName.equals("sigs")) {
9619 su.signatures.readXml(parser, mPastSignatures);
9620 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009621 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009622 } else {
9623 reportSettingsProblem(Log.WARN,
9624 "Unknown element under <shared-user>: "
9625 + parser.getName());
9626 XmlUtils.skipCurrentTag(parser);
9627 }
9628 }
9629
9630 } else {
9631 XmlUtils.skipCurrentTag(parser);
9632 }
9633 }
9634
9635 private void readGrantedPermissionsLP(XmlPullParser parser,
9636 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9637 int outerDepth = parser.getDepth();
9638 int type;
9639 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9640 && (type != XmlPullParser.END_TAG
9641 || parser.getDepth() > outerDepth)) {
9642 if (type == XmlPullParser.END_TAG
9643 || type == XmlPullParser.TEXT) {
9644 continue;
9645 }
9646
9647 String tagName = parser.getName();
9648 if (tagName.equals("item")) {
9649 String name = parser.getAttributeValue(null, "name");
9650 if (name != null) {
9651 outPerms.add(name.intern());
9652 } else {
9653 reportSettingsProblem(Log.WARN,
9654 "Error in package manager settings: <perms> has"
9655 + " no name at " + parser.getPositionDescription());
9656 }
9657 } else {
9658 reportSettingsProblem(Log.WARN,
9659 "Unknown element under <perms>: "
9660 + parser.getName());
9661 }
9662 XmlUtils.skipCurrentTag(parser);
9663 }
9664 }
9665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009666 private void readPreferredActivitiesLP(XmlPullParser parser)
9667 throws XmlPullParserException, IOException {
9668 int outerDepth = parser.getDepth();
9669 int type;
9670 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9671 && (type != XmlPullParser.END_TAG
9672 || parser.getDepth() > outerDepth)) {
9673 if (type == XmlPullParser.END_TAG
9674 || type == XmlPullParser.TEXT) {
9675 continue;
9676 }
9677
9678 String tagName = parser.getName();
9679 if (tagName.equals("item")) {
9680 PreferredActivity pa = new PreferredActivity(parser);
9681 if (pa.mParseError == null) {
9682 mPreferredActivities.addFilter(pa);
9683 } else {
9684 reportSettingsProblem(Log.WARN,
9685 "Error in package manager settings: <preferred-activity> "
9686 + pa.mParseError + " at "
9687 + parser.getPositionDescription());
9688 }
9689 } else {
9690 reportSettingsProblem(Log.WARN,
9691 "Unknown element under <preferred-activities>: "
9692 + parser.getName());
9693 XmlUtils.skipCurrentTag(parser);
9694 }
9695 }
9696 }
9697
Kenny Root6c4d9042010-11-19 12:48:05 -08009698 private void readObbPathsLP(PackageSettingBase packageSetting, XmlPullParser parser)
9699 throws XmlPullParserException, IOException {
9700 final List<String> obbPaths = new ArrayList<String>();
9701 final int outerDepth = parser.getDepth();
9702 int type;
9703 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
9704 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
9705 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
9706 continue;
9707 }
9708
9709 final String tagName = parser.getName();
9710 if (tagName.equals("obb")) {
9711 final String path = parser.getAttributeValue(null, "path");
9712 obbPaths.add(path);
9713 } else {
9714 reportSettingsProblem(Log.WARN, "Unknown element under <obbs>: "
9715 + parser.getName());
9716 }
9717 XmlUtils.skipCurrentTag(parser);
9718 }
9719 if (obbPaths.size() == 0) {
9720 return;
9721 } else {
9722 packageSetting.obbPathStrings = obbPaths.toArray(new String[obbPaths.size()]);
9723 }
9724 }
9725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009726 // Returns -1 if we could not find an available UserId to assign
9727 private int newUserIdLP(Object obj) {
9728 // Let's be stupidly inefficient for now...
9729 final int N = mUserIds.size();
9730 for (int i=0; i<N; i++) {
9731 if (mUserIds.get(i) == null) {
9732 mUserIds.set(i, obj);
9733 return FIRST_APPLICATION_UID + i;
9734 }
9735 }
9736
9737 // None left?
9738 if (N >= MAX_APPLICATION_UIDS) {
9739 return -1;
9740 }
9741
9742 mUserIds.add(obj);
9743 return FIRST_APPLICATION_UID + N;
9744 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009746 public PackageSetting getDisabledSystemPkg(String name) {
9747 synchronized(mPackages) {
9748 PackageSetting ps = mDisabledSysPackages.get(name);
9749 return ps;
9750 }
9751 }
9752
9753 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009754 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9755 return true;
9756 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009757 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9758 if (Config.LOGV) {
9759 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9760 + " componentName = " + componentInfo.name);
9761 Log.v(TAG, "enabledComponents: "
9762 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9763 Log.v(TAG, "disabledComponents: "
9764 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9765 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009766 if (packageSettings == null) {
9767 if (false) {
9768 Log.w(TAG, "WAITING FOR DEBUGGER");
9769 Debug.waitForDebugger();
9770 Log.i(TAG, "We will crash!");
9771 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009772 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009773 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009774 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9775 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9776 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9777 return false;
9778 }
9779 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9780 return true;
9781 }
9782 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9783 return false;
9784 }
9785 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009786 }
9787 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009788
9789 // ------- apps on sdcard specific code -------
9790 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009791 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9792 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9793 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009794 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009795
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009796 private String getEncryptKey() {
9797 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009798 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9799 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009800 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009801 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9802 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009803 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009804 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009805 return null;
9806 }
9807 }
9808 return sdEncKey;
9809 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009810 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009811 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009812 } catch (IOException ioe) {
9813 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9814 + ioe);
9815 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009816 }
Rich Cannings8d578832010-09-09 15:12:40 -07009817
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009818 }
9819
Kenny Rootc78a8072010-07-27 15:18:38 -07009820 /* package */ static String getTempContainerId() {
9821 int tmpIdx = 1;
9822 String list[] = PackageHelper.getSecureContainerList();
9823 if (list != null) {
9824 for (final String name : list) {
9825 // Ignore null and non-temporary container entries
9826 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9827 continue;
9828 }
9829
9830 String subStr = name.substring(mTempContainerPrefix.length());
9831 try {
9832 int cid = Integer.parseInt(subStr);
9833 if (cid >= tmpIdx) {
9834 tmpIdx = cid + 1;
9835 }
9836 } catch (NumberFormatException e) {
9837 }
9838 }
9839 }
9840 return mTempContainerPrefix + tmpIdx;
9841 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009842
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009843 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009844 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009845 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009846 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9847 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9848 throw new SecurityException("Media status can only be updated by the system");
9849 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009850 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009851 Log.i(TAG, "Updating external media status from " +
9852 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9853 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009854 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9855 mediaStatus+", mMediaMounted=" + mMediaMounted);
9856 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009857 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9858 reportStatus ? 1 : 0, -1);
9859 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009860 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009861 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009862 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009863 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009864 // Queue up an async operation since the package installation may take a little while.
9865 mHandler.post(new Runnable() {
9866 public void run() {
9867 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009868 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009869 }
9870 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009871 }
9872
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009873 /*
9874 * Collect information of applications on external media, map them
9875 * against existing containers and update information based on current
9876 * mount status. Please note that we always have to report status
9877 * if reportStatus has been set to true especially when unloading packages.
9878 */
9879 private void updateExternalMediaStatusInner(boolean mediaStatus,
9880 boolean reportStatus) {
9881 // Collection of uids
9882 int uidArr[] = null;
9883 // Collection of stale containers
9884 HashSet<String> removeCids = new HashSet<String>();
9885 // Collection of packages on external media with valid containers.
9886 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9887 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009888 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009889 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009890 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009891 } else {
9892 // Process list of secure containers and categorize them
9893 // as active or stale based on their package internal state.
9894 int uidList[] = new int[list.length];
9895 int num = 0;
9896 synchronized (mPackages) {
9897 for (String cid : list) {
9898 SdInstallArgs args = new SdInstallArgs(cid);
9899 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009900 String pkgName = args.getPackageName();
9901 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009902 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9903 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009904 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009905 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009906 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9907 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009908 // The package status is changed only if the code path
9909 // matches between settings and the container id.
9910 if (ps != null && ps.codePathString != null &&
9911 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009912 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9913 " corresponds to pkg : " + pkgName +
9914 " at code path: " + ps.codePathString);
9915 // We do have a valid package installed on sdcard
9916 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009917 int uid = ps.userId;
9918 if (uid != -1) {
9919 uidList[num++] = uid;
9920 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009921 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009922 // Stale container on sdcard. Just delete
9923 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9924 removeCids.add(cid);
9925 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009926 }
9927 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009928
9929 if (num > 0) {
9930 // Sort uid list
9931 Arrays.sort(uidList, 0, num);
9932 // Throw away duplicates
9933 uidArr = new int[num];
9934 uidArr[0] = uidList[0];
9935 int di = 0;
9936 for (int i = 1; i < num; i++) {
9937 if (uidList[i-1] != uidList[i]) {
9938 uidArr[di++] = uidList[i];
9939 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009940 }
9941 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009942 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009943 // Process packages with valid entries.
9944 if (mediaStatus) {
9945 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009946 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009947 startCleaningPackages();
9948 } else {
9949 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009950 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009951 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009952 }
9953
9954 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009955 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009956 int size = pkgList.size();
9957 if (size > 0) {
9958 // Send broadcasts here
9959 Bundle extras = new Bundle();
9960 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9961 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009962 if (uidArr != null) {
9963 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9964 }
9965 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9966 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009967 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009968 }
9969 }
9970
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009971 /*
9972 * Look at potentially valid container ids from processCids
9973 * If package information doesn't match the one on record
9974 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009975 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009976 */
9977 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009978 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009979 ArrayList<String> pkgList = new ArrayList<String>();
9980 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009981 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009982 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009983 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009984 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9985 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009986 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009987 try {
9988 // Make sure there are no container errors first.
9989 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9990 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009991 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009992 " when installing from sdcard");
9993 continue;
9994 }
9995 // Check code path here.
9996 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009997 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009998 " does not match one in settings " + codePath);
9999 continue;
10000 }
10001 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -070010002 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010003 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010004 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -070010005 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
Dianne Hackborn78d6883692010-10-07 01:12:46 -070010006 parseFlags, 0, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010007 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -070010008 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010009 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010010 retCode = PackageManager.INSTALL_SUCCEEDED;
10011 pkgList.add(pkg.packageName);
10012 // Post process args
10013 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
10014 }
10015 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -070010016 Slog.i(TAG, "Failed to install pkg from " +
10017 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010018 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010019 }
10020
10021 } finally {
10022 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
10023 // Don't destroy container here. Wait till gc clears things up.
10024 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010025 }
10026 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010027 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -070010028 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -070010029 // If the platform SDK has changed since the last time we booted,
10030 // we need to re-grant app permission to catch any new ones that
10031 // appear. This is really a hack, and means that apps can in some
10032 // cases get permissions that the user didn't initially explicitly
10033 // allow... it would be nice to have some better way to handle
10034 // this situation.
10035 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
10036 != mSdkVersion;
10037 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
10038 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
10039 + "; regranting permissions for external storage");
10040 mSettings.mExternalSdkPlatform = mSdkVersion;
10041
Dianne Hackbornaf7cea32010-03-24 12:59:52 -070010042 // Make sure group IDs have been assigned, and any permission
10043 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -070010044 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -070010045 // Persist settings
10046 mSettings.writeLP();
10047 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080010048 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -070010049 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010050 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010051 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010052 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010053 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010054 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010055 }
Kenny Rootf369a9b2010-07-28 14:47:01 -070010056 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010057 if (removeCids != null) {
10058 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -070010059 if (cid.startsWith(mTempContainerPrefix)) {
10060 Log.i(TAG, "Destroying stale temporary container " + cid);
10061 PackageHelper.destroySdDir(cid);
10062 } else {
10063 Log.w(TAG, "Container " + cid + " is stale");
10064 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010065 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010066 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010067 }
10068
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010069 /*
10070 * Utility method to unload a list of specified containers
10071 */
10072 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
10073 // Just unmount all valid containers.
10074 for (SdInstallArgs arg : cidArgs) {
10075 synchronized (mInstallLock) {
10076 arg.doPostDeleteLI(false);
10077 }
10078 }
10079 }
10080
10081 /*
10082 * Unload packages mounted on external media. This involves deleting
10083 * package data from internal structures, sending broadcasts about
10084 * diabled packages, gc'ing to free up references, unmounting all
10085 * secure containers corresponding to packages on external media, and
10086 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
10087 * Please note that we always have to post this message if status has
10088 * been requested no matter what.
10089 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010090 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010091 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010092 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010093 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010094 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010095 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010096 for (SdInstallArgs args : keys) {
10097 String cid = args.cid;
10098 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010099 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010100 // Delete package internally
10101 PackageRemovedInfo outInfo = new PackageRemovedInfo();
10102 synchronized (mInstallLock) {
10103 boolean res = deletePackageLI(pkgName, false,
Dianne Hackborn3aeee332010-10-02 18:56:33 -070010104 PackageManager.DONT_DELETE_DATA, outInfo, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010105 if (res) {
10106 pkgList.add(pkgName);
10107 } else {
Jeff Brown07330792010-03-30 19:57:08 -070010108 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010109 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010110 }
10111 }
10112 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -070010113
10114 synchronized (mPackages) {
10115 // We didn't update the settings after removing each package;
10116 // write them now for all packages.
10117 mSettings.writeLP();
10118 }
10119
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010120 // We have to absolutely send UPDATED_MEDIA_STATUS only
10121 // after confirming that all the receivers processed the ordered
10122 // broadcast when packages get disabled, force a gc to clean things up.
10123 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -070010124 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010125 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
10126 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
10127 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010128 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
10129 reportStatus ? 1 : 0, 1, keys);
10130 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010131 }
10132 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010133 } else {
10134 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
10135 reportStatus ? 1 : 0, -1, keys);
10136 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010137 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -080010138 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010139
10140 public void movePackage(final String packageName,
10141 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010142 mContext.enforceCallingOrSelfPermission(
10143 android.Manifest.permission.MOVE_PACKAGE, null);
10144 int returnCode = PackageManager.MOVE_SUCCEEDED;
10145 int currFlags = 0;
10146 int newFlags = 0;
10147 synchronized (mPackages) {
10148 PackageParser.Package pkg = mPackages.get(packageName);
10149 if (pkg == null) {
10150 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010151 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010152 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -070010153 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010154 Slog.w(TAG, "Cannot move system application");
10155 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -070010156 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010157 Slog.w(TAG, "Cannot move forward locked app.");
10158 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -070010159 } else if (pkg.mOperationPending) {
10160 Slog.w(TAG, "Attempt to move package which has pending operations");
10161 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010162 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010163 // Find install location first
10164 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
10165 (flags & PackageManager.MOVE_INTERNAL) != 0) {
10166 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010167 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010168 } else {
10169 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
10170 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -070010171 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
10172 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010173 if (newFlags == currFlags) {
10174 Slog.w(TAG, "No move required. Trying to move to same location");
10175 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
10176 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010177 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010178 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10179 pkg.mOperationPending = true;
10180 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010181 }
10182 }
10183 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -070010184 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010185 } else {
10186 Message msg = mHandler.obtainMessage(INIT_COPY);
10187 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -070010188 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
10189 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
10190 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010191 msg.obj = mp;
10192 mHandler.sendMessage(msg);
10193 }
10194 }
10195 }
10196
10197 private void processPendingMove(final MoveParams mp, final int currentStatus) {
10198 // Queue up an async operation since the package deletion may take a little while.
10199 mHandler.post(new Runnable() {
10200 public void run() {
10201 mHandler.removeCallbacks(this);
10202 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010203 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
10204 int uidArr[] = null;
10205 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010206 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010207 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -070010208 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010209 Slog.w(TAG, " Package " + mp.packageName +
10210 " doesn't exist. Aborting move");
10211 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
10212 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10213 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10214 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10215 " Aborting move and returning error");
10216 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10217 } else {
10218 uidArr = new int[] { pkg.applicationInfo.uid };
10219 pkgList = new ArrayList<String>();
10220 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010221 }
10222 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010223 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10224 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010225 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010226 // Update package code and resource paths
10227 synchronized (mInstallLock) {
10228 synchronized (mPackages) {
10229 PackageParser.Package pkg = mPackages.get(mp.packageName);
10230 // Recheck for package again.
Kenny Root6a6b0072010-10-07 16:46:10 -070010231 if (pkg == null) {
10232 Slog.w(TAG, " Package " + mp.packageName
10233 + " doesn't exist. Aborting move");
10234 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010235 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10236 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10237 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10238 " Aborting move and returning error");
10239 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10240 } else {
Kenny Root85387d72010-08-26 10:13:11 -070010241 final String oldCodePath = pkg.mPath;
10242 final String newCodePath = mp.targetArgs.getCodePath();
10243 final String newResPath = mp.targetArgs.getResourcePath();
10244 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Kenny Root6a6b0072010-10-07 16:46:10 -070010245
10246 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) == 0) {
10247 if (mInstaller
10248 .unlinkNativeLibraryDirectory(pkg.applicationInfo.dataDir) < 0) {
10249 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10250 } else {
10251 NativeLibraryHelper.copyNativeBinariesLI(
10252 new File(newCodePath), new File(newNativePath));
10253 }
10254 } else {
10255 if (mInstaller.linkNativeLibraryDirectory(
10256 pkg.applicationInfo.dataDir, newNativePath) < 0) {
10257 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10258 }
10259 }
10260
10261 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10262 pkg.mPath = newCodePath;
10263 // Move dex files around
10264 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
10265 // Moving of dex files failed. Set
10266 // error code and abort move.
10267 pkg.mPath = pkg.mScanPath;
10268 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10269 }
10270 }
10271
10272 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010273 pkg.mScanPath = newCodePath;
10274 pkg.applicationInfo.sourceDir = newCodePath;
10275 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -070010276 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010277 PackageSetting ps = (PackageSetting) pkg.mExtras;
10278 ps.codePath = new File(pkg.applicationInfo.sourceDir);
10279 ps.codePathString = ps.codePath.getPath();
10280 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
10281 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -070010282 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010283 // Set the application info flag correctly.
10284 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
10285 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10286 } else {
10287 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10288 }
10289 ps.setFlags(pkg.applicationInfo.flags);
10290 mAppDirs.remove(oldCodePath);
10291 mAppDirs.put(newCodePath, pkg);
10292 // Persist settings
10293 mSettings.writeLP();
10294 }
10295 }
10296 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010297 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -070010298 // Send resources available broadcast
10299 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010300 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010301 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010302 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010303 // Clean up failed installation
10304 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010305 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010306 }
10307 } else {
10308 // Force a gc to clear things up.
10309 Runtime.getRuntime().gc();
10310 // Delete older code
10311 synchronized (mInstallLock) {
10312 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010313 }
10314 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010315
10316 // Allow more operations on this file if we didn't fail because
10317 // an operation was already pending for this package.
10318 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
10319 synchronized (mPackages) {
10320 PackageParser.Package pkg = mPackages.get(mp.packageName);
10321 if (pkg != null) {
10322 pkg.mOperationPending = false;
10323 }
10324 }
10325 }
10326
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010327 IPackageMoveObserver observer = mp.observer;
10328 if (observer != null) {
10329 try {
10330 observer.packageMoved(mp.packageName, returnCode);
10331 } catch (RemoteException e) {
10332 Log.i(TAG, "Observer no longer exists.");
10333 }
10334 }
10335 }
10336 });
10337 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070010338
10339 public boolean setInstallLocation(int loc) {
10340 mContext.enforceCallingOrSelfPermission(
10341 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
10342 if (getInstallLocation() == loc) {
10343 return true;
10344 }
10345 if (loc == PackageHelper.APP_INSTALL_AUTO ||
10346 loc == PackageHelper.APP_INSTALL_INTERNAL ||
10347 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
10348 android.provider.Settings.System.putInt(mContext.getContentResolver(),
10349 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
10350 return true;
10351 }
10352 return false;
10353 }
10354
10355 public int getInstallLocation() {
10356 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
10357 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
10358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010359}