blob: a497b72a3dc48552c8b76f1a2016edc374c894d1 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080021import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080022import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070023import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080024import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025
26import org.xmlpull.v1.XmlPullParser;
27import org.xmlpull.v1.XmlPullParserException;
28import org.xmlpull.v1.XmlSerializer;
29
30import android.app.ActivityManagerNative;
31import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080032import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080033import android.app.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.Context;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070035import android.content.ComponentName;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070036import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.content.Intent;
38import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070039import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080040import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070041import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.pm.ActivityInfo;
43import android.content.pm.ApplicationInfo;
44import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070045import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.pm.IPackageDataObserver;
47import android.content.pm.IPackageDeleteObserver;
48import android.content.pm.IPackageInstallObserver;
49import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080050import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.content.pm.IPackageStatsObserver;
52import android.content.pm.InstrumentationInfo;
53import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080054import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.content.pm.PackageManager;
56import android.content.pm.PackageStats;
57import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
59import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.content.pm.PackageParser;
61import android.content.pm.PermissionInfo;
62import android.content.pm.PermissionGroupInfo;
63import android.content.pm.ProviderInfo;
64import android.content.pm.ResolveInfo;
65import android.content.pm.ServiceInfo;
66import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.net.Uri;
68import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070069import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080071import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080073import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070074import android.os.Looper;
75import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.os.Parcel;
77import android.os.RemoteException;
78import android.os.Environment;
79import android.os.FileObserver;
80import android.os.FileUtils;
81import android.os.Handler;
82import android.os.ParcelFileDescriptor;
83import android.os.Process;
84import android.os.ServiceManager;
85import android.os.SystemClock;
86import android.os.SystemProperties;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070087import android.provider.Settings;
Oscar Montemayord02546b2010-01-14 16:38:40 -080088import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.util.*;
90import android.view.Display;
91import android.view.WindowManager;
92
93import java.io.File;
94import java.io.FileDescriptor;
95import java.io.FileInputStream;
96import java.io.FileNotFoundException;
97import java.io.FileOutputStream;
98import java.io.FileReader;
99import java.io.FilenameFilter;
100import java.io.IOException;
101import java.io.InputStream;
102import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800103import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800104import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import java.util.ArrayList;
106import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700107import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import java.util.Collections;
109import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800110import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import java.util.Enumeration;
112import java.util.HashMap;
113import java.util.HashSet;
114import java.util.Iterator;
115import java.util.List;
116import java.util.Map;
117import java.util.Set;
118import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800119import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120import java.util.zip.ZipFile;
121import java.util.zip.ZipOutputStream;
122
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700123/**
124 * Keep track of all those .apks everywhere.
125 *
126 * This is very central to the platform's security; please run the unit
127 * tests whenever making modifications here:
128 *
129mmm frameworks/base/tests/AndroidTests
130adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
131adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
132 *
133 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134class PackageManagerService extends IPackageManager.Stub {
135 private static final String TAG = "PackageManager";
136 private static final boolean DEBUG_SETTINGS = false;
137 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800138 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800139 private static final boolean DEBUG_INSTALL = false;
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -0700140 private static final boolean DEBUG_NATIVE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141
142 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
143 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400144 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 private static final int FIRST_APPLICATION_UID =
146 Process.FIRST_APPLICATION_UID;
147 private static final int MAX_APPLICATION_UIDS = 1000;
148
149 private static final boolean SHOW_INFO = false;
150
151 private static final boolean GET_CERTIFICATES = true;
152
Oscar Montemayora8529f62009-11-18 10:14:20 -0800153 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 private static final int REMOVE_EVENTS =
156 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
157 private static final int ADD_EVENTS =
158 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
159
160 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800161 // Suffix used during package installation when copying/moving
162 // package apks to install directory.
163 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800165 /**
166 * Indicates the state of installation. Used by PackageManager to
167 * figure out incomplete installations. Say a package is being installed
168 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
169 * the package installation is successful or unsuccesful lin which case
170 * the PackageManager will no longer maintain state information associated
171 * with the package. If some exception(like device freeze or battery being
172 * pulled out) occurs during installation of a package, the PackageManager
173 * needs this information to clean up the previously failed installation.
174 */
175 private static final int PKG_INSTALL_INCOMPLETE = 0;
176 private static final int PKG_INSTALL_COMPLETE = 1;
177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 static final int SCAN_MONITOR = 1<<0;
179 static final int SCAN_NO_DEX = 1<<1;
180 static final int SCAN_FORCE_DEX = 1<<2;
181 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800182 static final int SCAN_NEW_INSTALL = 1<<4;
183 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700185 static final int REMOVE_CHATTY = 1<<16;
186
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800187 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
188 "com.android.defcontainer",
189 "com.android.defcontainer.DefaultContainerService");
190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
192 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700193 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194
Dianne Hackborn851a5412009-05-08 12:06:44 -0700195 final int mSdkVersion = Build.VERSION.SDK_INT;
196 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
197 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 final Context mContext;
200 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700201 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 final DisplayMetrics mMetrics;
203 final int mDefParseFlags;
204 final String[] mSeparateProcesses;
205
206 // This is where all application persistent data goes.
207 final File mAppDataDir;
208
Oscar Montemayora8529f62009-11-18 10:14:20 -0800209 // If Encrypted File System feature is enabled, all application persistent data
210 // should go here instead.
211 final File mSecureAppDataDir;
212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 // This is the object monitoring the framework dir.
214 final FileObserver mFrameworkInstallObserver;
215
216 // This is the object monitoring the system app dir.
217 final FileObserver mSystemInstallObserver;
218
219 // This is the object monitoring mAppInstallDir.
220 final FileObserver mAppInstallObserver;
221
222 // This is the object monitoring mDrmAppPrivateInstallDir.
223 final FileObserver mDrmAppInstallObserver;
224
225 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
226 // LOCK HELD. Can be called with mInstallLock held.
227 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 final File mFrameworkDir;
230 final File mSystemAppDir;
231 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700232 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233
234 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
235 // apps.
236 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 // Lock for state used when installing and doing other long running
241 // operations. Methods that must be called with this lock held have
242 // the prefix "LI".
243 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 // These are the directories in the 3rd party applications installed dir
246 // that we have currently loaded packages from. Keys are the application's
247 // installed zip file (absolute codePath), and values are Package.
248 final HashMap<String, PackageParser.Package> mAppDirs =
249 new HashMap<String, PackageParser.Package>();
250
251 // Information for the parser to write more useful error messages.
252 File mScanningPath;
253 int mLastScanError;
254
255 final int[] mOutPermissions = new int[3];
256
257 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 // Keys are String (package name), values are Package. This also serves
260 // as the lock for the global state. Methods that must be called with
261 // this lock held have the prefix "LP".
262 final HashMap<String, PackageParser.Package> mPackages =
263 new HashMap<String, PackageParser.Package>();
264
265 final Settings mSettings;
266 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267
268 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
269 int[] mGlobalGids;
270
271 // These are the built-in uid -> permission mappings that were read from the
272 // etc/permissions.xml file.
273 final SparseArray<HashSet<String>> mSystemPermissions =
274 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 // These are the built-in shared libraries that were read from the
277 // etc/permissions.xml file.
278 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800279
Dianne Hackborn49237342009-08-27 20:08:01 -0700280 // Temporary for building the final shared libraries for an .apk.
281 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800282
Dianne Hackborn49237342009-08-27 20:08:01 -0700283 // These are the features this devices supports that were read from the
284 // etc/permissions.xml file.
285 final HashMap<String, FeatureInfo> mAvailableFeatures =
286 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288 // All available activities, for your resolving pleasure.
289 final ActivityIntentResolver mActivities =
290 new ActivityIntentResolver();
291
292 // All available receivers, for your resolving pleasure.
293 final ActivityIntentResolver mReceivers =
294 new ActivityIntentResolver();
295
296 // All available services, for your resolving pleasure.
297 final ServiceIntentResolver mServices = new ServiceIntentResolver();
298
299 // Keys are String (provider class name), values are Provider.
300 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
301 new HashMap<ComponentName, PackageParser.Provider>();
302
303 // Mapping from provider base names (first directory in content URI codePath)
304 // to the provider information.
305 final HashMap<String, PackageParser.Provider> mProviders =
306 new HashMap<String, PackageParser.Provider>();
307
308 // Mapping from instrumentation class names to info about them.
309 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
310 new HashMap<ComponentName, PackageParser.Instrumentation>();
311
312 // Mapping from permission names to info about them.
313 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
314 new HashMap<String, PackageParser.PermissionGroup>();
315
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800316 // Packages whose data we have transfered into another package, thus
317 // should no longer exist.
318 final HashSet<String> mTransferedPackages = new HashSet<String>();
319
Dianne Hackborn854060af2009-07-09 18:14:31 -0700320 // Broadcast actions that are only available to the system.
321 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 boolean mSystemReady;
324 boolean mSafeMode;
325 boolean mHasSystemUidErrors;
326
327 ApplicationInfo mAndroidApplication;
328 final ActivityInfo mResolveActivity = new ActivityInfo();
329 final ResolveInfo mResolveInfo = new ResolveInfo();
330 ComponentName mResolveComponentName;
331 PackageParser.Package mPlatformPackage;
332
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700333 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800334 final HashMap<String, ArrayList<String>> mPendingBroadcasts
335 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800336 // Service Connection to remote media container service to copy
337 // package uri's from external media onto secure containers
338 // or internal storage.
339 private IMediaContainerService mContainerService = null;
340
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700341 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800342 static final int MCS_BOUND = 3;
343 static final int END_COPY = 4;
344 static final int INIT_COPY = 5;
345 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800346 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800347 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800348 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800349 static final int MCS_RECONNECT = 10;
350 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700351 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700352 static final int WRITE_SETTINGS = 13;
353
354 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800355
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700356 // Delay time in millisecs
357 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800358 final private DefaultContainerConnection mDefContainerConn =
359 new DefaultContainerConnection();
360 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800361 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800362 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800363 IMediaContainerService imcs =
364 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800365 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800366 }
367
368 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800369 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800370 }
371 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700372
Christopher Tate1bb69062010-02-19 17:02:12 -0800373 // Recordkeeping of restore-after-install operations that are currently in flight
374 // between the Package Manager and the Backup Manager
375 class PostInstallData {
376 public InstallArgs args;
377 public PackageInstalledInfo res;
378
379 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
380 args = _a;
381 res = _r;
382 }
383 };
384 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
385 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
386
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700387 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800388 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800389 final ArrayList<HandlerParams> mPendingInstalls =
390 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800391
392 private boolean connectToService() {
393 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
394 " DefaultContainerService");
395 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700396 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800397 if (mContext.bindService(service, mDefContainerConn,
398 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700399 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800400 mBound = true;
401 return true;
402 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700403 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800404 return false;
405 }
406
407 private void disconnectService() {
408 mContainerService = null;
409 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700410 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800411 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700412 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800413 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800414
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700415 PackageHandler(Looper looper) {
416 super(looper);
417 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700418
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700419 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700420 try {
421 doHandleMessage(msg);
422 } finally {
423 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
424 }
425 }
426
427 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700428 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800429 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800430 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800431 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800432 int idx = mPendingInstalls.size();
433 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
434 // If a bind was already initiated we dont really
435 // need to do anything. The pending install
436 // will be processed later on.
437 if (!mBound) {
438 // If this is the only one pending we might
439 // have to bind to the service again.
440 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800441 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800442 params.serviceError();
443 return;
444 } else {
445 // Once we bind to the service, the first
446 // pending request will be processed.
447 mPendingInstalls.add(idx, params);
448 }
449 } else {
450 mPendingInstalls.add(idx, params);
451 // Already bound to the service. Just make
452 // sure we trigger off processing the first request.
453 if (idx == 0) {
454 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800455 }
456 }
457 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800458 }
459 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800460 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800461 if (msg.obj != null) {
462 mContainerService = (IMediaContainerService) msg.obj;
463 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800464 if (mContainerService == null) {
465 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800466 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800467 for (HandlerParams params : mPendingInstalls) {
468 mPendingInstalls.remove(0);
469 // Indicate service bind error
470 params.serviceError();
471 }
472 mPendingInstalls.clear();
473 } else if (mPendingInstalls.size() > 0) {
474 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800475 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800476 params.startCopy();
477 }
478 } else {
479 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800480 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800481 }
482 break;
483 }
484 case MCS_RECONNECT : {
485 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
486 if (mPendingInstalls.size() > 0) {
487 if (mBound) {
488 disconnectService();
489 }
490 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800491 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800492 for (HandlerParams params : mPendingInstalls) {
493 mPendingInstalls.remove(0);
494 // Indicate service bind error
495 params.serviceError();
496 }
497 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800498 }
499 }
500 break;
501 }
502 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800503 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
504 // Delete pending install
505 if (mPendingInstalls.size() > 0) {
506 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800507 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800508 if (mPendingInstalls.size() == 0) {
509 if (mBound) {
510 disconnectService();
511 }
512 } else {
513 // There are more pending requests in queue.
514 // Just post MCS_BOUND message to trigger processing
515 // of next pending install.
516 mHandler.sendEmptyMessage(MCS_BOUND);
517 }
518 break;
519 }
520 case MCS_GIVE_UP: {
521 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
522 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800523 break;
524 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700525 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800526 String packages[];
527 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700528 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700529 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700530 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700531 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800532 if (mPendingBroadcasts == null) {
533 return;
534 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700535 size = mPendingBroadcasts.size();
536 if (size <= 0) {
537 // Nothing to be done. Just return
538 return;
539 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800540 packages = new String[size];
541 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700542 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800543 Iterator<HashMap.Entry<String, ArrayList<String>>>
544 it = mPendingBroadcasts.entrySet().iterator();
545 int i = 0;
546 while (it.hasNext() && i < size) {
547 HashMap.Entry<String, ArrayList<String>> ent = it.next();
548 packages[i] = ent.getKey();
549 components[i] = ent.getValue();
550 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700551 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800552 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700553 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800554 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700555 mPendingBroadcasts.clear();
556 }
557 // Send broadcasts
558 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800559 sendPackageChangedBroadcast(packages[i], true,
560 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700561 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700562 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700563 break;
564 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800565 case START_CLEANING_PACKAGE: {
566 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700567 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800568 synchronized (mPackages) {
569 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
570 mSettings.mPackagesToBeCleaned.add(packageName);
571 }
572 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700573 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800574 startCleaningPackages();
575 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800576 case POST_INSTALL: {
577 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
578 PostInstallData data = mRunningInstalls.get(msg.arg1);
579 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700580 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800581
582 if (data != null) {
583 InstallArgs args = data.args;
584 PackageInstalledInfo res = data.res;
585
586 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700587 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800588 Bundle extras = new Bundle(1);
589 extras.putInt(Intent.EXTRA_UID, res.uid);
590 final boolean update = res.removedInfo.removedPackage != null;
591 if (update) {
592 extras.putBoolean(Intent.EXTRA_REPLACING, true);
593 }
594 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
595 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700596 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800597 if (update) {
598 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
599 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700600 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800601 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700602 if (res.removedInfo.args != null) {
603 // Remove the replaced package's older resources safely now
604 deleteOld = true;
605 }
606 }
607 // Force a gc to clear up things
608 Runtime.getRuntime().gc();
609 // We delete after a gc for applications on sdcard.
610 if (deleteOld) {
611 synchronized (mInstallLock) {
612 res.removedInfo.args.doPostDeleteLI(true);
613 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800614 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800615 if (args.observer != null) {
616 try {
617 args.observer.packageInstalled(res.name, res.returnCode);
618 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800619 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800620 }
621 }
622 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800623 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800624 }
625 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700626 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700627 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
628 boolean reportStatus = msg.arg1 == 1;
629 boolean doGc = msg.arg2 == 1;
630 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
631 if (doGc) {
632 // Force a gc to clear up stale containers.
633 Runtime.getRuntime().gc();
634 }
635 if (msg.obj != null) {
636 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
637 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
638 // Unload containers
639 unloadAllContainers(args);
640 }
641 if (reportStatus) {
642 try {
643 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
644 PackageHelper.getMountService().finishMediaUpdate();
645 } catch (RemoteException e) {
646 Log.e(TAG, "MountService not running?");
647 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700648 }
649 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700650 case WRITE_SETTINGS: {
651 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
652 synchronized (mPackages) {
653 removeMessages(WRITE_SETTINGS);
654 mSettings.writeLP();
655 }
656 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
657 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700658 }
659 }
660 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800661
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700662 void scheduleWriteSettingsLocked() {
663 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
664 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
665 }
666 }
667
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800668 static boolean installOnSd(int flags) {
669 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700670 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800671 return false;
672 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700673 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
674 return true;
675 }
676 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800677 }
678
679 static boolean isFwdLocked(int flags) {
680 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
681 return true;
682 }
683 return false;
684 }
685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 public static final IPackageManager main(Context context, boolean factoryTest) {
687 PackageManagerService m = new PackageManagerService(context, factoryTest);
688 ServiceManager.addService("package", m);
689 return m;
690 }
691
692 static String[] splitString(String str, char sep) {
693 int count = 1;
694 int i = 0;
695 while ((i=str.indexOf(sep, i)) >= 0) {
696 count++;
697 i++;
698 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 String[] res = new String[count];
701 i=0;
702 count = 0;
703 int lastI=0;
704 while ((i=str.indexOf(sep, i)) >= 0) {
705 res[count] = str.substring(lastI, i);
706 count++;
707 i++;
708 lastI = i;
709 }
710 res[count] = str.substring(lastI, str.length());
711 return res;
712 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800715 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800719 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 mContext = context;
723 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700724 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 mMetrics = new DisplayMetrics();
726 mSettings = new Settings();
727 mSettings.addSharedUserLP("android.uid.system",
728 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
729 mSettings.addSharedUserLP("android.uid.phone",
730 MULTIPLE_APPLICATION_UIDS
731 ? RADIO_UID : FIRST_APPLICATION_UID,
732 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400733 mSettings.addSharedUserLP("android.uid.log",
734 MULTIPLE_APPLICATION_UIDS
735 ? LOG_UID : FIRST_APPLICATION_UID,
736 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737
738 String separateProcesses = SystemProperties.get("debug.separate_processes");
739 if (separateProcesses != null && separateProcesses.length() > 0) {
740 if ("*".equals(separateProcesses)) {
741 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
742 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800743 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 } else {
745 mDefParseFlags = 0;
746 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800747 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 + separateProcesses);
749 }
750 } else {
751 mDefParseFlags = 0;
752 mSeparateProcesses = null;
753 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 Installer installer = new Installer();
756 // Little hacky thing to check if installd is here, to determine
757 // whether we are running on the simulator and thus need to take
758 // care of building the /data file structure ourself.
759 // (apparently the sim now has a working installer)
760 if (installer.ping() && Process.supportsProcesses()) {
761 mInstaller = installer;
762 } else {
763 mInstaller = null;
764 }
765
766 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
767 Display d = wm.getDefaultDisplay();
768 d.getMetrics(mMetrics);
769
770 synchronized (mInstallLock) {
771 synchronized (mPackages) {
772 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700773 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 File dataDir = Environment.getDataDirectory();
776 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800777 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
779
780 if (mInstaller == null) {
781 // Make sure these dirs exist, when we are running in
782 // the simulator.
783 // Make a wide-open directory for random misc stuff.
784 File miscDir = new File(dataDir, "misc");
785 miscDir.mkdirs();
786 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800787 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 mDrmAppPrivateInstallDir.mkdirs();
789 }
790
791 readPermissions();
792
793 mRestoredSettings = mSettings.readLP();
794 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800795
796 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800798
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800799 // Set flag to monitor and not change apk file paths when
800 // scanning install directories.
801 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700802 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800803 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800804 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700805 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700810 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700813 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 /**
816 * Out of paranoia, ensure that everything in the boot class
817 * path has been dexed.
818 */
819 String bootClassPath = System.getProperty("java.boot.class.path");
820 if (bootClassPath != null) {
821 String[] paths = splitString(bootClassPath, ':');
822 for (int i=0; i<paths.length; i++) {
823 try {
824 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
825 libFiles.add(paths[i]);
826 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700827 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 }
829 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800830 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800832 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 }
834 }
835 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800836 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 /**
840 * Also ensure all external libraries have had dexopt run on them.
841 */
842 if (mSharedLibraries.size() > 0) {
843 Iterator<String> libs = mSharedLibraries.values().iterator();
844 while (libs.hasNext()) {
845 String lib = libs.next();
846 try {
847 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
848 libFiles.add(lib);
849 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700850 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 }
852 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800853 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800855 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 }
857 }
858 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 // Gross hack for now: we know this file doesn't contain any
861 // code, so don't dexopt it to avoid the resulting log spew.
862 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 /**
865 * And there are a number of commands implemented in Java, which
866 * we currently need to do the dexopt on so that they can be
867 * run from a non-root shell.
868 */
869 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700870 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 for (int i=0; i<frameworkFiles.length; i++) {
872 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
873 String path = libPath.getPath();
874 // Skip the file if we alrady did it.
875 if (libFiles.contains(path)) {
876 continue;
877 }
878 // Skip the file if it is not a type we want to dexopt.
879 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
880 continue;
881 }
882 try {
883 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
884 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700885 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 }
887 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800888 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800890 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 }
892 }
893 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800894
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700895 if (didDexOpt) {
896 // If we had to do a dexopt of one of the previous
897 // things, then something on the system has changed.
898 // Consider this significant, and wipe away all other
899 // existing dexopt files to ensure we don't leave any
900 // dangling around.
901 String[] files = mDalvikCacheDir.list();
902 if (files != null) {
903 for (int i=0; i<files.length; i++) {
904 String fn = files[i];
905 if (fn.startsWith("data@app@")
906 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800907 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700908 (new File(mDalvikCacheDir, fn)).delete();
909 }
910 }
911 }
912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800914
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800915 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 mFrameworkInstallObserver = new AppDirObserver(
917 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
918 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700919 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
920 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800921 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800922
923 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
925 mSystemInstallObserver = new AppDirObserver(
926 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
927 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700928 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
929 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800930
931 if (mInstaller != null) {
932 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
933 mInstaller.moveFiles();
934 }
935
936 // Prune any system packages that no longer exist.
937 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
938 while (psit.hasNext()) {
939 PackageSetting ps = psit.next();
940 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800941 && !mPackages.containsKey(ps.name)
942 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800943 psit.remove();
944 String msg = "System package " + ps.name
945 + " no longer exists; wiping its data";
946 reportSettingsProblem(Log.WARN, msg);
947 if (mInstaller != null) {
948 // XXX how to set useEncryptedFSDir for packages that
949 // are not encrypted?
950 mInstaller.remove(ps.name, true);
951 }
952 }
953 }
954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 mAppInstallDir = new File(dataDir, "app");
956 if (mInstaller == null) {
957 // Make sure these dirs exist, when we are running in
958 // the simulator.
959 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
960 }
961 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800962 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 //clean up list
964 for(int i = 0; i < deletePkgsList.size(); i++) {
965 //clean up here
966 cleanupInstallFailedPackage(deletePkgsList.get(i));
967 }
968 //delete tmp files
969 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800970
971 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 SystemClock.uptimeMillis());
973 mAppInstallObserver = new AppDirObserver(
974 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
975 mAppInstallObserver.startWatching();
976 scanDirLI(mAppInstallDir, 0, scanMode);
977
978 mDrmAppInstallObserver = new AppDirObserver(
979 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
980 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800981 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800983 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800985 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 + ((SystemClock.uptimeMillis()-startTime)/1000f)
987 + " seconds");
988
Dianne Hackbornf22221f2010-04-05 18:35:42 -0700989 // If the platform SDK has changed since the last time we booted,
990 // we need to re-grant app permission to catch any new ones that
991 // appear. This is really a hack, and means that apps can in some
992 // cases get permissions that the user didn't initially explicitly
993 // allow... it would be nice to have some better way to handle
994 // this situation.
995 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
996 != mSdkVersion;
997 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
998 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
999 + "; regranting permissions for internal storage");
1000 mSettings.mInternalSdkPlatform = mSdkVersion;
1001
Dianne Hackborn92cfa102010-04-28 11:00:44 -07001002 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003
1004 mSettings.writeLP();
1005
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001006 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 // Now after opening every single application zip, make sure they
1010 // are all flushed. Not really needed, but keeps things nice and
1011 // tidy.
1012 Runtime.getRuntime().gc();
1013 } // synchronized (mPackages)
1014 } // synchronized (mInstallLock)
1015 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 @Override
1018 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1019 throws RemoteException {
1020 try {
1021 return super.onTransact(code, data, reply, flags);
1022 } catch (RuntimeException e) {
1023 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001024 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 }
1026 throw e;
1027 }
1028 }
1029
Dianne Hackborne6620b22010-01-22 14:46:21 -08001030 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001031 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001033 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1034 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001036 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001037 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 }
1039 } else {
1040 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001041 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 File dataDir = new File(pkg.applicationInfo.dataDir);
1043 dataDir.delete();
1044 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001045 if (ps.codePath != null) {
1046 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001047 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001048 }
1049 }
1050 if (ps.resourcePath != null) {
1051 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001052 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001053 }
1054 }
1055 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 }
1057
1058 void readPermissions() {
1059 // Read permissions from .../etc/permission directory.
1060 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1061 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001062 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 return;
1064 }
1065 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001066 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 return;
1068 }
1069
1070 // Iterate over the files in the directory and scan .xml files
1071 for (File f : libraryDir.listFiles()) {
1072 // We'll read platform.xml last
1073 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1074 continue;
1075 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001078 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 continue;
1080 }
1081 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001082 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 continue;
1084 }
1085
1086 readPermissionsFromXml(f);
1087 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1090 final File permFile = new File(Environment.getRootDirectory(),
1091 "etc/permissions/platform.xml");
1092 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001093
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001094 StringBuilder sb = new StringBuilder(128);
1095 sb.append("Libs:");
1096 Iterator<String> it = mSharedLibraries.keySet().iterator();
1097 while (it.hasNext()) {
1098 sb.append(' ');
1099 String name = it.next();
1100 sb.append(name);
1101 sb.append(':');
1102 sb.append(mSharedLibraries.get(name));
1103 }
1104 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001105
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001106 sb.setLength(0);
1107 sb.append("Features:");
1108 it = mAvailableFeatures.keySet().iterator();
1109 while (it.hasNext()) {
1110 sb.append(' ');
1111 sb.append(it.next());
1112 }
1113 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 }
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.
1330 return PackageParser.generatePackageInfo(p, null, flags);
1331 }
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;
1337 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1338 }
1339
1340 public PackageInfo getPackageInfo(String packageName, int flags) {
1341 synchronized (mPackages) {
1342 PackageParser.Package p = mPackages.get(packageName);
1343 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001344 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 + ": " + p);
1346 if (p != null) {
1347 return generatePackageInfo(p, flags);
1348 }
1349 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1350 return generatePackageInfoFromSettingsLP(packageName, flags);
1351 }
1352 }
1353 return null;
1354 }
1355
Dianne Hackborn47096932010-02-11 15:57:09 -08001356 public String[] currentToCanonicalPackageNames(String[] names) {
1357 String[] out = new String[names.length];
1358 synchronized (mPackages) {
1359 for (int i=names.length-1; i>=0; i--) {
1360 PackageSetting ps = mSettings.mPackages.get(names[i]);
1361 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1362 }
1363 }
1364 return out;
1365 }
1366
1367 public String[] canonicalToCurrentPackageNames(String[] names) {
1368 String[] out = new String[names.length];
1369 synchronized (mPackages) {
1370 for (int i=names.length-1; i>=0; i--) {
1371 String cur = mSettings.mRenamedPackages.get(names[i]);
1372 out[i] = cur != null ? cur : names[i];
1373 }
1374 }
1375 return out;
1376 }
1377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 public int getPackageUid(String packageName) {
1379 synchronized (mPackages) {
1380 PackageParser.Package p = mPackages.get(packageName);
1381 if(p != null) {
1382 return p.applicationInfo.uid;
1383 }
1384 PackageSetting ps = mSettings.mPackages.get(packageName);
1385 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1386 return -1;
1387 }
1388 p = ps.pkg;
1389 return p != null ? p.applicationInfo.uid : -1;
1390 }
1391 }
1392
1393 public int[] getPackageGids(String packageName) {
1394 synchronized (mPackages) {
1395 PackageParser.Package p = mPackages.get(packageName);
1396 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001397 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 + ": " + p);
1399 if (p != null) {
1400 final PackageSetting ps = (PackageSetting)p.mExtras;
1401 final SharedUserSetting suid = ps.sharedUser;
1402 return suid != null ? suid.gids : ps.gids;
1403 }
1404 }
1405 // stupid thing to indicate an error.
1406 return new int[0];
1407 }
1408
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001409 static final PermissionInfo generatePermissionInfo(
1410 BasePermission bp, int flags) {
1411 if (bp.perm != null) {
1412 return PackageParser.generatePermissionInfo(bp.perm, flags);
1413 }
1414 PermissionInfo pi = new PermissionInfo();
1415 pi.name = bp.name;
1416 pi.packageName = bp.sourcePackage;
1417 pi.nonLocalizedLabel = bp.name;
1418 pi.protectionLevel = bp.protectionLevel;
1419 return pi;
1420 }
1421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 public PermissionInfo getPermissionInfo(String name, int flags) {
1423 synchronized (mPackages) {
1424 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001425 if (p != null) {
1426 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 }
1428 return null;
1429 }
1430 }
1431
1432 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1433 synchronized (mPackages) {
1434 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1435 for (BasePermission p : mSettings.mPermissions.values()) {
1436 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001437 if (p.perm == null || p.perm.info.group == null) {
1438 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 }
1440 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001441 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1443 }
1444 }
1445 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 if (out.size() > 0) {
1448 return out;
1449 }
1450 return mPermissionGroups.containsKey(group) ? out : null;
1451 }
1452 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1455 synchronized (mPackages) {
1456 return PackageParser.generatePermissionGroupInfo(
1457 mPermissionGroups.get(name), flags);
1458 }
1459 }
1460
1461 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1462 synchronized (mPackages) {
1463 final int N = mPermissionGroups.size();
1464 ArrayList<PermissionGroupInfo> out
1465 = new ArrayList<PermissionGroupInfo>(N);
1466 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1467 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1468 }
1469 return out;
1470 }
1471 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1474 PackageSetting ps = mSettings.mPackages.get(packageName);
1475 if(ps != null) {
1476 if(ps.pkg == null) {
1477 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1478 if(pInfo != null) {
1479 return pInfo.applicationInfo;
1480 }
1481 return null;
1482 }
1483 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1484 }
1485 return null;
1486 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1489 PackageSetting ps = mSettings.mPackages.get(packageName);
1490 if(ps != null) {
1491 if(ps.pkg == null) {
1492 ps.pkg = new PackageParser.Package(packageName);
1493 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001494 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1495 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1496 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1497 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 }
1499 return generatePackageInfo(ps.pkg, flags);
1500 }
1501 return null;
1502 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1505 synchronized (mPackages) {
1506 PackageParser.Package p = mPackages.get(packageName);
1507 if (Config.LOGV) Log.v(
1508 TAG, "getApplicationInfo " + packageName
1509 + ": " + p);
1510 if (p != null) {
1511 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001512 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 }
1514 if ("android".equals(packageName)||"system".equals(packageName)) {
1515 return mAndroidApplication;
1516 }
1517 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1518 return generateApplicationInfoFromSettingsLP(packageName, flags);
1519 }
1520 }
1521 return null;
1522 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001523
1524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1526 mContext.enforceCallingOrSelfPermission(
1527 android.Manifest.permission.CLEAR_APP_CACHE, null);
1528 // Queue up an async operation since clearing cache may take a little while.
1529 mHandler.post(new Runnable() {
1530 public void run() {
1531 mHandler.removeCallbacks(this);
1532 int retCode = -1;
1533 if (mInstaller != null) {
1534 retCode = mInstaller.freeCache(freeStorageSize);
1535 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001536 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 }
1538 } //end if mInstaller
1539 if (observer != null) {
1540 try {
1541 observer.onRemoveCompleted(null, (retCode >= 0));
1542 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001543 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 }
1545 }
1546 }
1547 });
1548 }
1549
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001550 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001551 mContext.enforceCallingOrSelfPermission(
1552 android.Manifest.permission.CLEAR_APP_CACHE, null);
1553 // Queue up an async operation since clearing cache may take a little while.
1554 mHandler.post(new Runnable() {
1555 public void run() {
1556 mHandler.removeCallbacks(this);
1557 int retCode = -1;
1558 if (mInstaller != null) {
1559 retCode = mInstaller.freeCache(freeStorageSize);
1560 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001561 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001562 }
1563 }
1564 if(pi != null) {
1565 try {
1566 // Callback via pending intent
1567 int code = (retCode >= 0) ? 1 : 0;
1568 pi.sendIntent(null, code, null,
1569 null, null);
1570 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001571 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001572 }
1573 }
1574 }
1575 });
1576 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1579 synchronized (mPackages) {
1580 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001581
1582 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001584 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 }
1586 if (mResolveComponentName.equals(component)) {
1587 return mResolveActivity;
1588 }
1589 }
1590 return null;
1591 }
1592
1593 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1594 synchronized (mPackages) {
1595 PackageParser.Activity a = mReceivers.mActivities.get(component);
1596 if (Config.LOGV) Log.v(
1597 TAG, "getReceiverInfo " + component + ": " + a);
1598 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1599 return PackageParser.generateActivityInfo(a, flags);
1600 }
1601 }
1602 return null;
1603 }
1604
1605 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1606 synchronized (mPackages) {
1607 PackageParser.Service s = mServices.mServices.get(component);
1608 if (Config.LOGV) Log.v(
1609 TAG, "getServiceInfo " + component + ": " + s);
1610 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1611 return PackageParser.generateServiceInfo(s, flags);
1612 }
1613 }
1614 return null;
1615 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 public String[] getSystemSharedLibraryNames() {
1618 Set<String> libSet;
1619 synchronized (mPackages) {
1620 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001621 int size = libSet.size();
1622 if (size > 0) {
1623 String[] libs = new String[size];
1624 libSet.toArray(libs);
1625 return libs;
1626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001628 return null;
1629 }
1630
1631 public FeatureInfo[] getSystemAvailableFeatures() {
1632 Collection<FeatureInfo> featSet;
1633 synchronized (mPackages) {
1634 featSet = mAvailableFeatures.values();
1635 int size = featSet.size();
1636 if (size > 0) {
1637 FeatureInfo[] features = new FeatureInfo[size+1];
1638 featSet.toArray(features);
1639 FeatureInfo fi = new FeatureInfo();
1640 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1641 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1642 features[size] = fi;
1643 return features;
1644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 }
1646 return null;
1647 }
1648
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001649 public boolean hasSystemFeature(String name) {
1650 synchronized (mPackages) {
1651 return mAvailableFeatures.containsKey(name);
1652 }
1653 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 public int checkPermission(String permName, String pkgName) {
1656 synchronized (mPackages) {
1657 PackageParser.Package p = mPackages.get(pkgName);
1658 if (p != null && p.mExtras != null) {
1659 PackageSetting ps = (PackageSetting)p.mExtras;
1660 if (ps.sharedUser != null) {
1661 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1662 return PackageManager.PERMISSION_GRANTED;
1663 }
1664 } else if (ps.grantedPermissions.contains(permName)) {
1665 return PackageManager.PERMISSION_GRANTED;
1666 }
1667 }
1668 }
1669 return PackageManager.PERMISSION_DENIED;
1670 }
1671
1672 public int checkUidPermission(String permName, int uid) {
1673 synchronized (mPackages) {
1674 Object obj = mSettings.getUserIdLP(uid);
1675 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001676 GrantedPermissions gp = (GrantedPermissions)obj;
1677 if (gp.grantedPermissions.contains(permName)) {
1678 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 }
1680 } else {
1681 HashSet<String> perms = mSystemPermissions.get(uid);
1682 if (perms != null && perms.contains(permName)) {
1683 return PackageManager.PERMISSION_GRANTED;
1684 }
1685 }
1686 }
1687 return PackageManager.PERMISSION_DENIED;
1688 }
1689
1690 private BasePermission findPermissionTreeLP(String permName) {
1691 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1692 if (permName.startsWith(bp.name) &&
1693 permName.length() > bp.name.length() &&
1694 permName.charAt(bp.name.length()) == '.') {
1695 return bp;
1696 }
1697 }
1698 return null;
1699 }
1700
1701 private BasePermission checkPermissionTreeLP(String permName) {
1702 if (permName != null) {
1703 BasePermission bp = findPermissionTreeLP(permName);
1704 if (bp != null) {
1705 if (bp.uid == Binder.getCallingUid()) {
1706 return bp;
1707 }
1708 throw new SecurityException("Calling uid "
1709 + Binder.getCallingUid()
1710 + " is not allowed to add to permission tree "
1711 + bp.name + " owned by uid " + bp.uid);
1712 }
1713 }
1714 throw new SecurityException("No permission tree found for " + permName);
1715 }
1716
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001717 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1718 if (s1 == null) {
1719 return s2 == null;
1720 }
1721 if (s2 == null) {
1722 return false;
1723 }
1724 if (s1.getClass() != s2.getClass()) {
1725 return false;
1726 }
1727 return s1.equals(s2);
1728 }
1729
1730 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1731 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001732 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001733 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1734 if (!compareStrings(pi1.name, pi2.name)) return false;
1735 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1736 // We'll take care of setting this one.
1737 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1738 // These are not currently stored in settings.
1739 //if (!compareStrings(pi1.group, pi2.group)) return false;
1740 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1741 //if (pi1.labelRes != pi2.labelRes) return false;
1742 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1743 return true;
1744 }
1745
1746 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1747 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1748 throw new SecurityException("Label must be specified in permission");
1749 }
1750 BasePermission tree = checkPermissionTreeLP(info.name);
1751 BasePermission bp = mSettings.mPermissions.get(info.name);
1752 boolean added = bp == null;
1753 boolean changed = true;
1754 if (added) {
1755 bp = new BasePermission(info.name, tree.sourcePackage,
1756 BasePermission.TYPE_DYNAMIC);
1757 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1758 throw new SecurityException(
1759 "Not allowed to modify non-dynamic permission "
1760 + info.name);
1761 } else {
1762 if (bp.protectionLevel == info.protectionLevel
1763 && bp.perm.owner.equals(tree.perm.owner)
1764 && bp.uid == tree.uid
1765 && comparePermissionInfos(bp.perm.info, info)) {
1766 changed = false;
1767 }
1768 }
1769 bp.protectionLevel = info.protectionLevel;
1770 bp.perm = new PackageParser.Permission(tree.perm.owner,
1771 new PermissionInfo(info));
1772 bp.perm.info.packageName = tree.perm.info.packageName;
1773 bp.uid = tree.uid;
1774 if (added) {
1775 mSettings.mPermissions.put(info.name, bp);
1776 }
1777 if (changed) {
1778 if (!async) {
1779 mSettings.writeLP();
1780 } else {
1781 scheduleWriteSettingsLocked();
1782 }
1783 }
1784 return added;
1785 }
1786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 public boolean addPermission(PermissionInfo info) {
1788 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001789 return addPermissionLocked(info, false);
1790 }
1791 }
1792
1793 public boolean addPermissionAsync(PermissionInfo info) {
1794 synchronized (mPackages) {
1795 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 }
1797 }
1798
1799 public void removePermission(String name) {
1800 synchronized (mPackages) {
1801 checkPermissionTreeLP(name);
1802 BasePermission bp = mSettings.mPermissions.get(name);
1803 if (bp != null) {
1804 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1805 throw new SecurityException(
1806 "Not allowed to modify non-dynamic permission "
1807 + name);
1808 }
1809 mSettings.mPermissions.remove(name);
1810 mSettings.writeLP();
1811 }
1812 }
1813 }
1814
Dianne Hackborn854060af2009-07-09 18:14:31 -07001815 public boolean isProtectedBroadcast(String actionName) {
1816 synchronized (mPackages) {
1817 return mProtectedBroadcasts.contains(actionName);
1818 }
1819 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 public int checkSignatures(String pkg1, String pkg2) {
1822 synchronized (mPackages) {
1823 PackageParser.Package p1 = mPackages.get(pkg1);
1824 PackageParser.Package p2 = mPackages.get(pkg2);
1825 if (p1 == null || p1.mExtras == null
1826 || p2 == null || p2.mExtras == null) {
1827 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1828 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001829 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 }
1831 }
1832
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001833 public int checkUidSignatures(int uid1, int uid2) {
1834 synchronized (mPackages) {
1835 Signature[] s1;
1836 Signature[] s2;
1837 Object obj = mSettings.getUserIdLP(uid1);
1838 if (obj != null) {
1839 if (obj instanceof SharedUserSetting) {
1840 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1841 } else if (obj instanceof PackageSetting) {
1842 s1 = ((PackageSetting)obj).signatures.mSignatures;
1843 } else {
1844 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1845 }
1846 } else {
1847 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1848 }
1849 obj = mSettings.getUserIdLP(uid2);
1850 if (obj != null) {
1851 if (obj instanceof SharedUserSetting) {
1852 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1853 } else if (obj instanceof PackageSetting) {
1854 s2 = ((PackageSetting)obj).signatures.mSignatures;
1855 } else {
1856 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1857 }
1858 } else {
1859 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1860 }
1861 return checkSignaturesLP(s1, s2);
1862 }
1863 }
1864
1865 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1866 if (s1 == null) {
1867 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1869 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1870 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001871 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1873 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001874 HashSet<Signature> set1 = new HashSet<Signature>();
1875 for (Signature sig : s1) {
1876 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001878 HashSet<Signature> set2 = new HashSet<Signature>();
1879 for (Signature sig : s2) {
1880 set2.add(sig);
1881 }
1882 // Make sure s2 contains all signatures in s1.
1883 if (set1.equals(set2)) {
1884 return PackageManager.SIGNATURE_MATCH;
1885 }
1886 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 }
1888
1889 public String[] getPackagesForUid(int uid) {
1890 synchronized (mPackages) {
1891 Object obj = mSettings.getUserIdLP(uid);
1892 if (obj instanceof SharedUserSetting) {
1893 SharedUserSetting sus = (SharedUserSetting)obj;
1894 final int N = sus.packages.size();
1895 String[] res = new String[N];
1896 Iterator<PackageSetting> it = sus.packages.iterator();
1897 int i=0;
1898 while (it.hasNext()) {
1899 res[i++] = it.next().name;
1900 }
1901 return res;
1902 } else if (obj instanceof PackageSetting) {
1903 PackageSetting ps = (PackageSetting)obj;
1904 return new String[] { ps.name };
1905 }
1906 }
1907 return null;
1908 }
1909
1910 public String getNameForUid(int uid) {
1911 synchronized (mPackages) {
1912 Object obj = mSettings.getUserIdLP(uid);
1913 if (obj instanceof SharedUserSetting) {
1914 SharedUserSetting sus = (SharedUserSetting)obj;
1915 return sus.name + ":" + sus.userId;
1916 } else if (obj instanceof PackageSetting) {
1917 PackageSetting ps = (PackageSetting)obj;
1918 return ps.name;
1919 }
1920 }
1921 return null;
1922 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 public int getUidForSharedUser(String sharedUserName) {
1925 if(sharedUserName == null) {
1926 return -1;
1927 }
1928 synchronized (mPackages) {
1929 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1930 if(suid == null) {
1931 return -1;
1932 }
1933 return suid.userId;
1934 }
1935 }
1936
1937 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1938 int flags) {
1939 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001940 return chooseBestActivity(intent, resolvedType, flags, query);
1941 }
1942
Mihai Predaeae850c2009-05-13 10:13:48 +02001943 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1944 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 if (query != null) {
1946 final int N = query.size();
1947 if (N == 1) {
1948 return query.get(0);
1949 } else if (N > 1) {
1950 // If there is more than one activity with the same priority,
1951 // then let the user decide between them.
1952 ResolveInfo r0 = query.get(0);
1953 ResolveInfo r1 = query.get(1);
1954 if (false) {
1955 System.out.println(r0.activityInfo.name +
1956 "=" + r0.priority + " vs " +
1957 r1.activityInfo.name +
1958 "=" + r1.priority);
1959 }
1960 // If the first activity has a higher priority, or a different
1961 // default, then it is always desireable to pick it.
1962 if (r0.priority != r1.priority
1963 || r0.preferredOrder != r1.preferredOrder
1964 || r0.isDefault != r1.isDefault) {
1965 return query.get(0);
1966 }
1967 // If we have saved a preference for a preferred activity for
1968 // this Intent, use that.
1969 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1970 flags, query, r0.priority);
1971 if (ri != null) {
1972 return ri;
1973 }
1974 return mResolveInfo;
1975 }
1976 }
1977 return null;
1978 }
1979
1980 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1981 int flags, List<ResolveInfo> query, int priority) {
1982 synchronized (mPackages) {
1983 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1984 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001985 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1987 if (prefs != null && prefs.size() > 0) {
1988 // First figure out how good the original match set is.
1989 // We will only allow preferred activities that came
1990 // from the same match quality.
1991 int match = 0;
1992 final int N = query.size();
1993 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1994 for (int j=0; j<N; j++) {
1995 ResolveInfo ri = query.get(j);
1996 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1997 + ": 0x" + Integer.toHexString(match));
1998 if (ri.match > match) match = ri.match;
1999 }
2000 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2001 + Integer.toHexString(match));
2002 match &= IntentFilter.MATCH_CATEGORY_MASK;
2003 final int M = prefs.size();
2004 for (int i=0; i<M; i++) {
2005 PreferredActivity pa = prefs.get(i);
2006 if (pa.mMatch != match) {
2007 continue;
2008 }
2009 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2010 if (DEBUG_PREFERRED) {
2011 Log.v(TAG, "Got preferred activity:");
2012 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
2013 }
2014 if (ai != null) {
2015 for (int j=0; j<N; j++) {
2016 ResolveInfo ri = query.get(j);
2017 if (!ri.activityInfo.applicationInfo.packageName
2018 .equals(ai.applicationInfo.packageName)) {
2019 continue;
2020 }
2021 if (!ri.activityInfo.name.equals(ai.name)) {
2022 continue;
2023 }
2024
2025 // Okay we found a previously set preferred app.
2026 // If the result set is different from when this
2027 // was created, we need to clear it and re-ask the
2028 // user their preference.
2029 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002030 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 + intent + " type " + resolvedType);
2032 mSettings.mPreferredActivities.removeFilter(pa);
2033 return null;
2034 }
2035
2036 // Yay!
2037 return ri;
2038 }
2039 }
2040 }
2041 }
2042 }
2043 return null;
2044 }
2045
2046 public List<ResolveInfo> queryIntentActivities(Intent intent,
2047 String resolvedType, int flags) {
2048 ComponentName comp = intent.getComponent();
2049 if (comp != null) {
2050 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2051 ActivityInfo ai = getActivityInfo(comp, flags);
2052 if (ai != null) {
2053 ResolveInfo ri = new ResolveInfo();
2054 ri.activityInfo = ai;
2055 list.add(ri);
2056 }
2057 return list;
2058 }
2059
2060 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002061 String pkgName = intent.getPackage();
2062 if (pkgName == null) {
2063 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2064 resolvedType, flags);
2065 }
2066 PackageParser.Package pkg = mPackages.get(pkgName);
2067 if (pkg != null) {
2068 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2069 resolvedType, flags, pkg.activities);
2070 }
2071 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 }
2073 }
2074
2075 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2076 Intent[] specifics, String[] specificTypes, Intent intent,
2077 String resolvedType, int flags) {
2078 final String resultsAction = intent.getAction();
2079
2080 List<ResolveInfo> results = queryIntentActivities(
2081 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2082 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2083
2084 int specificsPos = 0;
2085 int N;
2086
2087 // todo: note that the algorithm used here is O(N^2). This
2088 // isn't a problem in our current environment, but if we start running
2089 // into situations where we have more than 5 or 10 matches then this
2090 // should probably be changed to something smarter...
2091
2092 // First we go through and resolve each of the specific items
2093 // that were supplied, taking care of removing any corresponding
2094 // duplicate items in the generic resolve list.
2095 if (specifics != null) {
2096 for (int i=0; i<specifics.length; i++) {
2097 final Intent sintent = specifics[i];
2098 if (sintent == null) {
2099 continue;
2100 }
2101
2102 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2103 String action = sintent.getAction();
2104 if (resultsAction != null && resultsAction.equals(action)) {
2105 // If this action was explicitly requested, then don't
2106 // remove things that have it.
2107 action = null;
2108 }
2109 ComponentName comp = sintent.getComponent();
2110 ResolveInfo ri = null;
2111 ActivityInfo ai = null;
2112 if (comp == null) {
2113 ri = resolveIntent(
2114 sintent,
2115 specificTypes != null ? specificTypes[i] : null,
2116 flags);
2117 if (ri == null) {
2118 continue;
2119 }
2120 if (ri == mResolveInfo) {
2121 // ACK! Must do something better with this.
2122 }
2123 ai = ri.activityInfo;
2124 comp = new ComponentName(ai.applicationInfo.packageName,
2125 ai.name);
2126 } else {
2127 ai = getActivityInfo(comp, flags);
2128 if (ai == null) {
2129 continue;
2130 }
2131 }
2132
2133 // Look for any generic query activities that are duplicates
2134 // of this specific one, and remove them from the results.
2135 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2136 N = results.size();
2137 int j;
2138 for (j=specificsPos; j<N; j++) {
2139 ResolveInfo sri = results.get(j);
2140 if ((sri.activityInfo.name.equals(comp.getClassName())
2141 && sri.activityInfo.applicationInfo.packageName.equals(
2142 comp.getPackageName()))
2143 || (action != null && sri.filter.matchAction(action))) {
2144 results.remove(j);
2145 if (Config.LOGV) Log.v(
2146 TAG, "Removing duplicate item from " + j
2147 + " due to specific " + specificsPos);
2148 if (ri == null) {
2149 ri = sri;
2150 }
2151 j--;
2152 N--;
2153 }
2154 }
2155
2156 // Add this specific item to its proper place.
2157 if (ri == null) {
2158 ri = new ResolveInfo();
2159 ri.activityInfo = ai;
2160 }
2161 results.add(specificsPos, ri);
2162 ri.specificIndex = i;
2163 specificsPos++;
2164 }
2165 }
2166
2167 // Now we go through the remaining generic results and remove any
2168 // duplicate actions that are found here.
2169 N = results.size();
2170 for (int i=specificsPos; i<N-1; i++) {
2171 final ResolveInfo rii = results.get(i);
2172 if (rii.filter == null) {
2173 continue;
2174 }
2175
2176 // Iterate over all of the actions of this result's intent
2177 // filter... typically this should be just one.
2178 final Iterator<String> it = rii.filter.actionsIterator();
2179 if (it == null) {
2180 continue;
2181 }
2182 while (it.hasNext()) {
2183 final String action = it.next();
2184 if (resultsAction != null && resultsAction.equals(action)) {
2185 // If this action was explicitly requested, then don't
2186 // remove things that have it.
2187 continue;
2188 }
2189 for (int j=i+1; j<N; j++) {
2190 final ResolveInfo rij = results.get(j);
2191 if (rij.filter != null && rij.filter.hasAction(action)) {
2192 results.remove(j);
2193 if (Config.LOGV) Log.v(
2194 TAG, "Removing duplicate item from " + j
2195 + " due to action " + action + " at " + i);
2196 j--;
2197 N--;
2198 }
2199 }
2200 }
2201
2202 // If the caller didn't request filter information, drop it now
2203 // so we don't have to marshall/unmarshall it.
2204 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2205 rii.filter = null;
2206 }
2207 }
2208
2209 // Filter out the caller activity if so requested.
2210 if (caller != null) {
2211 N = results.size();
2212 for (int i=0; i<N; i++) {
2213 ActivityInfo ainfo = results.get(i).activityInfo;
2214 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2215 && caller.getClassName().equals(ainfo.name)) {
2216 results.remove(i);
2217 break;
2218 }
2219 }
2220 }
2221
2222 // If the caller didn't request filter information,
2223 // drop them now so we don't have to
2224 // marshall/unmarshall it.
2225 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2226 N = results.size();
2227 for (int i=0; i<N; i++) {
2228 results.get(i).filter = null;
2229 }
2230 }
2231
2232 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2233 return results;
2234 }
2235
2236 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2237 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002238 ComponentName comp = intent.getComponent();
2239 if (comp != null) {
2240 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2241 ActivityInfo ai = getReceiverInfo(comp, flags);
2242 if (ai != null) {
2243 ResolveInfo ri = new ResolveInfo();
2244 ri.activityInfo = ai;
2245 list.add(ri);
2246 }
2247 return list;
2248 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002251 String pkgName = intent.getPackage();
2252 if (pkgName == null) {
2253 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2254 resolvedType, flags);
2255 }
2256 PackageParser.Package pkg = mPackages.get(pkgName);
2257 if (pkg != null) {
2258 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2259 resolvedType, flags, pkg.receivers);
2260 }
2261 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002262 }
2263 }
2264
2265 public ResolveInfo resolveService(Intent intent, String resolvedType,
2266 int flags) {
2267 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2268 flags);
2269 if (query != null) {
2270 if (query.size() >= 1) {
2271 // If there is more than one service with the same priority,
2272 // just arbitrarily pick the first one.
2273 return query.get(0);
2274 }
2275 }
2276 return null;
2277 }
2278
2279 public List<ResolveInfo> queryIntentServices(Intent intent,
2280 String resolvedType, int flags) {
2281 ComponentName comp = intent.getComponent();
2282 if (comp != null) {
2283 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2284 ServiceInfo si = getServiceInfo(comp, flags);
2285 if (si != null) {
2286 ResolveInfo ri = new ResolveInfo();
2287 ri.serviceInfo = si;
2288 list.add(ri);
2289 }
2290 return list;
2291 }
2292
2293 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002294 String pkgName = intent.getPackage();
2295 if (pkgName == null) {
2296 return (List<ResolveInfo>)mServices.queryIntent(intent,
2297 resolvedType, flags);
2298 }
2299 PackageParser.Package pkg = mPackages.get(pkgName);
2300 if (pkg != null) {
2301 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2302 resolvedType, flags, pkg.services);
2303 }
2304 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002305 }
2306 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 public List<PackageInfo> getInstalledPackages(int flags) {
2309 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2310
2311 synchronized (mPackages) {
2312 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2313 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2314 while (i.hasNext()) {
2315 final PackageSetting ps = i.next();
2316 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2317 if(psPkg != null) {
2318 finalList.add(psPkg);
2319 }
2320 }
2321 }
2322 else {
2323 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2324 while (i.hasNext()) {
2325 final PackageParser.Package p = i.next();
2326 if (p.applicationInfo != null) {
2327 PackageInfo pi = generatePackageInfo(p, flags);
2328 if(pi != null) {
2329 finalList.add(pi);
2330 }
2331 }
2332 }
2333 }
2334 }
2335 return finalList;
2336 }
2337
2338 public List<ApplicationInfo> getInstalledApplications(int flags) {
2339 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2340 synchronized(mPackages) {
2341 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2342 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2343 while (i.hasNext()) {
2344 final PackageSetting ps = i.next();
2345 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2346 if(ai != null) {
2347 finalList.add(ai);
2348 }
2349 }
2350 }
2351 else {
2352 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2353 while (i.hasNext()) {
2354 final PackageParser.Package p = i.next();
2355 if (p.applicationInfo != null) {
2356 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2357 if(ai != null) {
2358 finalList.add(ai);
2359 }
2360 }
2361 }
2362 }
2363 }
2364 return finalList;
2365 }
2366
2367 public List<ApplicationInfo> getPersistentApplications(int flags) {
2368 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2369
2370 synchronized (mPackages) {
2371 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2372 while (i.hasNext()) {
2373 PackageParser.Package p = i.next();
2374 if (p.applicationInfo != null
2375 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2376 && (!mSafeMode || (p.applicationInfo.flags
2377 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
Jey2eebf5c2009-11-18 18:37:31 -08002378 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 }
2380 }
2381 }
2382
2383 return finalList;
2384 }
2385
2386 public ProviderInfo resolveContentProvider(String name, int flags) {
2387 synchronized (mPackages) {
2388 final PackageParser.Provider provider = mProviders.get(name);
2389 return provider != null
2390 && mSettings.isEnabledLP(provider.info, flags)
2391 && (!mSafeMode || (provider.info.applicationInfo.flags
2392 &ApplicationInfo.FLAG_SYSTEM) != 0)
2393 ? PackageParser.generateProviderInfo(provider, flags)
2394 : null;
2395 }
2396 }
2397
Fred Quintana718d8a22009-04-29 17:53:20 -07002398 /**
2399 * @deprecated
2400 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 public void querySyncProviders(List outNames, List outInfo) {
2402 synchronized (mPackages) {
2403 Iterator<Map.Entry<String, PackageParser.Provider>> i
2404 = mProviders.entrySet().iterator();
2405
2406 while (i.hasNext()) {
2407 Map.Entry<String, PackageParser.Provider> entry = i.next();
2408 PackageParser.Provider p = entry.getValue();
2409
2410 if (p.syncable
2411 && (!mSafeMode || (p.info.applicationInfo.flags
2412 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2413 outNames.add(entry.getKey());
2414 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2415 }
2416 }
2417 }
2418 }
2419
2420 public List<ProviderInfo> queryContentProviders(String processName,
2421 int uid, int flags) {
2422 ArrayList<ProviderInfo> finalList = null;
2423
2424 synchronized (mPackages) {
2425 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2426 while (i.hasNext()) {
2427 PackageParser.Provider p = i.next();
2428 if (p.info.authority != null
2429 && (processName == null ||
2430 (p.info.processName.equals(processName)
2431 && p.info.applicationInfo.uid == uid))
2432 && mSettings.isEnabledLP(p.info, flags)
2433 && (!mSafeMode || (p.info.applicationInfo.flags
2434 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2435 if (finalList == null) {
2436 finalList = new ArrayList<ProviderInfo>(3);
2437 }
2438 finalList.add(PackageParser.generateProviderInfo(p,
2439 flags));
2440 }
2441 }
2442 }
2443
2444 if (finalList != null) {
2445 Collections.sort(finalList, mProviderInitOrderSorter);
2446 }
2447
2448 return finalList;
2449 }
2450
2451 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2452 int flags) {
2453 synchronized (mPackages) {
2454 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2455 return PackageParser.generateInstrumentationInfo(i, flags);
2456 }
2457 }
2458
2459 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2460 int flags) {
2461 ArrayList<InstrumentationInfo> finalList =
2462 new ArrayList<InstrumentationInfo>();
2463
2464 synchronized (mPackages) {
2465 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2466 while (i.hasNext()) {
2467 PackageParser.Instrumentation p = i.next();
2468 if (targetPackage == null
2469 || targetPackage.equals(p.info.targetPackage)) {
2470 finalList.add(PackageParser.generateInstrumentationInfo(p,
2471 flags));
2472 }
2473 }
2474 }
2475
2476 return finalList;
2477 }
2478
2479 private void scanDirLI(File dir, int flags, int scanMode) {
2480 Log.d(TAG, "Scanning app dir " + dir);
2481
2482 String[] files = dir.list();
2483
2484 int i;
2485 for (i=0; i<files.length; i++) {
2486 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002487 if (!isPackageFilename(files[i])) {
2488 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002489 continue;
2490 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002491 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002493 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002494 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2495 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002496 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002497 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002498 file.delete();
2499 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 }
2501 }
2502
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002503 private static File getSettingsProblemFile() {
2504 File dataDir = Environment.getDataDirectory();
2505 File systemDir = new File(dataDir, "system");
2506 File fname = new File(systemDir, "uiderrors.txt");
2507 return fname;
2508 }
2509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 private static void reportSettingsProblem(int priority, String msg) {
2511 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002512 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 FileOutputStream out = new FileOutputStream(fname, true);
2514 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002515 SimpleDateFormat formatter = new SimpleDateFormat();
2516 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2517 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 pw.close();
2519 FileUtils.setPermissions(
2520 fname.toString(),
2521 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2522 -1, -1);
2523 } catch (java.io.IOException e) {
2524 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002525 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 }
2527
2528 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2529 PackageParser.Package pkg, File srcFile, int parseFlags) {
2530 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002531 if (ps != null
2532 && ps.codePath.equals(srcFile)
2533 && ps.getTimeStamp() == srcFile.lastModified()) {
2534 if (ps.signatures.mSignatures != null
2535 && ps.signatures.mSignatures.length != 0) {
2536 // Optimization: reuse the existing cached certificates
2537 // if the package appears to be unchanged.
2538 pkg.mSignatures = ps.signatures.mSignatures;
2539 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002540 }
Jeff Browne7600722010-04-07 18:28:23 -07002541
2542 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002543 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002544 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2545 }
2546
2547 if (!pp.collectCertificates(pkg, parseFlags)) {
2548 mLastScanError = pp.getParseError();
2549 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 }
2551 }
2552 return true;
2553 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 /*
2556 * Scan a package and return the newly parsed package.
2557 * Returns null in case of errors and the error code is stored in mLastScanError
2558 */
2559 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002560 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002562 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002564 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002567 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 if (pkg == null) {
2569 mLastScanError = pp.getParseError();
2570 return null;
2571 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002572 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 PackageSetting updatedPkg;
2574 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002575 // Look to see if we already know about this package.
2576 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002577 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002578 // This package has been renamed to its original name. Let's
2579 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002580 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002581 }
2582 // If there was no original package, see one for the real package name.
2583 if (ps == null) {
2584 ps = mSettings.peekPackageLP(pkg.packageName);
2585 }
2586 // Check to see if this package could be hiding/updating a system
2587 // package. Must look for it either under the original or real
2588 // package name depending on our state.
2589 updatedPkg = mSettings.mDisabledSysPackages.get(
2590 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002592 // First check if this is a system package that may involve an update
2593 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2594 if (!ps.codePath.equals(scanFile)) {
2595 // The path has changed from what was last scanned... check the
2596 // version of the new path against what we have stored to determine
2597 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002598 if (pkg.mVersionCode < ps.versionCode) {
2599 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002600 // Ignore entry. Skip it.
2601 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2602 + "ignored: updated version " + ps.versionCode
2603 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002604 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2605 return null;
2606 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002607 // The current app on the system partion is better than
2608 // what we have updated to on the data partition; switch
2609 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002610 // At this point, its safely assumed that package installation for
2611 // apps in system partition will go through. If not there won't be a working
2612 // version of the app
2613 synchronized (mPackages) {
2614 // Just remove the loaded entries from package lists.
2615 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002616 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002617 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002618 + "reverting from " + ps.codePathString
2619 + ": new version " + pkg.mVersionCode
2620 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002621 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2622 args.cleanUpResourcesLI();
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07002623 removeNativeBinariesLI(pkg);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002624 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002626 }
2627 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002628 if (updatedPkg != null) {
2629 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2630 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2631 }
2632 // Verify certificates against what was last scanned
2633 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002634 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002635 return null;
2636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 // The apk is forward locked (not public) if its code and resources
2638 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002639 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002641 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002642 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002643
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002644 String codePath = null;
2645 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002646 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2647 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002648 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002649 } else {
2650 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002651 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002652 }
2653 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002654 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002655 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002656 codePath = pkg.mScanPath;
2657 // Set application objects path explicitly.
2658 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002659 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002660 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 }
2662
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002663 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2664 String destCodePath, String destResPath) {
2665 pkg.mPath = pkg.mScanPath = destCodePath;
2666 pkg.applicationInfo.sourceDir = destCodePath;
2667 pkg.applicationInfo.publicSourceDir = destResPath;
2668 }
2669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 private static String fixProcessName(String defProcessName,
2671 String processName, int uid) {
2672 if (processName == null) {
2673 return defProcessName;
2674 }
2675 return processName;
2676 }
2677
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002678 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002679 PackageParser.Package pkg) {
2680 if (pkgSetting.signatures.mSignatures != null) {
2681 // Already existing package. Make sure signatures match
2682 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2683 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002684 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002685 + " signatures do not match the previously installed version; ignoring!");
2686 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687 return false;
2688 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002689 }
2690 // Check for shared user signatures
2691 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2692 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2693 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2694 Slog.e(TAG, "Package " + pkg.packageName
2695 + " has no signatures that match those in shared user "
2696 + pkgSetting.sharedUser.name + "; ignoring!");
2697 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2698 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 }
2701 return true;
2702 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002703
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002704 public boolean performDexOpt(String packageName) {
2705 if (!mNoDexOpt) {
2706 return false;
2707 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002708
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002709 PackageParser.Package p;
2710 synchronized (mPackages) {
2711 p = mPackages.get(packageName);
2712 if (p == null || p.mDidDexOpt) {
2713 return false;
2714 }
2715 }
2716 synchronized (mInstallLock) {
2717 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2718 }
2719 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002720
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002721 static final int DEX_OPT_SKIPPED = 0;
2722 static final int DEX_OPT_PERFORMED = 1;
2723 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002724
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002725 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2726 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002727 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002728 String path = pkg.mScanPath;
2729 int ret = 0;
2730 try {
2731 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002732 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002733 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002734 pkg.mDidDexOpt = true;
2735 performed = true;
2736 }
2737 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002738 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002739 ret = -1;
2740 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002741 Slog.w(TAG, "IOException reading apk: " + path, e);
2742 ret = -1;
2743 } catch (dalvik.system.StaleDexCacheError e) {
2744 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2745 ret = -1;
2746 } catch (Exception e) {
2747 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002748 ret = -1;
2749 }
2750 if (ret < 0) {
2751 //error from installer
2752 return DEX_OPT_FAILED;
2753 }
2754 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002755
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002756 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2757 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002758
2759 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2760 return Environment.isEncryptedFilesystemEnabled() &&
2761 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2762 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002763
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002764 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2765 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002766 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002767 + " to " + newPkg.packageName
2768 + ": old package not in system partition");
2769 return false;
2770 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002771 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002772 + " to " + newPkg.packageName
2773 + ": old package still exists");
2774 return false;
2775 }
2776 return true;
2777 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002778
2779 private File getDataPathForPackage(PackageParser.Package pkg) {
2780 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2781 File dataPath;
2782 if (useEncryptedFSDir) {
2783 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2784 } else {
2785 dataPath = new File(mAppDataDir, pkg.packageName);
2786 }
2787 return dataPath;
2788 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002789
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002790 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2791 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002792 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002793 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2794 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002795 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002796 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002797 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2798 return null;
2799 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800 mScanningPath = scanFile;
2801 if (pkg == null) {
2802 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2803 return null;
2804 }
2805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2807 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2808 }
2809
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002810 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002811 synchronized (mPackages) {
2812 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002813 Slog.w(TAG, "*************************************************");
2814 Slog.w(TAG, "Core android package being redefined. Skipping.");
2815 Slog.w(TAG, " file=" + mScanningPath);
2816 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2818 return null;
2819 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 // Set up information for our fall-back user intent resolution
2822 // activity.
2823 mPlatformPackage = pkg;
2824 pkg.mVersionCode = mSdkVersion;
2825 mAndroidApplication = pkg.applicationInfo;
2826 mResolveActivity.applicationInfo = mAndroidApplication;
2827 mResolveActivity.name = ResolverActivity.class.getName();
2828 mResolveActivity.packageName = mAndroidApplication.packageName;
2829 mResolveActivity.processName = mAndroidApplication.processName;
2830 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2831 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2832 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2833 mResolveActivity.exported = true;
2834 mResolveActivity.enabled = true;
2835 mResolveInfo.activityInfo = mResolveActivity;
2836 mResolveInfo.priority = 0;
2837 mResolveInfo.preferredOrder = 0;
2838 mResolveInfo.match = 0;
2839 mResolveComponentName = new ComponentName(
2840 mAndroidApplication.packageName, mResolveActivity.name);
2841 }
2842 }
2843
2844 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002845 TAG, "Scanning package " + pkg.packageName);
2846 if (mPackages.containsKey(pkg.packageName)
2847 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002848 Slog.w(TAG, "*************************************************");
2849 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002851 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2853 return null;
2854 }
2855
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002856 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002857 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2858 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 SharedUserSetting suid = null;
2861 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002862
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002863 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2864 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002865 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002866 pkg.mRealPackage = null;
2867 pkg.mAdoptPermissions = null;
2868 }
2869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 synchronized (mPackages) {
2871 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002872 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2873 if (mTmpSharedLibraries == null ||
2874 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2875 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2876 }
2877 int num = 0;
2878 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2879 for (int i=0; i<N; i++) {
2880 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002882 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002884 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2886 return null;
2887 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002888 mTmpSharedLibraries[num] = file;
2889 num++;
2890 }
2891 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2892 for (int i=0; i<N; i++) {
2893 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2894 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002895 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002896 + " desires unavailable shared library "
2897 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2898 } else {
2899 mTmpSharedLibraries[num] = file;
2900 num++;
2901 }
2902 }
2903 if (num > 0) {
2904 pkg.usesLibraryFiles = new String[num];
2905 System.arraycopy(mTmpSharedLibraries, 0,
2906 pkg.usesLibraryFiles, 0, num);
2907 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002908
Dianne Hackborn49237342009-08-27 20:08:01 -07002909 if (pkg.reqFeatures != null) {
2910 N = pkg.reqFeatures.size();
2911 for (int i=0; i<N; i++) {
2912 FeatureInfo fi = pkg.reqFeatures.get(i);
2913 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2914 // Don't care.
2915 continue;
2916 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002917
Dianne Hackborn49237342009-08-27 20:08:01 -07002918 if (fi.name != null) {
2919 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002920 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002921 + " requires unavailable feature "
2922 + fi.name + "; failing!");
2923 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2924 return null;
2925 }
2926 }
2927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002928 }
2929 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 if (pkg.mSharedUserId != null) {
2932 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2933 pkg.applicationInfo.flags, true);
2934 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002935 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 + " for shared user failed");
2937 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2938 return null;
2939 }
2940 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2941 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2942 + suid.userId + "): packages=" + suid.packages);
2943 }
2944 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002945
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002946 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002947 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002948 Log.w(TAG, "WAITING FOR DEBUGGER");
2949 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002950 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2951 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002952 }
2953 }
2954
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002955 // Check if we are renaming from an original package name.
2956 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002957 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002958 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002959 // This package may need to be renamed to a previously
2960 // installed name. Let's check on that...
2961 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002962 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002963 // This package had originally been installed as the
2964 // original name, and we have already taken care of
2965 // transitioning to the new one. Just update the new
2966 // one to continue using the old name.
2967 realName = pkg.mRealPackage;
2968 if (!pkg.packageName.equals(renamed)) {
2969 // Callers into this function may have already taken
2970 // care of renaming the package; only do it here if
2971 // it is not already done.
2972 pkg.setPackageName(renamed);
2973 }
2974
Dianne Hackbornc1552392010-03-03 16:19:01 -08002975 } else {
2976 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2977 if ((origPackage=mSettings.peekPackageLP(
2978 pkg.mOriginalPackages.get(i))) != null) {
2979 // We do have the package already installed under its
2980 // original name... should we use it?
2981 if (!verifyPackageUpdate(origPackage, pkg)) {
2982 // New package is not compatible with original.
2983 origPackage = null;
2984 continue;
2985 } else if (origPackage.sharedUser != null) {
2986 // Make sure uid is compatible between packages.
2987 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002988 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002989 + " to " + pkg.packageName + ": old uid "
2990 + origPackage.sharedUser.name
2991 + " differs from " + pkg.mSharedUserId);
2992 origPackage = null;
2993 continue;
2994 }
2995 } else {
2996 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2997 + pkg.packageName + " to old name " + origPackage.name);
2998 }
2999 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003000 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003001 }
3002 }
3003 }
3004
3005 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003006 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003007 + " was transferred to another, but its .apk remains");
3008 }
3009
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003010 // Just create the setting, don't add it yet. For already existing packages
3011 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003012 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003013 destResourceFile, pkg.applicationInfo.flags, true, false);
3014 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003015 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3017 return null;
3018 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003019
3020 if (pkgSetting.origPackage != null) {
3021 // If we are first transitioning from an original package,
3022 // fix up the new package's name now. We need to do this after
3023 // looking up the package under its new name, so getPackageLP
3024 // can take care of fiddling things correctly.
3025 pkg.setPackageName(origPackage.name);
3026
3027 // File a report about this.
3028 String msg = "New package " + pkgSetting.realName
3029 + " renamed to replace old package " + pkgSetting.name;
3030 reportSettingsProblem(Log.WARN, msg);
3031
3032 // Make a note of it.
3033 mTransferedPackages.add(origPackage.name);
3034
3035 // No longer need to retain this.
3036 pkgSetting.origPackage = null;
3037 }
3038
3039 if (realName != null) {
3040 // Make a note of it.
3041 mTransferedPackages.add(pkg.packageName);
3042 }
3043
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003044 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003045 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3046 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 pkg.applicationInfo.uid = pkgSetting.userId;
3049 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003050
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003051 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003052 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003053 return null;
3054 }
3055 // The signature has changed, but this package is in the system
3056 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003057 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058 // However... if this package is part of a shared user, but it
3059 // doesn't match the signature of the shared user, let's fail.
3060 // What this means is that you can't change the signatures
3061 // associated with an overall shared user, which doesn't seem all
3062 // that unreasonable.
3063 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003064 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3065 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3066 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003067 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3068 return null;
3069 }
3070 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003071 // File a report about this.
3072 String msg = "System package " + pkg.packageName
3073 + " signature changed; retaining data.";
3074 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003076
The Android Open Source Project10592532009-03-18 17:39:46 -07003077 // Verify that this new package doesn't have any content providers
3078 // that conflict with existing packages. Only do this if the
3079 // package isn't already installed, since we don't want to break
3080 // things that are installed.
3081 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3082 int N = pkg.providers.size();
3083 int i;
3084 for (i=0; i<N; i++) {
3085 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003086 if (p.info.authority != null) {
3087 String names[] = p.info.authority.split(";");
3088 for (int j = 0; j < names.length; j++) {
3089 if (mProviders.containsKey(names[j])) {
3090 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003091 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003092 " (in package " + pkg.applicationInfo.packageName +
3093 ") is already used by "
3094 + ((other != null && other.getComponentName() != null)
3095 ? other.getComponentName().getPackageName() : "?"));
3096 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3097 return null;
3098 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003099 }
3100 }
3101 }
3102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003103 }
3104
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003105 final String pkgName = pkg.packageName;
3106
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003107 if (pkg.mAdoptPermissions != null) {
3108 // This package wants to adopt ownership of permissions from
3109 // another package.
3110 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3111 String origName = pkg.mAdoptPermissions.get(i);
3112 PackageSetting orig = mSettings.peekPackageLP(origName);
3113 if (orig != null) {
3114 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003115 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003116 + origName + " to " + pkg.packageName);
3117 mSettings.transferPermissions(origName, pkg.packageName);
3118 }
3119 }
3120 }
3121 }
3122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003123 long scanFileTime = scanFile.lastModified();
3124 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3125 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3126 pkg.applicationInfo.processName = fixProcessName(
3127 pkg.applicationInfo.packageName,
3128 pkg.applicationInfo.processName,
3129 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003130
3131 File dataPath;
3132 if (mPlatformPackage == pkg) {
3133 // The system package is special.
3134 dataPath = new File (Environment.getDataDirectory(), "system");
3135 pkg.applicationInfo.dataDir = dataPath.getPath();
3136 } else {
3137 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003138 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003139 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003140
3141 boolean uidError = false;
3142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003143 if (dataPath.exists()) {
3144 mOutPermissions[1] = 0;
3145 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3146 if (mOutPermissions[1] == pkg.applicationInfo.uid
3147 || !Process.supportsProcesses()) {
3148 pkg.applicationInfo.dataDir = dataPath.getPath();
3149 } else {
3150 boolean recovered = false;
3151 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3152 // If this is a system app, we can at least delete its
3153 // current data so the application will still work.
3154 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003155 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003156 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003157 // Old data gone!
3158 String msg = "System package " + pkg.packageName
3159 + " has changed from uid: "
3160 + mOutPermissions[1] + " to "
3161 + pkg.applicationInfo.uid + "; old data erased";
3162 reportSettingsProblem(Log.WARN, msg);
3163 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003165 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003166 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 pkg.applicationInfo.uid);
3168 if (ret == -1) {
3169 // Ack should not happen!
3170 msg = "System package " + pkg.packageName
3171 + " could not have data directory re-created after delete.";
3172 reportSettingsProblem(Log.WARN, msg);
3173 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3174 return null;
3175 }
3176 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 if (!recovered) {
3179 mHasSystemUidErrors = true;
3180 }
3181 }
3182 if (!recovered) {
3183 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3184 + pkg.applicationInfo.uid + "/fs_"
3185 + mOutPermissions[1];
3186 String msg = "Package " + pkg.packageName
3187 + " has mismatched uid: "
3188 + mOutPermissions[1] + " on disk, "
3189 + pkg.applicationInfo.uid + " in settings";
3190 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003191 mSettings.mReadMessages.append(msg);
3192 mSettings.mReadMessages.append('\n');
3193 uidError = true;
3194 if (!pkgSetting.uidError) {
3195 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197 }
3198 }
3199 }
3200 pkg.applicationInfo.dataDir = dataPath.getPath();
3201 } else {
3202 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3203 Log.v(TAG, "Want this data dir: " + dataPath);
3204 //invoke installer to do the actual installation
3205 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003206 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003207 pkg.applicationInfo.uid);
3208 if(ret < 0) {
3209 // Error from installer
3210 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3211 return null;
3212 }
3213 } else {
3214 dataPath.mkdirs();
3215 if (dataPath.exists()) {
3216 FileUtils.setPermissions(
3217 dataPath.toString(),
3218 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3219 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3220 }
3221 }
3222 if (dataPath.exists()) {
3223 pkg.applicationInfo.dataDir = dataPath.getPath();
3224 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003225 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226 pkg.applicationInfo.dataDir = null;
3227 }
3228 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003229
3230 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003231 }
3232
3233 // Perform shared library installation and dex validation and
3234 // optimization, if this is not a system app.
3235 if (mInstaller != null) {
3236 String path = scanFile.getPath();
3237 if (scanFileNewer) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003238 // Note: We don't want to unpack the native binaries for
3239 // system applications, unless they have been updated
3240 // (the binaries are already under /system/lib).
3241 //
3242 // In other words, we're going to unpack the binaries
3243 // only for non-system apps and system app upgrades.
3244 //
3245 int flags = pkg.applicationInfo.flags;
3246 if ((flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
3247 (flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3248 Log.i(TAG, path + " changed; unpacking");
3249 int err = cachePackageSharedLibsLI(pkg, scanFile);
3250 if (err != PackageManager.INSTALL_SUCCEEDED) {
3251 mLastScanError = err;
3252 return null;
3253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 }
3255 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003256 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003257
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003258 if ((scanMode&SCAN_NO_DEX) == 0) {
3259 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3261 return null;
3262 }
3263 }
3264 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003266 if (mFactoryTest && pkg.requestedPermissions.contains(
3267 android.Manifest.permission.FACTORY_TEST)) {
3268 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3269 }
3270
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003271 // Request the ActivityManager to kill the process(only for existing packages)
3272 // so that we do not end up in a confused state while the user is still using the older
3273 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003274 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003275 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003276 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003277 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003280 // We don't expect installation to fail beyond this point,
3281 if ((scanMode&SCAN_MONITOR) != 0) {
3282 mAppDirs.put(pkg.mPath, pkg);
3283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003285 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003286 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003287 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003288 // Make sure we don't accidentally delete its data.
3289 mSettings.mPackagesToBeCleaned.remove(pkgName);
3290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 int N = pkg.providers.size();
3292 StringBuilder r = null;
3293 int i;
3294 for (i=0; i<N; i++) {
3295 PackageParser.Provider p = pkg.providers.get(i);
3296 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3297 p.info.processName, pkg.applicationInfo.uid);
3298 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3299 p.info.name), p);
3300 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003301 if (p.info.authority != null) {
3302 String names[] = p.info.authority.split(";");
3303 p.info.authority = null;
3304 for (int j = 0; j < names.length; j++) {
3305 if (j == 1 && p.syncable) {
3306 // We only want the first authority for a provider to possibly be
3307 // syncable, so if we already added this provider using a different
3308 // authority clear the syncable flag. We copy the provider before
3309 // changing it because the mProviders object contains a reference
3310 // to a provider that we don't want to change.
3311 // Only do this for the second authority since the resulting provider
3312 // object can be the same for all future authorities for this provider.
3313 p = new PackageParser.Provider(p);
3314 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003316 if (!mProviders.containsKey(names[j])) {
3317 mProviders.put(names[j], p);
3318 if (p.info.authority == null) {
3319 p.info.authority = names[j];
3320 } else {
3321 p.info.authority = p.info.authority + ";" + names[j];
3322 }
3323 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3324 Log.d(TAG, "Registered content provider: " + names[j] +
3325 ", className = " + p.info.name +
3326 ", isSyncable = " + p.info.isSyncable);
3327 } else {
3328 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003329 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003330 " (in package " + pkg.applicationInfo.packageName +
3331 "): name already used by "
3332 + ((other != null && other.getComponentName() != null)
3333 ? other.getComponentName().getPackageName() : "?"));
3334 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 }
3336 }
3337 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3338 if (r == null) {
3339 r = new StringBuilder(256);
3340 } else {
3341 r.append(' ');
3342 }
3343 r.append(p.info.name);
3344 }
3345 }
3346 if (r != null) {
3347 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3348 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350 N = pkg.services.size();
3351 r = null;
3352 for (i=0; i<N; i++) {
3353 PackageParser.Service s = pkg.services.get(i);
3354 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3355 s.info.processName, pkg.applicationInfo.uid);
3356 mServices.addService(s);
3357 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3358 if (r == null) {
3359 r = new StringBuilder(256);
3360 } else {
3361 r.append(' ');
3362 }
3363 r.append(s.info.name);
3364 }
3365 }
3366 if (r != null) {
3367 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3368 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 N = pkg.receivers.size();
3371 r = null;
3372 for (i=0; i<N; i++) {
3373 PackageParser.Activity a = pkg.receivers.get(i);
3374 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3375 a.info.processName, pkg.applicationInfo.uid);
3376 mReceivers.addActivity(a, "receiver");
3377 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3378 if (r == null) {
3379 r = new StringBuilder(256);
3380 } else {
3381 r.append(' ');
3382 }
3383 r.append(a.info.name);
3384 }
3385 }
3386 if (r != null) {
3387 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3388 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003390 N = pkg.activities.size();
3391 r = null;
3392 for (i=0; i<N; i++) {
3393 PackageParser.Activity a = pkg.activities.get(i);
3394 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3395 a.info.processName, pkg.applicationInfo.uid);
3396 mActivities.addActivity(a, "activity");
3397 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3398 if (r == null) {
3399 r = new StringBuilder(256);
3400 } else {
3401 r.append(' ');
3402 }
3403 r.append(a.info.name);
3404 }
3405 }
3406 if (r != null) {
3407 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3408 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 N = pkg.permissionGroups.size();
3411 r = null;
3412 for (i=0; i<N; i++) {
3413 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3414 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3415 if (cur == null) {
3416 mPermissionGroups.put(pg.info.name, pg);
3417 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3418 if (r == null) {
3419 r = new StringBuilder(256);
3420 } else {
3421 r.append(' ');
3422 }
3423 r.append(pg.info.name);
3424 }
3425 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003426 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 + pg.info.packageName + " ignored: original from "
3428 + cur.info.packageName);
3429 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3430 if (r == null) {
3431 r = new StringBuilder(256);
3432 } else {
3433 r.append(' ');
3434 }
3435 r.append("DUP:");
3436 r.append(pg.info.name);
3437 }
3438 }
3439 }
3440 if (r != null) {
3441 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3442 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003444 N = pkg.permissions.size();
3445 r = null;
3446 for (i=0; i<N; i++) {
3447 PackageParser.Permission p = pkg.permissions.get(i);
3448 HashMap<String, BasePermission> permissionMap =
3449 p.tree ? mSettings.mPermissionTrees
3450 : mSettings.mPermissions;
3451 p.group = mPermissionGroups.get(p.info.group);
3452 if (p.info.group == null || p.group != null) {
3453 BasePermission bp = permissionMap.get(p.info.name);
3454 if (bp == null) {
3455 bp = new BasePermission(p.info.name, p.info.packageName,
3456 BasePermission.TYPE_NORMAL);
3457 permissionMap.put(p.info.name, bp);
3458 }
3459 if (bp.perm == null) {
3460 if (bp.sourcePackage == null
3461 || bp.sourcePackage.equals(p.info.packageName)) {
3462 BasePermission tree = findPermissionTreeLP(p.info.name);
3463 if (tree == null
3464 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003465 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003466 bp.perm = p;
3467 bp.uid = pkg.applicationInfo.uid;
3468 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3469 if (r == null) {
3470 r = new StringBuilder(256);
3471 } else {
3472 r.append(' ');
3473 }
3474 r.append(p.info.name);
3475 }
3476 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003477 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 + p.info.packageName + " ignored: base tree "
3479 + tree.name + " is from package "
3480 + tree.sourcePackage);
3481 }
3482 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003483 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 + p.info.packageName + " ignored: original from "
3485 + bp.sourcePackage);
3486 }
3487 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3488 if (r == null) {
3489 r = new StringBuilder(256);
3490 } else {
3491 r.append(' ');
3492 }
3493 r.append("DUP:");
3494 r.append(p.info.name);
3495 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003496 if (bp.perm == p) {
3497 bp.protectionLevel = p.info.protectionLevel;
3498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003499 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003500 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 + p.info.packageName + " ignored: no group "
3502 + p.group);
3503 }
3504 }
3505 if (r != null) {
3506 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3507 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003509 N = pkg.instrumentation.size();
3510 r = null;
3511 for (i=0; i<N; i++) {
3512 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3513 a.info.packageName = pkg.applicationInfo.packageName;
3514 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3515 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3516 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003517 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3519 if (r == null) {
3520 r = new StringBuilder(256);
3521 } else {
3522 r.append(' ');
3523 }
3524 r.append(a.info.name);
3525 }
3526 }
3527 if (r != null) {
3528 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3529 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003530
Dianne Hackborn854060af2009-07-09 18:14:31 -07003531 if (pkg.protectedBroadcasts != null) {
3532 N = pkg.protectedBroadcasts.size();
3533 for (i=0; i<N; i++) {
3534 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3535 }
3536 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003538 pkgSetting.setTimeStamp(scanFileTime);
3539 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 return pkg;
3542 }
3543
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003544 private void killApplication(String pkgName, int uid) {
3545 // Request the ActivityManager to kill the process(only for existing packages)
3546 // so that we do not end up in a confused state while the user is still using the older
3547 // version of the application while the new one gets installed.
3548 IActivityManager am = ActivityManagerNative.getDefault();
3549 if (am != null) {
3550 try {
3551 am.killApplicationWithUid(pkgName, uid);
3552 } catch (RemoteException e) {
3553 }
3554 }
3555 }
3556
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003557 // The following constants are returned by cachePackageSharedLibsForAbiLI
3558 // to indicate if native shared libraries were found in the package.
3559 // Values are:
3560 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3561 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3562 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3563 // in package (and not installed)
3564 //
3565 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3566 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3567 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003569 // Return the path of the directory that will contain the native binaries
3570 // of a given installed package. This is relative to the data path.
3571 //
3572 private static File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3573 return new File(pkg.applicationInfo.dataDir + "/lib");
3574 }
3575
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003576 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3577 // and automatically copy them to /data/data/<appname>/lib if present.
3578 //
3579 // NOTE: this method may throw an IOException if the library cannot
3580 // be copied to its final destination, e.g. if there isn't enough
3581 // room left on the data partition, or a ZipException if the package
3582 // file is malformed.
3583 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003584 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003585 File scanFile, String cpuAbi) throws IOException, ZipException {
3586 File sharedLibraryDir = getNativeBinaryDirForPackage(pkg);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003587 final String apkLib = "lib/";
3588 final int apkLibLen = apkLib.length();
3589 final int cpuAbiLen = cpuAbi.length();
3590 final String libPrefix = "lib";
3591 final int libPrefixLen = libPrefix.length();
3592 final String libSuffix = ".so";
3593 final int libSuffixLen = libSuffix.length();
3594 boolean hasNativeLibraries = false;
3595 boolean installedNativeLibraries = false;
3596
3597 // the minimum length of a valid native shared library of the form
3598 // lib/<something>/lib<name>.so.
3599 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3600
3601 ZipFile zipFile = new ZipFile(scanFile);
3602 Enumeration<ZipEntry> entries =
3603 (Enumeration<ZipEntry>) zipFile.entries();
3604
3605 while (entries.hasMoreElements()) {
3606 ZipEntry entry = entries.nextElement();
3607 // skip directories
3608 if (entry.isDirectory()) {
3609 continue;
3610 }
3611 String entryName = entry.getName();
3612
3613 // check that the entry looks like lib/<something>/lib<name>.so
3614 // here, but don't check the ABI just yet.
3615 //
3616 // - must be sufficiently long
3617 // - must end with libSuffix, i.e. ".so"
3618 // - must start with apkLib, i.e. "lib/"
3619 if (entryName.length() < minEntryLen ||
3620 !entryName.endsWith(libSuffix) ||
3621 !entryName.startsWith(apkLib) ) {
3622 continue;
3623 }
3624
3625 // file name must start with libPrefix, i.e. "lib"
3626 int lastSlash = entryName.lastIndexOf('/');
3627
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003628 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003629 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3630 continue;
3631 }
3632
3633 hasNativeLibraries = true;
3634
3635 // check the cpuAbi now, between lib/ and /lib<name>.so
3636 //
3637 if (lastSlash != apkLibLen + cpuAbiLen ||
3638 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3639 continue;
3640
3641 // extract the library file name, ensure it doesn't contain
3642 // weird characters. we're guaranteed here that it doesn't contain
3643 // a directory separator though.
3644 String libFileName = entryName.substring(lastSlash+1);
3645 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3646 continue;
3647 }
3648
3649 installedNativeLibraries = true;
3650
3651 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3652 File.separator + libFileName;
3653 File sharedLibraryFile = new File(sharedLibraryFilePath);
3654 if (! sharedLibraryFile.exists() ||
3655 sharedLibraryFile.length() != entry.getSize() ||
3656 sharedLibraryFile.lastModified() != entry.getTime()) {
3657 if (Config.LOGD) {
3658 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003659 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003660 if (mInstaller == null) {
3661 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003662 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003663 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003664 sharedLibraryFile);
3665 }
3666 }
3667 if (!hasNativeLibraries)
3668 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3669
3670 if (!installedNativeLibraries)
3671 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3672
3673 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3674 }
3675
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003676 // Find the gdbserver executable program in a package at
3677 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3678 //
3679 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3680 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3681 //
3682 private int cachePackageGdbServerLI(PackageParser.Package pkg,
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003683 File scanFile, String cpuAbi) throws IOException, ZipException {
3684 File installGdbServerDir = getNativeBinaryDirForPackage(pkg);
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003685 final String GDBSERVER = "gdbserver";
3686 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3687
3688 ZipFile zipFile = new ZipFile(scanFile);
3689 Enumeration<ZipEntry> entries =
3690 (Enumeration<ZipEntry>) zipFile.entries();
3691
3692 while (entries.hasMoreElements()) {
3693 ZipEntry entry = entries.nextElement();
3694 // skip directories
3695 if (entry.isDirectory()) {
3696 continue;
3697 }
3698 String entryName = entry.getName();
3699
3700 if (!entryName.equals(apkGdbServerPath)) {
3701 continue;
3702 }
3703
3704 String installGdbServerPath = installGdbServerDir.getPath() +
3705 "/" + GDBSERVER;
3706 File installGdbServerFile = new File(installGdbServerPath);
3707 if (! installGdbServerFile.exists() ||
3708 installGdbServerFile.length() != entry.getSize() ||
3709 installGdbServerFile.lastModified() != entry.getTime()) {
3710 if (Config.LOGD) {
3711 Log.d(TAG, "Caching gdbserver " + entry.getName());
3712 }
3713 if (mInstaller == null) {
3714 installGdbServerDir.mkdir();
3715 }
3716 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3717 installGdbServerFile);
3718 }
3719 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3720 }
3721 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3722 }
3723
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003724 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3725 // and copy them to /data/data/<appname>/lib.
3726 //
3727 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3728 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3729 // one if ro.product.cpu.abi2 is defined.
3730 //
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003731 private int cachePackageSharedLibsLI(PackageParser.Package pkg, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003732 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003733 try {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003734 int result = cachePackageSharedLibsForAbiLI(pkg, scanFile, cpuAbi);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003735
3736 // some architectures are capable of supporting several CPU ABIs
3737 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3738 // this is indicated by the definition of the ro.product.cpu.abi2
3739 // system property.
3740 //
3741 // only scan the package twice in case of ABI mismatch
3742 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003743 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003744 if (cpuAbi2 != null) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003745 result = cachePackageSharedLibsForAbiLI(pkg, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003747
3748 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003749 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003750 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003752
3753 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3754 cpuAbi = cpuAbi2;
3755 }
3756 }
3757
3758 // for debuggable packages, also extract gdbserver from lib/<abi>
3759 // into /data/data/<appname>/lib too.
3760 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3761 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003762 int result2 = cachePackageGdbServerLI(pkg, scanFile, cpuAbi);
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003763 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3764 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003766 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003767 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003768 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003769 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003771 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003772 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003773 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003774 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003775 }
3776
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003777 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003779 File binaryDir,
3780 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003781 InputStream inputStream = zipFile.getInputStream(entry);
3782 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003783 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003784 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003785 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003786 // now need to be left as world readable and owned by the system.
3787 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3788 ! tempFile.setLastModified(entry.getTime()) ||
3789 FileUtils.setPermissions(tempFilePath,
3790 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003791 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003792 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003793 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794 // Failed to properly write file.
3795 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003796 throw new IOException("Couldn't create cached binary "
3797 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003798 }
3799 } finally {
3800 inputStream.close();
3801 }
3802 }
3803
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003804 // Remove the native binaries of a given package. This simply
3805 // gets rid of the files in the 'lib' sub-directory.
3806 private void removeNativeBinariesLI(PackageParser.Package pkg) {
3807 File binaryDir = getNativeBinaryDirForPackage(pkg);
3808
3809 if (DEBUG_NATIVE) {
3810 Slog.w(TAG,"Deleting native binaries from: " + binaryDir.getPath());
3811 }
3812
3813 // Just remove any file in the directory. Since the directory
3814 // is owned by the 'system' UID, the application is not supposed
3815 // to have written anything there.
3816 //
3817 if (binaryDir.exists()) {
3818 File[] binaries = binaryDir.listFiles();
3819 if (binaries != null) {
3820 for (int nn=0; nn < binaries.length; nn++) {
3821 if (DEBUG_NATIVE) {
3822 Slog.d(TAG," Deleting " + binaries[nn].getName());
3823 }
3824 if (!binaries[nn].delete()) {
3825 Slog.w(TAG,"Could not delete native binary: " +
3826 binaries[nn].getPath());
3827 }
3828 }
3829 }
3830 // Do not delete 'lib' directory itself, or this will prevent
3831 // installation of future updates.
3832 }
3833 }
3834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3836 if (chatty && Config.LOGD) Log.d(
3837 TAG, "Removing package " + pkg.applicationInfo.packageName );
3838
3839 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003840 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842 mPackages.remove(pkg.applicationInfo.packageName);
3843 if (pkg.mPath != null) {
3844 mAppDirs.remove(pkg.mPath);
3845 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003847 PackageSetting ps = (PackageSetting)pkg.mExtras;
3848 if (ps != null && ps.sharedUser != null) {
3849 // XXX don't do this until the data is removed.
3850 if (false) {
3851 ps.sharedUser.packages.remove(ps);
3852 if (ps.sharedUser.packages.size() == 0) {
3853 // Remove.
3854 }
3855 }
3856 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003858 int N = pkg.providers.size();
3859 StringBuilder r = null;
3860 int i;
3861 for (i=0; i<N; i++) {
3862 PackageParser.Provider p = pkg.providers.get(i);
3863 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3864 p.info.name));
3865 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 /* The is another ContentProvider with this authority when
3868 * this app was installed so this authority is null,
3869 * Ignore it as we don't have to unregister the provider.
3870 */
3871 continue;
3872 }
3873 String names[] = p.info.authority.split(";");
3874 for (int j = 0; j < names.length; j++) {
3875 if (mProviders.get(names[j]) == p) {
3876 mProviders.remove(names[j]);
3877 if (chatty && Config.LOGD) Log.d(
3878 TAG, "Unregistered content provider: " + names[j] +
3879 ", className = " + p.info.name +
3880 ", isSyncable = " + p.info.isSyncable);
3881 }
3882 }
3883 if (chatty) {
3884 if (r == null) {
3885 r = new StringBuilder(256);
3886 } else {
3887 r.append(' ');
3888 }
3889 r.append(p.info.name);
3890 }
3891 }
3892 if (r != null) {
3893 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3894 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 N = pkg.services.size();
3897 r = null;
3898 for (i=0; i<N; i++) {
3899 PackageParser.Service s = pkg.services.get(i);
3900 mServices.removeService(s);
3901 if (chatty) {
3902 if (r == null) {
3903 r = new StringBuilder(256);
3904 } else {
3905 r.append(' ');
3906 }
3907 r.append(s.info.name);
3908 }
3909 }
3910 if (r != null) {
3911 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3912 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003914 N = pkg.receivers.size();
3915 r = null;
3916 for (i=0; i<N; i++) {
3917 PackageParser.Activity a = pkg.receivers.get(i);
3918 mReceivers.removeActivity(a, "receiver");
3919 if (chatty) {
3920 if (r == null) {
3921 r = new StringBuilder(256);
3922 } else {
3923 r.append(' ');
3924 }
3925 r.append(a.info.name);
3926 }
3927 }
3928 if (r != null) {
3929 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3930 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003932 N = pkg.activities.size();
3933 r = null;
3934 for (i=0; i<N; i++) {
3935 PackageParser.Activity a = pkg.activities.get(i);
3936 mActivities.removeActivity(a, "activity");
3937 if (chatty) {
3938 if (r == null) {
3939 r = new StringBuilder(256);
3940 } else {
3941 r.append(' ');
3942 }
3943 r.append(a.info.name);
3944 }
3945 }
3946 if (r != null) {
3947 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3948 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950 N = pkg.permissions.size();
3951 r = null;
3952 for (i=0; i<N; i++) {
3953 PackageParser.Permission p = pkg.permissions.get(i);
3954 boolean tree = false;
3955 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3956 if (bp == null) {
3957 tree = true;
3958 bp = mSettings.mPermissionTrees.get(p.info.name);
3959 }
3960 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003961 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 if (chatty) {
3963 if (r == null) {
3964 r = new StringBuilder(256);
3965 } else {
3966 r.append(' ');
3967 }
3968 r.append(p.info.name);
3969 }
3970 }
3971 }
3972 if (r != null) {
3973 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3974 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003976 N = pkg.instrumentation.size();
3977 r = null;
3978 for (i=0; i<N; i++) {
3979 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003980 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003981 if (chatty) {
3982 if (r == null) {
3983 r = new StringBuilder(256);
3984 } else {
3985 r.append(' ');
3986 }
3987 r.append(a.info.name);
3988 }
3989 }
3990 if (r != null) {
3991 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3992 }
3993 }
3994 }
3995
3996 private static final boolean isPackageFilename(String name) {
3997 return name != null && name.endsWith(".apk");
3998 }
3999
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004000 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
4001 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
4002 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
4003 return true;
4004 }
4005 }
4006 return false;
4007 }
4008
4009 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004010 PackageParser.Package pkgInfo, boolean grantPermissions,
4011 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 // Make sure there are no dangling permission trees.
4013 Iterator<BasePermission> it = mSettings.mPermissionTrees
4014 .values().iterator();
4015 while (it.hasNext()) {
4016 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004017 if (bp.packageSetting == null) {
4018 // We may not yet have parsed the package, so just see if
4019 // we still know about its settings.
4020 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4021 }
4022 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004023 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024 + " from package " + bp.sourcePackage);
4025 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004026 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4027 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4028 Slog.i(TAG, "Removing old permission tree: " + bp.name
4029 + " from package " + bp.sourcePackage);
4030 grantPermissions = true;
4031 it.remove();
4032 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 }
4034 }
4035
4036 // Make sure all dynamic permissions have been assigned to a package,
4037 // and make sure there are no dangling permissions.
4038 it = mSettings.mPermissions.values().iterator();
4039 while (it.hasNext()) {
4040 BasePermission bp = it.next();
4041 if (bp.type == BasePermission.TYPE_DYNAMIC) {
4042 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
4043 + bp.name + " pkg=" + bp.sourcePackage
4044 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004045 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 BasePermission tree = findPermissionTreeLP(bp.name);
4047 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004048 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004049 bp.perm = new PackageParser.Permission(tree.perm.owner,
4050 new PermissionInfo(bp.pendingInfo));
4051 bp.perm.info.packageName = tree.perm.info.packageName;
4052 bp.perm.info.name = bp.name;
4053 bp.uid = tree.uid;
4054 }
4055 }
4056 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004057 if (bp.packageSetting == null) {
4058 // We may not yet have parsed the package, so just see if
4059 // we still know about its settings.
4060 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4061 }
4062 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004063 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004064 + " from package " + bp.sourcePackage);
4065 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004066 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4067 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4068 Slog.i(TAG, "Removing old permission: " + bp.name
4069 + " from package " + bp.sourcePackage);
4070 grantPermissions = true;
4071 it.remove();
4072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004073 }
4074 }
4075
4076 // Now update the permissions for all packages, in particular
4077 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004078 if (grantPermissions) {
4079 for (PackageParser.Package pkg : mPackages.values()) {
4080 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004081 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004082 }
4083 }
4084 }
4085
4086 if (pkgInfo != null) {
4087 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004088 }
4089 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004091 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
4092 final PackageSetting ps = (PackageSetting)pkg.mExtras;
4093 if (ps == null) {
4094 return;
4095 }
4096 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004097 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004099 if (replace) {
4100 ps.permissionsFixed = false;
4101 if (gp == ps) {
4102 gp.grantedPermissions.clear();
4103 gp.gids = mGlobalGids;
4104 }
4105 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004107 if (gp.gids == null) {
4108 gp.gids = mGlobalGids;
4109 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004111 final int N = pkg.requestedPermissions.size();
4112 for (int i=0; i<N; i++) {
4113 String name = pkg.requestedPermissions.get(i);
4114 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004115 if (false) {
4116 if (gp != ps) {
4117 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004118 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004119 }
4120 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004121 if (bp != null && bp.packageSetting != null) {
4122 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004123 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004124 boolean allowedSig = false;
4125 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
4126 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004127 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07004128 } else if (bp.packageSetting == null) {
4129 // This permission is invalid; skip it.
4130 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004131 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
4132 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
4133 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004135 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004136 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004137 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004138 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4139 // For updated system applications, the signatureOrSystem permission
4140 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004141 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004142 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
4143 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
4144 if(sysPs.grantedPermissions.contains(perm)) {
4145 allowed = true;
4146 } else {
4147 allowed = false;
4148 }
4149 } else {
4150 allowed = true;
4151 }
4152 }
4153 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004154 if (allowed) {
4155 allowedSig = true;
4156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004157 } else {
4158 allowed = false;
4159 }
4160 if (false) {
4161 if (gp != ps) {
4162 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4163 }
4164 }
4165 if (allowed) {
4166 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4167 && ps.permissionsFixed) {
4168 // If this is an existing, non-system package, then
4169 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004170 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004171 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004172 // Except... if this is a permission that was added
4173 // to the platform (note: need to only do this when
4174 // updating the platform).
4175 final int NP = PackageParser.NEW_PERMISSIONS.length;
4176 for (int ip=0; ip<NP; ip++) {
4177 final PackageParser.NewPermissionInfo npi
4178 = PackageParser.NEW_PERMISSIONS[ip];
4179 if (npi.name.equals(perm)
4180 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4181 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004182 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004183 + pkg.packageName);
4184 break;
4185 }
4186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004187 }
4188 }
4189 if (allowed) {
4190 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004191 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004192 gp.grantedPermissions.add(perm);
4193 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004194 } else if (!ps.haveGids) {
4195 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004196 }
4197 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004198 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 + " to package " + pkg.packageName
4200 + " because it was previously installed without");
4201 }
4202 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004203 if (gp.grantedPermissions.remove(perm)) {
4204 changedPermission = true;
4205 gp.gids = removeInts(gp.gids, bp.gids);
4206 Slog.i(TAG, "Un-granting permission " + perm
4207 + " from package " + pkg.packageName
4208 + " (protectionLevel=" + bp.protectionLevel
4209 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4210 + ")");
4211 } else {
4212 Slog.w(TAG, "Not granting permission " + perm
4213 + " to package " + pkg.packageName
4214 + " (protectionLevel=" + bp.protectionLevel
4215 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4216 + ")");
4217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004218 }
4219 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004220 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 + " in package " + pkg.packageName);
4222 }
4223 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004224
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004225 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004226 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4227 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004228 // This is the first that we have heard about this package, so the
4229 // permissions we have now selected are fixed until explicitly
4230 // changed.
4231 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004232 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004233 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004236 private final class ActivityIntentResolver
4237 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004238 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004239 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004240 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241 }
4242
Mihai Preda074edef2009-05-18 17:13:31 +02004243 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004244 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004245 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004246 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4247 }
4248
Mihai Predaeae850c2009-05-13 10:13:48 +02004249 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4250 ArrayList<PackageParser.Activity> packageActivities) {
4251 if (packageActivities == null) {
4252 return null;
4253 }
4254 mFlags = flags;
4255 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4256 int N = packageActivities.size();
4257 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4258 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004259
4260 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004261 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004262 intentFilters = packageActivities.get(i).intents;
4263 if (intentFilters != null && intentFilters.size() > 0) {
4264 listCut.add(intentFilters);
4265 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004266 }
4267 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4268 }
4269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004270 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004271 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004272 if (SHOW_INFO || Config.LOGV) Log.v(
4273 TAG, " " + type + " " +
4274 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4275 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4276 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004277 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004278 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4279 if (SHOW_INFO || Config.LOGV) {
4280 Log.v(TAG, " IntentFilter:");
4281 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4282 }
4283 if (!intent.debugCheck()) {
4284 Log.w(TAG, "==> For Activity " + a.info.name);
4285 }
4286 addFilter(intent);
4287 }
4288 }
4289
4290 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004291 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004292 if (SHOW_INFO || Config.LOGV) Log.v(
4293 TAG, " " + type + " " +
4294 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4295 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4296 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004297 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004298 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4299 if (SHOW_INFO || Config.LOGV) {
4300 Log.v(TAG, " IntentFilter:");
4301 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4302 }
4303 removeFilter(intent);
4304 }
4305 }
4306
4307 @Override
4308 protected boolean allowFilterResult(
4309 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4310 ActivityInfo filterAi = filter.activity.info;
4311 for (int i=dest.size()-1; i>=0; i--) {
4312 ActivityInfo destAi = dest.get(i).activityInfo;
4313 if (destAi.name == filterAi.name
4314 && destAi.packageName == filterAi.packageName) {
4315 return false;
4316 }
4317 }
4318 return true;
4319 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004321 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004322 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4323 return info.activity.owner.packageName;
4324 }
4325
4326 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004327 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4328 int match) {
4329 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4330 return null;
4331 }
4332 final PackageParser.Activity activity = info.activity;
4333 if (mSafeMode && (activity.info.applicationInfo.flags
4334 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4335 return null;
4336 }
4337 final ResolveInfo res = new ResolveInfo();
4338 res.activityInfo = PackageParser.generateActivityInfo(activity,
4339 mFlags);
4340 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4341 res.filter = info;
4342 }
4343 res.priority = info.getPriority();
4344 res.preferredOrder = activity.owner.mPreferredOrder;
4345 //System.out.println("Result: " + res.activityInfo.className +
4346 // " = " + res.priority);
4347 res.match = match;
4348 res.isDefault = info.hasDefault;
4349 res.labelRes = info.labelRes;
4350 res.nonLocalizedLabel = info.nonLocalizedLabel;
4351 res.icon = info.icon;
4352 return res;
4353 }
4354
4355 @Override
4356 protected void sortResults(List<ResolveInfo> results) {
4357 Collections.sort(results, mResolvePrioritySorter);
4358 }
4359
4360 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004361 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004362 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004363 out.print(prefix); out.print(
4364 Integer.toHexString(System.identityHashCode(filter.activity)));
4365 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004366 out.print(filter.activity.getComponentShortName());
4367 out.print(" filter ");
4368 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004369 }
4370
4371// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4372// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4373// final List<ResolveInfo> retList = Lists.newArrayList();
4374// while (i.hasNext()) {
4375// final ResolveInfo resolveInfo = i.next();
4376// if (isEnabledLP(resolveInfo.activityInfo)) {
4377// retList.add(resolveInfo);
4378// }
4379// }
4380// return retList;
4381// }
4382
4383 // Keys are String (activity class name), values are Activity.
4384 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4385 = new HashMap<ComponentName, PackageParser.Activity>();
4386 private int mFlags;
4387 }
4388
4389 private final class ServiceIntentResolver
4390 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004391 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004392 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004393 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004394 }
4395
Mihai Preda074edef2009-05-18 17:13:31 +02004396 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004397 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004398 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004399 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4400 }
4401
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004402 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4403 ArrayList<PackageParser.Service> packageServices) {
4404 if (packageServices == null) {
4405 return null;
4406 }
4407 mFlags = flags;
4408 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4409 int N = packageServices.size();
4410 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4411 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4412
4413 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4414 for (int i = 0; i < N; ++i) {
4415 intentFilters = packageServices.get(i).intents;
4416 if (intentFilters != null && intentFilters.size() > 0) {
4417 listCut.add(intentFilters);
4418 }
4419 }
4420 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4421 }
4422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004423 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004424 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004425 if (SHOW_INFO || Config.LOGV) Log.v(
4426 TAG, " " + (s.info.nonLocalizedLabel != null
4427 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4428 if (SHOW_INFO || Config.LOGV) Log.v(
4429 TAG, " Class=" + s.info.name);
4430 int NI = s.intents.size();
4431 int j;
4432 for (j=0; j<NI; j++) {
4433 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4434 if (SHOW_INFO || Config.LOGV) {
4435 Log.v(TAG, " IntentFilter:");
4436 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4437 }
4438 if (!intent.debugCheck()) {
4439 Log.w(TAG, "==> For Service " + s.info.name);
4440 }
4441 addFilter(intent);
4442 }
4443 }
4444
4445 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004446 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004447 if (SHOW_INFO || Config.LOGV) Log.v(
4448 TAG, " " + (s.info.nonLocalizedLabel != null
4449 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4450 if (SHOW_INFO || Config.LOGV) Log.v(
4451 TAG, " Class=" + s.info.name);
4452 int NI = s.intents.size();
4453 int j;
4454 for (j=0; j<NI; j++) {
4455 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4456 if (SHOW_INFO || Config.LOGV) {
4457 Log.v(TAG, " IntentFilter:");
4458 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4459 }
4460 removeFilter(intent);
4461 }
4462 }
4463
4464 @Override
4465 protected boolean allowFilterResult(
4466 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4467 ServiceInfo filterSi = filter.service.info;
4468 for (int i=dest.size()-1; i>=0; i--) {
4469 ServiceInfo destAi = dest.get(i).serviceInfo;
4470 if (destAi.name == filterSi.name
4471 && destAi.packageName == filterSi.packageName) {
4472 return false;
4473 }
4474 }
4475 return true;
4476 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004478 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004479 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4480 return info.service.owner.packageName;
4481 }
4482
4483 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004484 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4485 int match) {
4486 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4487 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4488 return null;
4489 }
4490 final PackageParser.Service service = info.service;
4491 if (mSafeMode && (service.info.applicationInfo.flags
4492 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4493 return null;
4494 }
4495 final ResolveInfo res = new ResolveInfo();
4496 res.serviceInfo = PackageParser.generateServiceInfo(service,
4497 mFlags);
4498 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4499 res.filter = filter;
4500 }
4501 res.priority = info.getPriority();
4502 res.preferredOrder = service.owner.mPreferredOrder;
4503 //System.out.println("Result: " + res.activityInfo.className +
4504 // " = " + res.priority);
4505 res.match = match;
4506 res.isDefault = info.hasDefault;
4507 res.labelRes = info.labelRes;
4508 res.nonLocalizedLabel = info.nonLocalizedLabel;
4509 res.icon = info.icon;
4510 return res;
4511 }
4512
4513 @Override
4514 protected void sortResults(List<ResolveInfo> results) {
4515 Collections.sort(results, mResolvePrioritySorter);
4516 }
4517
4518 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004519 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004521 out.print(prefix); out.print(
4522 Integer.toHexString(System.identityHashCode(filter.service)));
4523 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004524 out.print(filter.service.getComponentShortName());
4525 out.print(" filter ");
4526 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004527 }
4528
4529// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4530// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4531// final List<ResolveInfo> retList = Lists.newArrayList();
4532// while (i.hasNext()) {
4533// final ResolveInfo resolveInfo = (ResolveInfo) i;
4534// if (isEnabledLP(resolveInfo.serviceInfo)) {
4535// retList.add(resolveInfo);
4536// }
4537// }
4538// return retList;
4539// }
4540
4541 // Keys are String (activity class name), values are Activity.
4542 private final HashMap<ComponentName, PackageParser.Service> mServices
4543 = new HashMap<ComponentName, PackageParser.Service>();
4544 private int mFlags;
4545 };
4546
4547 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4548 new Comparator<ResolveInfo>() {
4549 public int compare(ResolveInfo r1, ResolveInfo r2) {
4550 int v1 = r1.priority;
4551 int v2 = r2.priority;
4552 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4553 if (v1 != v2) {
4554 return (v1 > v2) ? -1 : 1;
4555 }
4556 v1 = r1.preferredOrder;
4557 v2 = r2.preferredOrder;
4558 if (v1 != v2) {
4559 return (v1 > v2) ? -1 : 1;
4560 }
4561 if (r1.isDefault != r2.isDefault) {
4562 return r1.isDefault ? -1 : 1;
4563 }
4564 v1 = r1.match;
4565 v2 = r2.match;
4566 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4567 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4568 }
4569 };
4570
4571 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4572 new Comparator<ProviderInfo>() {
4573 public int compare(ProviderInfo p1, ProviderInfo p2) {
4574 final int v1 = p1.initOrder;
4575 final int v2 = p2.initOrder;
4576 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4577 }
4578 };
4579
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004580 private static final void sendPackageBroadcast(String action, String pkg,
4581 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004582 IActivityManager am = ActivityManagerNative.getDefault();
4583 if (am != null) {
4584 try {
4585 final Intent intent = new Intent(action,
4586 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4587 if (extras != null) {
4588 intent.putExtras(extras);
4589 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004590 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004591 am.broadcastIntent(null, intent, null, finishedReceiver,
4592 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004593 } catch (RemoteException ex) {
4594 }
4595 }
4596 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004597
4598 public String nextPackageToClean(String lastPackage) {
4599 synchronized (mPackages) {
4600 if (!mMediaMounted) {
4601 // If the external storage is no longer mounted at this point,
4602 // the caller may not have been able to delete all of this
4603 // packages files and can not delete any more. Bail.
4604 return null;
4605 }
4606 if (lastPackage != null) {
4607 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4608 }
4609 return mSettings.mPackagesToBeCleaned.size() > 0
4610 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4611 }
4612 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004613
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004614 void schedulePackageCleaning(String packageName) {
4615 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4616 }
4617
4618 void startCleaningPackages() {
4619 synchronized (mPackages) {
4620 if (!mMediaMounted) {
4621 return;
4622 }
4623 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4624 return;
4625 }
4626 }
4627 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4628 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4629 IActivityManager am = ActivityManagerNative.getDefault();
4630 if (am != null) {
4631 try {
4632 am.startService(null, intent, null);
4633 } catch (RemoteException e) {
4634 }
4635 }
4636 }
4637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004638 private final class AppDirObserver extends FileObserver {
4639 public AppDirObserver(String path, int mask, boolean isrom) {
4640 super(path, mask);
4641 mRootDir = path;
4642 mIsRom = isrom;
4643 }
4644
4645 public void onEvent(int event, String path) {
4646 String removedPackage = null;
4647 int removedUid = -1;
4648 String addedPackage = null;
4649 int addedUid = -1;
4650
4651 synchronized (mInstallLock) {
4652 String fullPathStr = null;
4653 File fullPath = null;
4654 if (path != null) {
4655 fullPath = new File(mRootDir, path);
4656 fullPathStr = fullPath.getPath();
4657 }
4658
4659 if (Config.LOGV) Log.v(
4660 TAG, "File " + fullPathStr + " changed: "
4661 + Integer.toHexString(event));
4662
4663 if (!isPackageFilename(path)) {
4664 if (Config.LOGV) Log.v(
4665 TAG, "Ignoring change of non-package file: " + fullPathStr);
4666 return;
4667 }
4668
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004669 // Ignore packages that are being installed or
4670 // have just been installed.
4671 if (ignoreCodePath(fullPathStr)) {
4672 return;
4673 }
4674 PackageParser.Package p = null;
4675 synchronized (mPackages) {
4676 p = mAppDirs.get(fullPathStr);
4677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004678 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004679 if (p != null) {
4680 removePackageLI(p, true);
4681 removedPackage = p.applicationInfo.packageName;
4682 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004683 }
4684 }
4685
4686 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004687 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004688 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004689 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4690 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004691 PackageParser.PARSE_CHATTY |
4692 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004693 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004694 if (p != null) {
4695 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004696 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004697 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004698 }
4699 addedPackage = p.applicationInfo.packageName;
4700 addedUid = p.applicationInfo.uid;
4701 }
4702 }
4703 }
4704
4705 synchronized (mPackages) {
4706 mSettings.writeLP();
4707 }
4708 }
4709
4710 if (removedPackage != null) {
4711 Bundle extras = new Bundle(1);
4712 extras.putInt(Intent.EXTRA_UID, removedUid);
4713 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004714 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4715 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004716 }
4717 if (addedPackage != null) {
4718 Bundle extras = new Bundle(1);
4719 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004720 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4721 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004722 }
4723 }
4724
4725 private final String mRootDir;
4726 private final boolean mIsRom;
4727 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004729 /* Called when a downloaded package installation has been confirmed by the user */
4730 public void installPackage(
4731 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004732 installPackage(packageURI, observer, flags, null);
4733 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004734
Jacek Surazski65e13172009-04-28 15:26:38 +02004735 /* Called when a downloaded package installation has been confirmed by the user */
4736 public void installPackage(
4737 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4738 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004739 mContext.enforceCallingOrSelfPermission(
4740 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004741
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004742 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004743 msg.obj = new InstallParams(packageURI, observer, flags,
4744 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004745 mHandler.sendMessage(msg);
4746 }
4747
Christopher Tate1bb69062010-02-19 17:02:12 -08004748 public void finishPackageInstall(int token) {
4749 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4750 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4751 mHandler.sendMessage(msg);
4752 }
4753
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004754 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004755 // Queue up an async operation since the package installation may take a little while.
4756 mHandler.post(new Runnable() {
4757 public void run() {
4758 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004759 // Result object to be returned
4760 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004761 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004762 res.uid = -1;
4763 res.pkg = null;
4764 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004765 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004766 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004767 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004768 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004769 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004770 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004771 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004772
4773 // A restore should be performed at this point if (a) the install
4774 // succeeded, (b) the operation is not an update, and (c) the new
4775 // package has a backupAgent defined.
4776 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004777 boolean doRestore = (!update
4778 && res.pkg != null
4779 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004780
4781 // Set up the post-install work request bookkeeping. This will be used
4782 // and cleaned up by the post-install event handling regardless of whether
4783 // there's a restore pass performed. Token values are >= 1.
4784 int token;
4785 if (mNextInstallToken < 0) mNextInstallToken = 1;
4786 token = mNextInstallToken++;
4787
4788 PostInstallData data = new PostInstallData(args, res);
4789 mRunningInstalls.put(token, data);
4790 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4791
4792 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4793 // Pass responsibility to the Backup Manager. It will perform a
4794 // restore if appropriate, then pass responsibility back to the
4795 // Package Manager to run the post-install observer callbacks
4796 // and broadcasts.
4797 IBackupManager bm = IBackupManager.Stub.asInterface(
4798 ServiceManager.getService(Context.BACKUP_SERVICE));
4799 if (bm != null) {
4800 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4801 + " to BM for possible restore");
4802 try {
4803 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4804 } catch (RemoteException e) {
4805 // can't happen; the backup manager is local
4806 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004807 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004808 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004809 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004810 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004811 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004812 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004814 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004815
4816 if (!doRestore) {
4817 // No restore possible, or the Backup Manager was mysteriously not
4818 // available -- just fire the post-install work request directly.
4819 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4820 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4821 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004823 }
4824 });
4825 }
4826
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004827 abstract class HandlerParams {
4828 final static int MAX_RETRIES = 4;
4829 int retry = 0;
4830 final void startCopy() {
4831 try {
4832 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4833 retry++;
4834 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004835 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004836 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4837 handleServiceError();
4838 return;
4839 } else {
4840 handleStartCopy();
4841 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4842 mHandler.sendEmptyMessage(MCS_UNBIND);
4843 }
4844 } catch (RemoteException e) {
4845 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4846 mHandler.sendEmptyMessage(MCS_RECONNECT);
4847 }
4848 handleReturnCode();
4849 }
4850
4851 final void serviceError() {
4852 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4853 handleServiceError();
4854 handleReturnCode();
4855 }
4856 abstract void handleStartCopy() throws RemoteException;
4857 abstract void handleServiceError();
4858 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004859 }
4860
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004861 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004862 final IPackageInstallObserver observer;
4863 int flags;
4864 final Uri packageURI;
4865 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004866 private InstallArgs mArgs;
4867 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004868 InstallParams(Uri packageURI,
4869 IPackageInstallObserver observer, int flags,
4870 String installerPackageName) {
4871 this.packageURI = packageURI;
4872 this.flags = flags;
4873 this.observer = observer;
4874 this.installerPackageName = installerPackageName;
4875 }
4876
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004877 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4878 String packageName = pkgLite.packageName;
4879 int installLocation = pkgLite.installLocation;
4880 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4881 synchronized (mPackages) {
4882 PackageParser.Package pkg = mPackages.get(packageName);
4883 if (pkg != null) {
4884 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4885 // Check for updated system application.
4886 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4887 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004888 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004889 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4890 }
4891 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4892 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004893 if (onSd) {
4894 // Install flag overrides everything.
4895 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4896 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004897 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004898 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4899 // Application explicitly specified internal.
4900 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4901 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4902 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004903 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004904 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004905 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4906 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4907 }
4908 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004909 }
4910 }
4911 } else {
4912 // Invalid install. Return error code
4913 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4914 }
4915 }
4916 }
4917 // All the special cases have been taken care of.
4918 // Return result based on recommended install location.
4919 if (onSd) {
4920 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4921 }
4922 return pkgLite.recommendedInstallLocation;
4923 }
4924
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004925 /*
4926 * Invoke remote method to get package information and install
4927 * location values. Override install location based on default
4928 * policy if needed and then create install arguments based
4929 * on the install location.
4930 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004931 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004932 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004933 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4934 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004935 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4936 if (onInt && onSd) {
4937 // Check if both bits are set.
4938 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4939 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4940 } else if (fwdLocked && onSd) {
4941 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004942 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004943 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004944 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004945 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004946 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004947 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004948 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4949 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4950 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4951 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4952 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004953 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4954 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4955 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004956 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4957 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004958 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004959 // Override with defaults if needed.
4960 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004961 if (!onSd && !onInt) {
4962 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004963 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4964 // Set the flag to install on external media.
4965 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004966 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004967 } else {
4968 // Make sure the flag for installing on external
4969 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004970 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004971 flags &= ~PackageManager.INSTALL_EXTERNAL;
4972 }
4973 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004974 }
4975 }
4976 // Create the file args now.
4977 mArgs = createInstallArgs(this);
4978 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4979 // Create copy only if we are not in an erroneous state.
4980 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004981 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004982 }
4983 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004984 }
4985
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004986 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004987 void handleReturnCode() {
4988 processPendingInstall(mArgs, mRet);
4989 }
4990
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004991 @Override
4992 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004993 mArgs = createInstallArgs(this);
4994 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004995 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004996 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004997
4998 /*
4999 * Utility class used in movePackage api.
5000 * srcArgs and targetArgs are not set for invalid flags and make
5001 * sure to do null checks when invoking methods on them.
5002 * We probably want to return ErrorPrams for both failed installs
5003 * and moves.
5004 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005005 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005006 final IPackageMoveObserver observer;
5007 final int flags;
5008 final String packageName;
5009 final InstallArgs srcArgs;
5010 final InstallArgs targetArgs;
5011 int mRet;
5012 MoveParams(InstallArgs srcArgs,
5013 IPackageMoveObserver observer,
5014 int flags, String packageName) {
5015 this.srcArgs = srcArgs;
5016 this.observer = observer;
5017 this.flags = flags;
5018 this.packageName = packageName;
5019 if (srcArgs != null) {
5020 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
5021 targetArgs = createInstallArgs(packageUri, flags, packageName);
5022 } else {
5023 targetArgs = null;
5024 }
5025 }
5026
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005027 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005028 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5029 // Check for storage space on target medium
5030 if (!targetArgs.checkFreeStorage(mContainerService)) {
5031 Log.w(TAG, "Insufficient storage to install");
5032 return;
5033 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005034 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005035 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005036 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005037 if (DEBUG_SD_INSTALL) {
5038 StringBuilder builder = new StringBuilder();
5039 if (srcArgs != null) {
5040 builder.append("src: ");
5041 builder.append(srcArgs.getCodePath());
5042 }
5043 if (targetArgs != null) {
5044 builder.append(" target : ");
5045 builder.append(targetArgs.getCodePath());
5046 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005047 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005048 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005049 }
5050
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005051 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005052 void handleReturnCode() {
5053 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005054 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
5055 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
5056 currentStatus = PackageManager.MOVE_SUCCEEDED;
5057 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
5058 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
5059 }
5060 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005061 }
5062
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005063 @Override
5064 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005065 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005066 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005067 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005068
5069 private InstallArgs createInstallArgs(InstallParams params) {
5070 if (installOnSd(params.flags)) {
5071 return new SdInstallArgs(params);
5072 } else {
5073 return new FileInstallArgs(params);
5074 }
5075 }
5076
5077 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
5078 if (installOnSd(flags)) {
5079 return new SdInstallArgs(fullCodePath, fullResourcePath);
5080 } else {
5081 return new FileInstallArgs(fullCodePath, fullResourcePath);
5082 }
5083 }
5084
Suchi Amalapurapu9a212ad2010-05-18 11:06:53 -07005085 private InstallArgs createInstallArgs(Uri packageURI, int flags,
5086 String pkgName) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005087 if (installOnSd(flags)) {
5088 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
5089 return new SdInstallArgs(packageURI, cid);
5090 } else {
5091 return new FileInstallArgs(packageURI, pkgName);
5092 }
5093 }
5094
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005095 static abstract class InstallArgs {
5096 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005097 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005098 final int flags;
5099 final Uri packageURI;
5100 final String installerPackageName;
5101
5102 InstallArgs(Uri packageURI,
5103 IPackageInstallObserver observer, int flags,
5104 String installerPackageName) {
5105 this.packageURI = packageURI;
5106 this.flags = flags;
5107 this.observer = observer;
5108 this.installerPackageName = installerPackageName;
5109 }
5110
5111 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005112 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005113 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005114 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005115 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005116 abstract String getCodePath();
5117 abstract String getResourcePath();
5118 // Need installer lock especially for dex file removal.
5119 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005120 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005121 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005122 }
5123
5124 class FileInstallArgs extends InstallArgs {
5125 File installDir;
5126 String codeFileName;
5127 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005128 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005129
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005130 FileInstallArgs(InstallParams params) {
5131 super(params.packageURI, params.observer,
5132 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005133 }
5134
5135 FileInstallArgs(String fullCodePath, String fullResourcePath) {
5136 super(null, null, 0, null);
5137 File codeFile = new File(fullCodePath);
5138 installDir = codeFile.getParentFile();
5139 codeFileName = fullCodePath;
5140 resourceFileName = fullResourcePath;
5141 }
5142
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005143 FileInstallArgs(Uri packageURI, String pkgName) {
5144 super(packageURI, null, 0, null);
5145 boolean fwdLocked = isFwdLocked(flags);
5146 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5147 String apkName = getNextCodePath(null, pkgName, ".apk");
5148 codeFileName = new File(installDir, apkName + ".apk").getPath();
5149 resourceFileName = getResourcePathFromCodePath();
5150 }
5151
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005152 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5153 return imcs.checkFreeStorage(false, packageURI);
5154 }
5155
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005156 String getCodePath() {
5157 return codeFileName;
5158 }
5159
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005160 void createCopyFile() {
5161 boolean fwdLocked = isFwdLocked(flags);
5162 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5163 codeFileName = createTempPackageFile(installDir).getPath();
5164 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005165 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005166 }
5167
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005168 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005169 if (temp) {
5170 // Generate temp file name
5171 createCopyFile();
5172 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005173 // Get a ParcelFileDescriptor to write to the output file
5174 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005175 if (!created) {
5176 try {
5177 codeFile.createNewFile();
5178 // Set permissions
5179 if (!setPermissions()) {
5180 // Failed setting permissions.
5181 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5182 }
5183 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005184 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005185 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5186 }
5187 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005188 ParcelFileDescriptor out = null;
5189 try {
5190 out = ParcelFileDescriptor.open(codeFile,
5191 ParcelFileDescriptor.MODE_READ_WRITE);
5192 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005193 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005194 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5195 }
5196 // Copy the resource now
5197 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5198 try {
5199 if (imcs.copyResource(packageURI, out)) {
5200 ret = PackageManager.INSTALL_SUCCEEDED;
5201 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005202 } finally {
5203 try { if (out != null) out.close(); } catch (IOException e) {}
5204 }
5205 return ret;
5206 }
5207
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005208 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005209 if (status != PackageManager.INSTALL_SUCCEEDED) {
5210 cleanUp();
5211 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005212 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005213 }
5214
5215 boolean doRename(int status, final String pkgName, String oldCodePath) {
5216 if (status != PackageManager.INSTALL_SUCCEEDED) {
5217 cleanUp();
5218 return false;
5219 } else {
5220 // Rename based on packageName
5221 File codeFile = new File(getCodePath());
5222 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5223 File desFile = new File(installDir, apkName + ".apk");
5224 if (!codeFile.renameTo(desFile)) {
5225 return false;
5226 }
5227 // Reset paths since the file has been renamed.
5228 codeFileName = desFile.getPath();
5229 resourceFileName = getResourcePathFromCodePath();
5230 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005231 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005232 // Failed setting permissions.
5233 return false;
5234 }
5235 return true;
5236 }
5237 }
5238
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005239 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005240 if (status != PackageManager.INSTALL_SUCCEEDED) {
5241 cleanUp();
5242 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005243 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005244 }
5245
5246 String getResourcePath() {
5247 return resourceFileName;
5248 }
5249
5250 String getResourcePathFromCodePath() {
5251 String codePath = getCodePath();
5252 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5253 String apkNameOnly = getApkName(codePath);
5254 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5255 } else {
5256 return codePath;
5257 }
5258 }
5259
5260 private boolean cleanUp() {
5261 boolean ret = true;
5262 String sourceDir = getCodePath();
5263 String publicSourceDir = getResourcePath();
5264 if (sourceDir != null) {
5265 File sourceFile = new File(sourceDir);
5266 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005267 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005268 ret = false;
5269 }
5270 // Delete application's code and resources
5271 sourceFile.delete();
5272 }
5273 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5274 final File publicSourceFile = new File(publicSourceDir);
5275 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005276 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005277 }
5278 if (publicSourceFile.exists()) {
5279 publicSourceFile.delete();
5280 }
5281 }
5282 return ret;
5283 }
5284
5285 void cleanUpResourcesLI() {
5286 String sourceDir = getCodePath();
5287 if (cleanUp() && mInstaller != null) {
5288 int retCode = mInstaller.rmdex(sourceDir);
5289 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005290 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005291 + " at location "
5292 + sourceDir + ", retcode=" + retCode);
5293 // we don't consider this to be a failure of the core package deletion
5294 }
5295 }
5296 }
5297
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005298 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005299 // TODO Do this in a more elegant way later on. for now just a hack
5300 if (!isFwdLocked(flags)) {
5301 final int filePermissions =
5302 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5303 |FileUtils.S_IROTH;
5304 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5305 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005306 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005307 getCodePath()
5308 + ". The return code was: " + retCode);
5309 // TODO Define new internal error
5310 return false;
5311 }
5312 return true;
5313 }
5314 return true;
5315 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005316
5317 boolean doPostDeleteLI(boolean delete) {
5318 cleanUpResourcesLI();
5319 return true;
5320 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005321 }
5322
5323 class SdInstallArgs extends InstallArgs {
5324 String cid;
5325 String cachePath;
5326 static final String RES_FILE_NAME = "pkg.apk";
5327
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005328 SdInstallArgs(InstallParams params) {
5329 super(params.packageURI, params.observer,
5330 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005331 }
5332
5333 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005334 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005335 // Extract cid from fullCodePath
5336 int eidx = fullCodePath.lastIndexOf("/");
5337 String subStr1 = fullCodePath.substring(0, eidx);
5338 int sidx = subStr1.lastIndexOf("/");
5339 cid = subStr1.substring(sidx+1, eidx);
5340 cachePath = subStr1;
5341 }
5342
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005343 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005344 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5345 this.cid = cid;
Suchi Amalapurapu9a212ad2010-05-18 11:06:53 -07005346 cachePath = PackageHelper.getSdDir(cid);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005347 }
5348
5349 SdInstallArgs(Uri packageURI, String cid) {
5350 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005351 this.cid = cid;
5352 }
5353
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005354 void createCopyFile() {
5355 cid = getTempContainerId();
5356 }
5357
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005358 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5359 return imcs.checkFreeStorage(true, packageURI);
5360 }
5361
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005362 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005363 if (temp) {
5364 createCopyFile();
5365 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005366 cachePath = imcs.copyResourceToContainer(
5367 packageURI, cid,
5368 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005369 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5370 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005371 }
5372
5373 @Override
5374 String getCodePath() {
5375 return cachePath + "/" + RES_FILE_NAME;
5376 }
5377
5378 @Override
5379 String getResourcePath() {
5380 return cachePath + "/" + RES_FILE_NAME;
5381 }
5382
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005383 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005384 if (status != PackageManager.INSTALL_SUCCEEDED) {
5385 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005386 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005387 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005388 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005389 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005390 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005391 if (cachePath == null) {
5392 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5393 }
5394 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005395 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005396 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005397 }
5398
5399 boolean doRename(int status, final String pkgName,
5400 String oldCodePath) {
5401 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005402 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005403 if (PackageHelper.isContainerMounted(cid)) {
5404 // Unmount the container
5405 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005406 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005407 return false;
5408 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005409 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005410 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005411 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5412 " which might be stale. Will try to clean up.");
5413 // Clean up the stale container and proceed to recreate.
5414 if (!PackageHelper.destroySdDir(newCacheId)) {
5415 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5416 return false;
5417 }
5418 // Successfully cleaned up stale container. Try to rename again.
5419 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5420 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5421 + " inspite of cleaning it up.");
5422 return false;
5423 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005424 }
5425 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005426 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005427 newCachePath = PackageHelper.mountSdDir(newCacheId,
5428 getEncryptKey(), Process.SYSTEM_UID);
5429 } else {
5430 newCachePath = PackageHelper.getSdDir(newCacheId);
5431 }
5432 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005433 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005434 return false;
5435 }
5436 Log.i(TAG, "Succesfully renamed " + cid +
5437 " at path: " + cachePath + " to " + newCacheId +
5438 " at new path: " + newCachePath);
5439 cid = newCacheId;
5440 cachePath = newCachePath;
5441 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005442 }
5443
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005444 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005445 if (status != PackageManager.INSTALL_SUCCEEDED) {
5446 cleanUp();
5447 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005448 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005449 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005450 PackageHelper.mountSdDir(cid,
5451 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005452 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005453 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005454 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005455 }
5456
5457 private void cleanUp() {
5458 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005459 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005460 }
5461
5462 void cleanUpResourcesLI() {
5463 String sourceFile = getCodePath();
5464 // Remove dex file
5465 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005466 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005467 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005468 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005469 + " at location "
5470 + sourceFile.toString() + ", retcode=" + retCode);
5471 // we don't consider this to be a failure of the core package deletion
5472 }
5473 }
5474 cleanUp();
5475 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005476
5477 boolean matchContainer(String app) {
5478 if (cid.startsWith(app)) {
5479 return true;
5480 }
5481 return false;
5482 }
5483
5484 String getPackageName() {
5485 int idx = cid.lastIndexOf("-");
5486 if (idx == -1) {
5487 return cid;
5488 }
5489 return cid.substring(0, idx);
5490 }
5491
5492 boolean doPostDeleteLI(boolean delete) {
5493 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005494 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005495 if (mounted) {
5496 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005497 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005498 }
5499 if (ret && delete) {
5500 cleanUpResourcesLI();
5501 }
5502 return ret;
5503 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005504 };
5505
5506 // Utility method used to create code paths based on package name and available index.
5507 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5508 String idxStr = "";
5509 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005510 // Fall back to default value of idx=1 if prefix is not
5511 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005512 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005513 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005514 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005515 if (subStr.endsWith(suffix)) {
5516 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005517 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005518 // If oldCodePath already contains prefix find out the
5519 // ending index to either increment or decrement.
5520 int sidx = subStr.lastIndexOf(prefix);
5521 if (sidx != -1) {
5522 subStr = subStr.substring(sidx + prefix.length());
5523 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005524 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5525 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005526 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005527 try {
5528 idx = Integer.parseInt(subStr);
5529 if (idx <= 1) {
5530 idx++;
5531 } else {
5532 idx--;
5533 }
5534 } catch(NumberFormatException e) {
5535 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005536 }
5537 }
5538 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005539 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005540 return prefix + idxStr;
5541 }
5542
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005543 // Utility method used to ignore ADD/REMOVE events
5544 // by directory observer.
5545 private static boolean ignoreCodePath(String fullPathStr) {
5546 String apkName = getApkName(fullPathStr);
5547 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5548 if (idx != -1 && ((idx+1) < apkName.length())) {
5549 // Make sure the package ends with a numeral
5550 String version = apkName.substring(idx+1);
5551 try {
5552 Integer.parseInt(version);
5553 return true;
5554 } catch (NumberFormatException e) {}
5555 }
5556 return false;
5557 }
5558
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005559 // Utility method that returns the relative package path with respect
5560 // to the installation directory. Like say for /data/data/com.test-1.apk
5561 // string com.test-1 is returned.
5562 static String getApkName(String codePath) {
5563 if (codePath == null) {
5564 return null;
5565 }
5566 int sidx = codePath.lastIndexOf("/");
5567 int eidx = codePath.lastIndexOf(".");
5568 if (eidx == -1) {
5569 eidx = codePath.length();
5570 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005571 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005572 return null;
5573 }
5574 return codePath.substring(sidx+1, eidx);
5575 }
5576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 class PackageInstalledInfo {
5578 String name;
5579 int uid;
5580 PackageParser.Package pkg;
5581 int returnCode;
5582 PackageRemovedInfo removedInfo;
5583 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005585 /*
5586 * Install a non-existing package.
5587 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005588 private void installNewPackageLI(PackageParser.Package pkg,
5589 int parseFlags,
5590 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005591 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005592 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005593 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005594
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005595 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596 res.name = pkgName;
5597 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005598 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5599 // A package with the same name is already installed, though
5600 // it has been renamed to an older name. The package we
5601 // are trying to install should be installed as an update to
5602 // the existing one, but that has not been requested, so bail.
5603 Slog.w(TAG, "Attempt to re-install " + pkgName
5604 + " without first uninstalling package running as "
5605 + mSettings.mRenamedPackages.get(pkgName));
5606 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5607 return;
5608 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005609 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005610 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005611 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005612 + " without first uninstalling.");
5613 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5614 return;
5615 }
5616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005617 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005618 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005619 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005620 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005621 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5622 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5623 }
5624 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005625 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005626 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005627 res);
5628 // delete the partially installed application. the data directory will have to be
5629 // restored if it was already existing
5630 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5631 // remove package from internal structures. Note that we want deletePackageX to
5632 // delete the package data and cache directories that it created in
5633 // scanPackageLocked, unless those directories existed before we even tried to
5634 // install.
5635 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005636 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005637 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5638 res.removedInfo);
5639 }
5640 }
5641 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005642
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005643 private void replacePackageLI(PackageParser.Package pkg,
5644 int parseFlags,
5645 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005646 String installerPackageName, PackageInstalledInfo res) {
5647
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005648 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005649 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005650 // First find the old package info and check signatures
5651 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005652 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005653 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005654 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005655 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5656 return;
5657 }
5658 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005659 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005660 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005661 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005662 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005663 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005664 }
5665 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005667 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005668 PackageParser.Package pkg,
5669 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005670 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005671 PackageParser.Package newPackage = null;
5672 String pkgName = deletedPackage.packageName;
5673 boolean deletedPkg = true;
5674 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005675
Jacek Surazski65e13172009-04-28 15:26:38 +02005676 String oldInstallerPackageName = null;
5677 synchronized (mPackages) {
5678 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5679 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005681 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005682 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005683 res.removedInfo)) {
5684 // If the existing package was'nt successfully deleted
5685 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5686 deletedPkg = false;
5687 } else {
5688 // Successfully deleted the old package. Now proceed with re-installation
5689 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005690 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005691 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005692 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005693 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5694 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005695 }
5696 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005697 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005698 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005699 res);
5700 updatedSettings = true;
5701 }
5702 }
5703
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005704 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005705 // remove package from internal structures. Note that we want deletePackageX to
5706 // delete the package data and cache directories that it created in
5707 // scanPackageLocked, unless those directories existed before we even tried to
5708 // install.
5709 if(updatedSettings) {
5710 deletePackageLI(
5711 pkgName, true,
5712 PackageManager.DONT_DELETE_DATA,
5713 res.removedInfo);
5714 }
5715 // Since we failed to install the new package we need to restore the old
5716 // package that we deleted.
5717 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005718 File restoreFile = new File(deletedPackage.mPath);
5719 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005720 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005721 return;
5722 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005723 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005724 boolean oldOnSd = isExternal(deletedPackage);
5725 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5726 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5727 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5728 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5729 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5730 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5731 return;
5732 }
5733 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005734 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005735 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005736 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005737 mSettings.writeLP();
5738 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005739 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 }
5741 }
5742 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005745 PackageParser.Package pkg,
5746 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005747 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748 PackageParser.Package newPackage = null;
5749 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005750 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005751 PackageParser.PARSE_IS_SYSTEM;
5752 String packageName = deletedPackage.packageName;
5753 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5754 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005755 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005756 return;
5757 }
5758 PackageParser.Package oldPkg;
5759 PackageSetting oldPkgSetting;
5760 synchronized (mPackages) {
5761 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005762 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005763 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5764 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005765 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005766 return;
5767 }
5768 }
5769 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5770 res.removedInfo.removedPackage = packageName;
5771 // Remove existing system package
5772 removePackageLI(oldPkg, true);
5773 synchronized (mPackages) {
5774 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5775 }
5776
5777 // Successfully disabled the old package. Now proceed with re-installation
5778 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5779 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005780 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005781 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005782 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005783 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5784 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5785 }
5786 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005787 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005788 updatedSettings = true;
5789 }
5790
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005791 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005792 // Re installation failed. Restore old information
5793 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005794 if (newPackage != null) {
5795 removePackageLI(newPackage, true);
5796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005797 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005798 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005799 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005800 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005801 // Restore the old system information in Settings
5802 synchronized(mPackages) {
5803 if(updatedSettings) {
5804 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005805 mSettings.setInstallerPackageName(packageName,
5806 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005807 }
5808 mSettings.writeLP();
5809 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005810 } else {
5811 // If this is an update to an existing update, setup
5812 // to remove the existing update.
5813 synchronized (mPackages) {
5814 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5815 if (ps != null && ps.codePathString != null &&
5816 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
5817 int installFlags = 0;
5818 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
5819 oldPkgSetting.resourcePathString);
5820 }
5821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005822 }
5823 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005824
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005825 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005826 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005827 int retCode;
5828 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5829 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5830 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005831 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005832 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5833 }
5834 }
5835 return PackageManager.INSTALL_SUCCEEDED;
5836 }
5837
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005838 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005839 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005840 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005841 synchronized (mPackages) {
5842 //write settings. the installStatus will be incomplete at this stage.
5843 //note that the new package setting would have already been
5844 //added to mPackages. It hasn't been persisted yet.
5845 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5846 mSettings.writeLP();
5847 }
5848
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005849 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005850 != PackageManager.INSTALL_SUCCEEDED) {
5851 // Discontinue if moving dex files failed.
5852 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005853 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005854 if((res.returnCode = setPermissionsLI(newPackage))
5855 != PackageManager.INSTALL_SUCCEEDED) {
5856 if (mInstaller != null) {
5857 mInstaller.rmdex(newPackage.mScanPath);
5858 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005859 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005860 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005861 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005863 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005864 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005865 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005866 res.name = pkgName;
5867 res.uid = newPackage.applicationInfo.uid;
5868 res.pkg = newPackage;
5869 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005870 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005871 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5872 //to update install status
5873 mSettings.writeLP();
5874 }
5875 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005876
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005877 private void installPackageLI(InstallArgs args,
5878 boolean newInstall, PackageInstalledInfo res) {
5879 int pFlags = args.flags;
5880 String installerPackageName = args.installerPackageName;
5881 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005882 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005883 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005884 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005885 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005886 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005887 // Result object to be returned
5888 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5889
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005890 // Retrieve PackageSettings and parse package
5891 int parseFlags = PackageParser.PARSE_CHATTY |
5892 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5893 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5894 parseFlags |= mDefParseFlags;
5895 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5896 pp.setSeparateProcesses(mSeparateProcesses);
5897 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5898 null, mMetrics, parseFlags);
5899 if (pkg == null) {
5900 res.returnCode = pp.getParseError();
5901 return;
5902 }
5903 String pkgName = res.name = pkg.packageName;
5904 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5905 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5906 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5907 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005908 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005909 }
5910 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5911 res.returnCode = pp.getParseError();
5912 return;
5913 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005914 // Get rid of all references to package scan path via parser.
5915 pp = null;
5916 String oldCodePath = null;
5917 boolean systemApp = false;
5918 synchronized (mPackages) {
5919 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005920 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5921 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005922 if (pkg.mOriginalPackages != null
5923 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005924 && mPackages.containsKey(oldName)) {
5925 // This package is derived from an original package,
5926 // and this device has been updating from that original
5927 // name. We must continue using the original name, so
5928 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005929 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005930 pkgName = pkg.packageName;
5931 replace = true;
5932 } else if (mPackages.containsKey(pkgName)) {
5933 // This package, under its official name, already exists
5934 // on the device; we should replace it.
5935 replace = true;
5936 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005937 }
5938 PackageSetting ps = mSettings.mPackages.get(pkgName);
5939 if (ps != null) {
5940 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5941 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5942 systemApp = (ps.pkg.applicationInfo.flags &
5943 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005944 }
5945 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005946 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005947
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005948 if (systemApp && onSd) {
5949 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005950 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005951 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5952 return;
5953 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005954
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005955 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5956 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5957 return;
5958 }
5959 // Set application objects path explicitly after the rename
5960 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005961 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005962 replacePackageLI(pkg, parseFlags, scanMode,
5963 installerPackageName, res);
5964 } else {
5965 installNewPackageLI(pkg, parseFlags, scanMode,
5966 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005967 }
5968 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005969
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005970 private int setPermissionsLI(PackageParser.Package newPackage) {
5971 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005972 int retCode = 0;
5973 // TODO Gross hack but fix later. Ideally move this to be a post installation
5974 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005975 if ((newPackage.applicationInfo.flags
5976 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5977 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005978 try {
5979 extractPublicFiles(newPackage, destResourceFile);
5980 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005981 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 -08005982 " forward-locked app.");
5983 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5984 } finally {
5985 //TODO clean up the extracted public files
5986 }
5987 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005988 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005989 newPackage.applicationInfo.uid);
5990 } else {
5991 final int filePermissions =
5992 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005993 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005994 newPackage.applicationInfo.uid);
5995 }
5996 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005997 // The permissions on the resource file was set when it was copied for
5998 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005999 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006002 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006003 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006004 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006005 // TODO Define new internal error
6006 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 }
6008 return PackageManager.INSTALL_SUCCEEDED;
6009 }
6010
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006011 private boolean isForwardLocked(PackageParser.Package pkg) {
6012 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006013 }
6014
Suchi Amalapurapuae181712010-03-30 14:01:02 -07006015 private boolean isExternal(PackageParser.Package pkg) {
6016 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
6017 }
6018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006019 private void extractPublicFiles(PackageParser.Package newPackage,
6020 File publicZipFile) throws IOException {
6021 final ZipOutputStream publicZipOutStream =
6022 new ZipOutputStream(new FileOutputStream(publicZipFile));
6023 final ZipFile privateZip = new ZipFile(newPackage.mPath);
6024
6025 // Copy manifest, resources.arsc and res directory to public zip
6026
6027 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
6028 while (privateZipEntries.hasMoreElements()) {
6029 final ZipEntry zipEntry = privateZipEntries.nextElement();
6030 final String zipEntryName = zipEntry.getName();
6031 if ("AndroidManifest.xml".equals(zipEntryName)
6032 || "resources.arsc".equals(zipEntryName)
6033 || zipEntryName.startsWith("res/")) {
6034 try {
6035 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
6036 } catch (IOException e) {
6037 try {
6038 publicZipOutStream.close();
6039 throw e;
6040 } finally {
6041 publicZipFile.delete();
6042 }
6043 }
6044 }
6045 }
6046
6047 publicZipOutStream.close();
6048 FileUtils.setPermissions(
6049 publicZipFile.getAbsolutePath(),
6050 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
6051 -1, -1);
6052 }
6053
6054 private static void copyZipEntry(ZipEntry zipEntry,
6055 ZipFile inZipFile,
6056 ZipOutputStream outZipStream) throws IOException {
6057 byte[] buffer = new byte[4096];
6058 int num;
6059
6060 ZipEntry newEntry;
6061 if (zipEntry.getMethod() == ZipEntry.STORED) {
6062 // Preserve the STORED method of the input entry.
6063 newEntry = new ZipEntry(zipEntry);
6064 } else {
6065 // Create a new entry so that the compressed len is recomputed.
6066 newEntry = new ZipEntry(zipEntry.getName());
6067 }
6068 outZipStream.putNextEntry(newEntry);
6069
6070 InputStream data = inZipFile.getInputStream(zipEntry);
6071 while ((num = data.read(buffer)) > 0) {
6072 outZipStream.write(buffer, 0, num);
6073 }
6074 outZipStream.flush();
6075 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006077 private void deleteTempPackageFiles() {
6078 FilenameFilter filter = new FilenameFilter() {
6079 public boolean accept(File dir, String name) {
6080 return name.startsWith("vmdl") && name.endsWith(".tmp");
6081 }
6082 };
6083 String tmpFilesList[] = mAppInstallDir.list(filter);
6084 if(tmpFilesList == null) {
6085 return;
6086 }
6087 for(int i = 0; i < tmpFilesList.length; i++) {
6088 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
6089 tmpFile.delete();
6090 }
6091 }
6092
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006093 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006094 File tmpPackageFile;
6095 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006096 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006097 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006098 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006099 return null;
6100 }
6101 try {
6102 FileUtils.setPermissions(
6103 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6104 -1, -1);
6105 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006106 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006107 return null;
6108 }
6109 return tmpPackageFile;
6110 }
6111
6112 public void deletePackage(final String packageName,
6113 final IPackageDeleteObserver observer,
6114 final int flags) {
6115 mContext.enforceCallingOrSelfPermission(
6116 android.Manifest.permission.DELETE_PACKAGES, null);
6117 // Queue up an async operation since the package deletion may take a little while.
6118 mHandler.post(new Runnable() {
6119 public void run() {
6120 mHandler.removeCallbacks(this);
6121 final boolean succeded = deletePackageX(packageName, true, true, flags);
6122 if (observer != null) {
6123 try {
6124 observer.packageDeleted(succeded);
6125 } catch (RemoteException e) {
6126 Log.i(TAG, "Observer no longer exists.");
6127 } //end catch
6128 } //end if
6129 } //end run
6130 });
6131 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006133 /**
6134 * This method is an internal method that could be get invoked either
6135 * to delete an installed package or to clean up a failed installation.
6136 * After deleting an installed package, a broadcast is sent to notify any
6137 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006138 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006139 * installation wouldn't have sent the initial broadcast either
6140 * The key steps in deleting a package are
6141 * deleting the package information in internal structures like mPackages,
6142 * deleting the packages base directories through installd
6143 * updating mSettings to reflect current status
6144 * persisting settings for later use
6145 * sending a broadcast if necessary
6146 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006147 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6148 boolean deleteCodeAndResources, int flags) {
6149 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006150 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006151
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006152 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6153 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6154 try {
6155 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006156 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006157 return false;
6158 }
6159 } catch (RemoteException e) {
6160 }
6161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006162 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006163 res = deletePackageLI(packageName, deleteCodeAndResources,
6164 flags | REMOVE_CHATTY, info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006165 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006167 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006168 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006169 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006170
6171 // If the removed package was a system update, the old system packaged
6172 // was re-enabled; we need to broadcast this information
6173 if (systemUpdate) {
6174 Bundle extras = new Bundle(1);
6175 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6176 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6177
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006178 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6179 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006181 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006182 // Force a gc here.
6183 Runtime.getRuntime().gc();
6184 // Delete the resources here after sending the broadcast to let
6185 // other processes clean up before deleting resources.
6186 if (info.args != null) {
6187 synchronized (mInstallLock) {
6188 info.args.doPostDeleteLI(deleteCodeAndResources);
6189 }
6190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006191 return res;
6192 }
6193
6194 static class PackageRemovedInfo {
6195 String removedPackage;
6196 int uid = -1;
6197 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006198 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006199 // Clean up resources deleted packages.
6200 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006201
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006202 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203 Bundle extras = new Bundle(1);
6204 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6205 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6206 if (replacing) {
6207 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6208 }
6209 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006210 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006211 }
6212 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006213 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214 }
6215 }
6216 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006218 /*
6219 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6220 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006221 * 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 -08006222 * delete a partially installed application.
6223 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006224 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006225 int flags) {
6226 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006227 if (outInfo != null) {
6228 outInfo.removedPackage = packageName;
6229 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006230 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006231 // Retrieve object to delete permissions for shared user later on
6232 PackageSetting deletedPs;
6233 synchronized (mPackages) {
6234 deletedPs = mSettings.mPackages.get(packageName);
6235 }
6236 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006237 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006238 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006239 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006240 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006241 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006242 + packageName + ", retcode=" + retCode);
6243 // we don't consider this to be a failure of the core package deletion
6244 }
6245 } else {
6246 //for emulator
6247 PackageParser.Package pkg = mPackages.get(packageName);
6248 File dataDir = new File(pkg.applicationInfo.dataDir);
6249 dataDir.delete();
6250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 }
6252 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006253 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006254 schedulePackageCleaning(packageName);
6255
6256 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6257 if (outInfo != null) {
6258 outInfo.removedUid = mSettings.removePackageLP(packageName);
6259 }
6260 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006261 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006262 if (deletedPs.sharedUser != null) {
6263 // remove permissions associated with package
6264 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6265 }
6266 }
6267 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006268 // remove from preferred activities.
6269 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6270 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6271 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6272 removed.add(pa);
6273 }
6274 }
6275 for (PreferredActivity pa : removed) {
6276 mSettings.mPreferredActivities.removeFilter(pa);
6277 }
6278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006280 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006281 }
6282 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 /*
6285 * Tries to delete system package.
6286 */
6287 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006288 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006289 ApplicationInfo applicationInfo = p.applicationInfo;
6290 //applicable for non-partially installed applications only
6291 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006292 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006293 return false;
6294 }
6295 PackageSetting ps = null;
6296 // Confirm if the system package has been updated
6297 // An updated system app can be deleted. This will also have to restore
6298 // the system pkg from system partition
6299 synchronized (mPackages) {
6300 ps = mSettings.getDisabledSystemPkg(p.packageName);
6301 }
6302 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006303 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304 return false;
6305 } else {
6306 Log.i(TAG, "Deleting system pkg from data partition");
6307 }
6308 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006309 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006310 boolean deleteCodeAndResources = false;
6311 if (ps.versionCode < p.mVersionCode) {
6312 // Delete code and resources for downgrades
6313 deleteCodeAndResources = true;
6314 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6315 flags &= ~PackageManager.DONT_DELETE_DATA;
6316 }
6317 } else {
6318 // Preserve data by setting flag
6319 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6320 flags |= PackageManager.DONT_DELETE_DATA;
6321 }
6322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6324 if (!ret) {
6325 return false;
6326 }
6327 synchronized (mPackages) {
6328 // Reinstate the old system package
6329 mSettings.enableSystemPackageLP(p.packageName);
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07006330 // Remove any native libraries.
6331 removeNativeBinariesLI(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 }
6333 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006334 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006335 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006336 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006338 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006339 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006340 return false;
6341 }
6342 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006343 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 mSettings.writeLP();
6345 }
6346 return true;
6347 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006349 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6350 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6351 ApplicationInfo applicationInfo = p.applicationInfo;
6352 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006353 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006354 return false;
6355 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006356 if (outInfo != null) {
6357 outInfo.uid = applicationInfo.uid;
6358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006359
6360 // Delete package data from internal structures and also remove data if flag is set
6361 removePackageDataLI(p, outInfo, flags);
6362
6363 // Delete application code and resources
6364 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006365 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006366 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006367 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006368 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6369 PackageManager.INSTALL_FORWARD_LOCK : 0;
6370 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006371 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006372 }
6373 return true;
6374 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006376 /*
6377 * This method handles package deletion in general
6378 */
6379 private boolean deletePackageLI(String packageName,
6380 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6381 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006382 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006383 return false;
6384 }
6385 PackageParser.Package p;
6386 boolean dataOnly = false;
6387 synchronized (mPackages) {
6388 p = mPackages.get(packageName);
6389 if (p == null) {
6390 //this retrieves partially installed apps
6391 dataOnly = true;
6392 PackageSetting ps = mSettings.mPackages.get(packageName);
6393 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006394 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 return false;
6396 }
6397 p = ps.pkg;
6398 }
6399 }
6400 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006401 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402 return false;
6403 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006405 if (dataOnly) {
6406 // Delete application data first
6407 removePackageDataLI(p, outInfo, flags);
6408 return true;
6409 }
6410 // At this point the package should have ApplicationInfo associated with it
6411 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006412 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006413 return false;
6414 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006415 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6417 Log.i(TAG, "Removing system package:"+p.packageName);
6418 // When an updated system application is deleted we delete the existing resources as well and
6419 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006420 ret = deleteSystemPackageLI(p, flags, outInfo);
6421 } else {
6422 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006423 // Kill application pre-emptively especially for apps on sd.
6424 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006425 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006426 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006427 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006428 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006430 public void clearApplicationUserData(final String packageName,
6431 final IPackageDataObserver observer) {
6432 mContext.enforceCallingOrSelfPermission(
6433 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6434 // Queue up an async operation since the package deletion may take a little while.
6435 mHandler.post(new Runnable() {
6436 public void run() {
6437 mHandler.removeCallbacks(this);
6438 final boolean succeeded;
6439 synchronized (mInstallLock) {
6440 succeeded = clearApplicationUserDataLI(packageName);
6441 }
6442 if (succeeded) {
6443 // invoke DeviceStorageMonitor's update method to clear any notifications
6444 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6445 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6446 if (dsm != null) {
6447 dsm.updateMemory();
6448 }
6449 }
6450 if(observer != null) {
6451 try {
6452 observer.onRemoveCompleted(packageName, succeeded);
6453 } catch (RemoteException e) {
6454 Log.i(TAG, "Observer no longer exists.");
6455 }
6456 } //end if observer
6457 } //end run
6458 });
6459 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006461 private boolean clearApplicationUserDataLI(String packageName) {
6462 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006463 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006464 return false;
6465 }
6466 PackageParser.Package p;
6467 boolean dataOnly = false;
6468 synchronized (mPackages) {
6469 p = mPackages.get(packageName);
6470 if(p == null) {
6471 dataOnly = true;
6472 PackageSetting ps = mSettings.mPackages.get(packageName);
6473 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006474 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006475 return false;
6476 }
6477 p = ps.pkg;
6478 }
6479 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006480 boolean useEncryptedFSDir = false;
6481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006482 if(!dataOnly) {
6483 //need to check this only for fully installed applications
6484 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006485 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006486 return false;
6487 }
6488 final ApplicationInfo applicationInfo = p.applicationInfo;
6489 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006490 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006491 return false;
6492 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006493 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006494 }
6495 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006496 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006497 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006498 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006499 + packageName);
6500 return false;
6501 }
6502 }
6503 return true;
6504 }
6505
6506 public void deleteApplicationCacheFiles(final String packageName,
6507 final IPackageDataObserver observer) {
6508 mContext.enforceCallingOrSelfPermission(
6509 android.Manifest.permission.DELETE_CACHE_FILES, null);
6510 // Queue up an async operation since the package deletion may take a little while.
6511 mHandler.post(new Runnable() {
6512 public void run() {
6513 mHandler.removeCallbacks(this);
6514 final boolean succeded;
6515 synchronized (mInstallLock) {
6516 succeded = deleteApplicationCacheFilesLI(packageName);
6517 }
6518 if(observer != null) {
6519 try {
6520 observer.onRemoveCompleted(packageName, succeded);
6521 } catch (RemoteException e) {
6522 Log.i(TAG, "Observer no longer exists.");
6523 }
6524 } //end if observer
6525 } //end run
6526 });
6527 }
6528
6529 private boolean deleteApplicationCacheFilesLI(String packageName) {
6530 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006531 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006532 return false;
6533 }
6534 PackageParser.Package p;
6535 synchronized (mPackages) {
6536 p = mPackages.get(packageName);
6537 }
6538 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006539 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006540 return false;
6541 }
6542 final ApplicationInfo applicationInfo = p.applicationInfo;
6543 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006544 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006545 return false;
6546 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006547 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006548 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006549 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006550 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006551 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006552 + packageName);
6553 return false;
6554 }
6555 }
6556 return true;
6557 }
6558
6559 public void getPackageSizeInfo(final String packageName,
6560 final IPackageStatsObserver observer) {
6561 mContext.enforceCallingOrSelfPermission(
6562 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6563 // Queue up an async operation since the package deletion may take a little while.
6564 mHandler.post(new Runnable() {
6565 public void run() {
6566 mHandler.removeCallbacks(this);
6567 PackageStats lStats = new PackageStats(packageName);
6568 final boolean succeded;
6569 synchronized (mInstallLock) {
6570 succeded = getPackageSizeInfoLI(packageName, lStats);
6571 }
6572 if(observer != null) {
6573 try {
6574 observer.onGetStatsCompleted(lStats, succeded);
6575 } catch (RemoteException e) {
6576 Log.i(TAG, "Observer no longer exists.");
6577 }
6578 } //end if observer
6579 } //end run
6580 });
6581 }
6582
6583 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6584 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006585 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006586 return false;
6587 }
6588 PackageParser.Package p;
6589 boolean dataOnly = false;
6590 synchronized (mPackages) {
6591 p = mPackages.get(packageName);
6592 if(p == null) {
6593 dataOnly = true;
6594 PackageSetting ps = mSettings.mPackages.get(packageName);
6595 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006596 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006597 return false;
6598 }
6599 p = ps.pkg;
6600 }
6601 }
6602 String publicSrcDir = null;
6603 if(!dataOnly) {
6604 final ApplicationInfo applicationInfo = p.applicationInfo;
6605 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006606 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006607 return false;
6608 }
6609 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6610 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006611 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 if (mInstaller != null) {
6613 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006614 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006615 if (res < 0) {
6616 return false;
6617 } else {
6618 return true;
6619 }
6620 }
6621 return true;
6622 }
6623
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006625 public void addPackageToPreferred(String packageName) {
6626 mContext.enforceCallingOrSelfPermission(
6627 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006628 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006629 }
6630
6631 public void removePackageFromPreferred(String packageName) {
6632 mContext.enforceCallingOrSelfPermission(
6633 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006634 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006635 }
6636
6637 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006638 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006639 }
6640
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006641 int getUidTargetSdkVersionLockedLP(int uid) {
6642 Object obj = mSettings.getUserIdLP(uid);
6643 if (obj instanceof SharedUserSetting) {
6644 SharedUserSetting sus = (SharedUserSetting)obj;
6645 final int N = sus.packages.size();
6646 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6647 Iterator<PackageSetting> it = sus.packages.iterator();
6648 int i=0;
6649 while (it.hasNext()) {
6650 PackageSetting ps = it.next();
6651 if (ps.pkg != null) {
6652 int v = ps.pkg.applicationInfo.targetSdkVersion;
6653 if (v < vers) vers = v;
6654 }
6655 }
6656 return vers;
6657 } else if (obj instanceof PackageSetting) {
6658 PackageSetting ps = (PackageSetting)obj;
6659 if (ps.pkg != null) {
6660 return ps.pkg.applicationInfo.targetSdkVersion;
6661 }
6662 }
6663 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6664 }
6665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006666 public void addPreferredActivity(IntentFilter filter, int match,
6667 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006668 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006669 if (mContext.checkCallingOrSelfPermission(
6670 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6671 != PackageManager.PERMISSION_GRANTED) {
6672 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6673 < Build.VERSION_CODES.FROYO) {
6674 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6675 + Binder.getCallingUid());
6676 return;
6677 }
6678 mContext.enforceCallingOrSelfPermission(
6679 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6680 }
6681
6682 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006683 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6684 mSettings.mPreferredActivities.addFilter(
6685 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006686 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006687 }
6688 }
6689
Satish Sampath8dbe6122009-06-02 23:35:54 +01006690 public void replacePreferredActivity(IntentFilter filter, int match,
6691 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006692 if (filter.countActions() != 1) {
6693 throw new IllegalArgumentException(
6694 "replacePreferredActivity expects filter to have only 1 action.");
6695 }
6696 if (filter.countCategories() != 1) {
6697 throw new IllegalArgumentException(
6698 "replacePreferredActivity expects filter to have only 1 category.");
6699 }
6700 if (filter.countDataAuthorities() != 0
6701 || filter.countDataPaths() != 0
6702 || filter.countDataSchemes() != 0
6703 || filter.countDataTypes() != 0) {
6704 throw new IllegalArgumentException(
6705 "replacePreferredActivity expects filter to have no data authorities, " +
6706 "paths, schemes or types.");
6707 }
6708 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006709 if (mContext.checkCallingOrSelfPermission(
6710 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6711 != PackageManager.PERMISSION_GRANTED) {
6712 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6713 < Build.VERSION_CODES.FROYO) {
6714 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6715 + Binder.getCallingUid());
6716 return;
6717 }
6718 mContext.enforceCallingOrSelfPermission(
6719 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6720 }
6721
Satish Sampath8dbe6122009-06-02 23:35:54 +01006722 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6723 String action = filter.getAction(0);
6724 String category = filter.getCategory(0);
6725 while (it.hasNext()) {
6726 PreferredActivity pa = it.next();
6727 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6728 it.remove();
6729 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6730 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6731 }
6732 }
6733 addPreferredActivity(filter, match, set, activity);
6734 }
6735 }
6736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006737 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006738 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006739 int uid = Binder.getCallingUid();
6740 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006741 if (pkg == null || pkg.applicationInfo.uid != uid) {
6742 if (mContext.checkCallingOrSelfPermission(
6743 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6744 != PackageManager.PERMISSION_GRANTED) {
6745 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6746 < Build.VERSION_CODES.FROYO) {
6747 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6748 + Binder.getCallingUid());
6749 return;
6750 }
6751 mContext.enforceCallingOrSelfPermission(
6752 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6753 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006754 }
6755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006756 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006757 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006758 }
6759 }
6760 }
6761
6762 boolean clearPackagePreferredActivitiesLP(String packageName) {
6763 boolean changed = false;
6764 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6765 while (it.hasNext()) {
6766 PreferredActivity pa = it.next();
6767 if (pa.mActivity.getPackageName().equals(packageName)) {
6768 it.remove();
6769 changed = true;
6770 }
6771 }
6772 return changed;
6773 }
6774
6775 public int getPreferredActivities(List<IntentFilter> outFilters,
6776 List<ComponentName> outActivities, String packageName) {
6777
6778 int num = 0;
6779 synchronized (mPackages) {
6780 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6781 while (it.hasNext()) {
6782 PreferredActivity pa = it.next();
6783 if (packageName == null
6784 || pa.mActivity.getPackageName().equals(packageName)) {
6785 if (outFilters != null) {
6786 outFilters.add(new IntentFilter(pa));
6787 }
6788 if (outActivities != null) {
6789 outActivities.add(pa.mActivity);
6790 }
6791 }
6792 }
6793 }
6794
6795 return num;
6796 }
6797
6798 public void setApplicationEnabledSetting(String appPackageName,
6799 int newState, int flags) {
6800 setEnabledSetting(appPackageName, null, newState, flags);
6801 }
6802
6803 public void setComponentEnabledSetting(ComponentName componentName,
6804 int newState, int flags) {
6805 setEnabledSetting(componentName.getPackageName(),
6806 componentName.getClassName(), newState, flags);
6807 }
6808
6809 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006810 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006811 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6812 || newState == COMPONENT_ENABLED_STATE_ENABLED
6813 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6814 throw new IllegalArgumentException("Invalid new component state: "
6815 + newState);
6816 }
6817 PackageSetting pkgSetting;
6818 final int uid = Binder.getCallingUid();
6819 final int permission = mContext.checkCallingPermission(
6820 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6821 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006822 boolean sendNow = false;
6823 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006824 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006825 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006826 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006827 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006828 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006829 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006830 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006831 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006832 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006833 }
6834 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006835 "Unknown component: " + packageName
6836 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006837 }
6838 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6839 throw new SecurityException(
6840 "Permission Denial: attempt to change component state from pid="
6841 + Binder.getCallingPid()
6842 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6843 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006844 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006845 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006846 if (pkgSetting.enabled == newState) {
6847 // Nothing to do
6848 return;
6849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006850 pkgSetting.enabled = newState;
6851 } else {
6852 // We're dealing with a component level state change
6853 switch (newState) {
6854 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006855 if (!pkgSetting.enableComponentLP(className)) {
6856 return;
6857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006858 break;
6859 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006860 if (!pkgSetting.disableComponentLP(className)) {
6861 return;
6862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006863 break;
6864 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006865 if (!pkgSetting.restoreComponentLP(className)) {
6866 return;
6867 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006868 break;
6869 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006870 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006871 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006872 }
6873 }
6874 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006875 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006876 components = mPendingBroadcasts.get(packageName);
6877 boolean newPackage = components == null;
6878 if (newPackage) {
6879 components = new ArrayList<String>();
6880 }
6881 if (!components.contains(componentName)) {
6882 components.add(componentName);
6883 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006884 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6885 sendNow = true;
6886 // Purge entry from pending broadcast list if another one exists already
6887 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006888 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006889 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006890 if (newPackage) {
6891 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006892 }
6893 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6894 // Schedule a message
6895 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6896 }
6897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006898 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006900 long callingId = Binder.clearCallingIdentity();
6901 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006902 if (sendNow) {
6903 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006904 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006906 } finally {
6907 Binder.restoreCallingIdentity(callingId);
6908 }
6909 }
6910
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006911 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006912 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6913 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6914 + " components=" + componentNames);
6915 Bundle extras = new Bundle(4);
6916 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6917 String nameList[] = new String[componentNames.size()];
6918 componentNames.toArray(nameList);
6919 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006920 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6921 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006922 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006923 }
6924
Jacek Surazski65e13172009-04-28 15:26:38 +02006925 public String getInstallerPackageName(String packageName) {
6926 synchronized (mPackages) {
6927 PackageSetting pkg = mSettings.mPackages.get(packageName);
6928 if (pkg == null) {
6929 throw new IllegalArgumentException("Unknown package: " + packageName);
6930 }
6931 return pkg.installerPackageName;
6932 }
6933 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006935 public int getApplicationEnabledSetting(String appPackageName) {
6936 synchronized (mPackages) {
6937 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6938 if (pkg == null) {
6939 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6940 }
6941 return pkg.enabled;
6942 }
6943 }
6944
6945 public int getComponentEnabledSetting(ComponentName componentName) {
6946 synchronized (mPackages) {
6947 final String packageNameStr = componentName.getPackageName();
6948 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6949 if (pkg == null) {
6950 throw new IllegalArgumentException("Unknown component: " + componentName);
6951 }
6952 final String classNameStr = componentName.getClassName();
6953 return pkg.currentEnabledStateLP(classNameStr);
6954 }
6955 }
6956
6957 public void enterSafeMode() {
6958 if (!mSystemReady) {
6959 mSafeMode = true;
6960 }
6961 }
6962
6963 public void systemReady() {
6964 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006965
6966 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006967 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006968 mContext.getContentResolver(),
6969 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006970 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006971 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006972 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006974 }
6975
6976 public boolean isSafeMode() {
6977 return mSafeMode;
6978 }
6979
6980 public boolean hasSystemUidErrors() {
6981 return mHasSystemUidErrors;
6982 }
6983
6984 static String arrayToString(int[] array) {
6985 StringBuffer buf = new StringBuffer(128);
6986 buf.append('[');
6987 if (array != null) {
6988 for (int i=0; i<array.length; i++) {
6989 if (i > 0) buf.append(", ");
6990 buf.append(array[i]);
6991 }
6992 }
6993 buf.append(']');
6994 return buf.toString();
6995 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006997 @Override
6998 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6999 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
7000 != PackageManager.PERMISSION_GRANTED) {
7001 pw.println("Permission Denial: can't dump ActivityManager from from pid="
7002 + Binder.getCallingPid()
7003 + ", uid=" + Binder.getCallingUid()
7004 + " without permission "
7005 + android.Manifest.permission.DUMP);
7006 return;
7007 }
7008
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007009 String packageName = null;
7010
7011 int opti = 0;
7012 while (opti < args.length) {
7013 String opt = args[opti];
7014 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
7015 break;
7016 }
7017 opti++;
7018 if ("-a".equals(opt)) {
7019 // Right now we only know how to print all.
7020 } else if ("-h".equals(opt)) {
7021 pw.println("Package manager dump options:");
7022 pw.println(" [-h] [cmd] ...");
7023 pw.println(" cmd may be one of:");
7024 pw.println(" [package.name]: info about given package");
7025 return;
7026 } else {
7027 pw.println("Unknown argument: " + opt + "; use -h for help");
7028 }
7029 }
7030
7031 // Is the caller requesting to dump a particular piece of data?
7032 if (opti < args.length) {
7033 String cmd = args[opti];
7034 opti++;
7035 // Is this a package name?
7036 if ("android".equals(cmd) || cmd.contains(".")) {
7037 packageName = cmd;
7038 }
7039 }
7040
7041 boolean printedTitle = false;
7042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007043 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007044 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
7045 printedTitle = true;
7046 }
7047 if (mReceivers.dump(pw, printedTitle
7048 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
7049 " ", packageName)) {
7050 printedTitle = true;
7051 }
7052 if (mServices.dump(pw, printedTitle
7053 ? "\nService Resolver Table:" : "Service Resolver Table:",
7054 " ", packageName)) {
7055 printedTitle = true;
7056 }
7057 if (mSettings.mPreferredActivities.dump(pw, printedTitle
7058 ? "\nPreferred Activities:" : "Preferred Activities:",
7059 " ", packageName)) {
7060 printedTitle = true;
7061 }
7062 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007063 {
7064 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007065 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7066 continue;
7067 }
7068 if (!printedSomething) {
7069 if (printedTitle) pw.println(" ");
7070 pw.println("Permissions:");
7071 printedSomething = true;
7072 printedTitle = true;
7073 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007074 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7075 pw.print(Integer.toHexString(System.identityHashCode(p)));
7076 pw.println("):");
7077 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7078 pw.print(" uid="); pw.print(p.uid);
7079 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007080 pw.print(" type="); pw.print(p.type);
7081 pw.print(" prot="); pw.println(p.protectionLevel);
7082 if (p.packageSetting != null) {
7083 pw.print(" packageSetting="); pw.println(p.packageSetting);
7084 }
7085 if (p.perm != null) {
7086 pw.print(" perm="); pw.println(p.perm);
7087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007088 }
7089 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007090 printedSomething = false;
7091 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007092 {
7093 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007094 if (packageName != null && !packageName.equals(ps.realName)
7095 && !packageName.equals(ps.name)) {
7096 continue;
7097 }
7098 if (!printedSomething) {
7099 if (printedTitle) pw.println(" ");
7100 pw.println("Packages:");
7101 printedSomething = true;
7102 printedTitle = true;
7103 }
7104 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007105 pw.print(" Package [");
7106 pw.print(ps.realName != null ? ps.realName : ps.name);
7107 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007108 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7109 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007110 if (ps.realName != null) {
7111 pw.print(" compat name="); pw.println(ps.name);
7112 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007113 pw.print(" userId="); pw.print(ps.userId);
7114 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7115 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7116 pw.print(" pkg="); pw.println(ps.pkg);
7117 pw.print(" codePath="); pw.println(ps.codePathString);
7118 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007119 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007120 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007121 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007122 pw.print(" supportsScreens=[");
7123 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007124 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007125 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7126 if (!first) pw.print(", ");
7127 first = false;
7128 pw.print("small");
7129 }
7130 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007131 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007132 if (!first) pw.print(", ");
7133 first = false;
7134 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007135 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007136 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007137 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007138 if (!first) pw.print(", ");
7139 first = false;
7140 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007141 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007142 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007143 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007144 if (!first) pw.print(", ");
7145 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007146 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007147 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007148 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007149 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007150 if (!first) pw.print(", ");
7151 first = false;
7152 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007153 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007154 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007155 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7156 if (!first) pw.print(", ");
7157 first = false;
7158 pw.print("anyDensity");
7159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007160 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007161 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007162 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7163 pw.print(" signatures="); pw.println(ps.signatures);
7164 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007165 pw.print(" haveGids="); pw.println(ps.haveGids);
7166 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007167 pw.print(" installStatus="); pw.print(ps.installStatus);
7168 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007169 if (ps.disabledComponents.size() > 0) {
7170 pw.println(" disabledComponents:");
7171 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007172 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007173 }
7174 }
7175 if (ps.enabledComponents.size() > 0) {
7176 pw.println(" enabledComponents:");
7177 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007178 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007179 }
7180 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007181 if (ps.grantedPermissions.size() > 0) {
7182 pw.println(" grantedPermissions:");
7183 for (String s : ps.grantedPermissions) {
7184 pw.print(" "); pw.println(s);
7185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007187 }
7188 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007189 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007190 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007191 for (HashMap.Entry<String, String> e
7192 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007193 if (packageName != null && !packageName.equals(e.getKey())
7194 && !packageName.equals(e.getValue())) {
7195 continue;
7196 }
7197 if (!printedSomething) {
7198 if (printedTitle) pw.println(" ");
7199 pw.println("Renamed packages:");
7200 printedSomething = true;
7201 printedTitle = true;
7202 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007203 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7204 pw.println(e.getValue());
7205 }
7206 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007207 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007208 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007209 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007210 if (packageName != null && !packageName.equals(ps.realName)
7211 && !packageName.equals(ps.name)) {
7212 continue;
7213 }
7214 if (!printedSomething) {
7215 if (printedTitle) pw.println(" ");
7216 pw.println("Hidden system packages:");
7217 printedSomething = true;
7218 printedTitle = true;
7219 }
7220 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007221 pw.print(ps.realName != null ? ps.realName : ps.name);
7222 pw.print("] (");
7223 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7224 pw.println("):");
7225 if (ps.realName != null) {
7226 pw.print(" compat name="); pw.println(ps.name);
7227 }
7228 pw.print(" userId="); pw.println(ps.userId);
7229 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7230 pw.print(" codePath="); pw.println(ps.codePathString);
7231 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7232 }
7233 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007234 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007235 {
7236 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007237 if (packageName != null && su != packageSharedUser) {
7238 continue;
7239 }
7240 if (!printedSomething) {
7241 if (printedTitle) pw.println(" ");
7242 pw.println("Shared users:");
7243 printedSomething = true;
7244 printedTitle = true;
7245 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007246 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7247 pw.print(Integer.toHexString(System.identityHashCode(su)));
7248 pw.println("):");
7249 pw.print(" userId="); pw.print(su.userId);
7250 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007251 pw.println(" grantedPermissions:");
7252 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007253 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007255 }
7256 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007257
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007258 if (packageName == null) {
7259 if (printedTitle) pw.println(" ");
7260 printedTitle = true;
7261 pw.println("Settings parse messages:");
7262 pw.println(mSettings.mReadMessages.toString());
7263
7264 pw.println(" ");
7265 pw.println("Package warning messages:");
7266 File fname = getSettingsProblemFile();
7267 FileInputStream in;
7268 try {
7269 in = new FileInputStream(fname);
7270 int avail = in.available();
7271 byte[] data = new byte[avail];
7272 in.read(data);
7273 pw.println(new String(data));
7274 } catch (FileNotFoundException e) {
7275 } catch (IOException e) {
7276 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007278 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007279
7280 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007281 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007282 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007283 if (packageName != null && !packageName.equals(p.info.packageName)) {
7284 continue;
7285 }
7286 if (!printedSomething) {
7287 if (printedTitle) pw.println(" ");
7288 pw.println("Registered ContentProviders:");
7289 printedSomething = true;
7290 printedTitle = true;
7291 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007292 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007293 pw.println(p.toString());
7294 }
7295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007296 }
7297
7298 static final class BasePermission {
7299 final static int TYPE_NORMAL = 0;
7300 final static int TYPE_BUILTIN = 1;
7301 final static int TYPE_DYNAMIC = 2;
7302
7303 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007304 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007305 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007306 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007307 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007308 PackageParser.Permission perm;
7309 PermissionInfo pendingInfo;
7310 int uid;
7311 int[] gids;
7312
7313 BasePermission(String _name, String _sourcePackage, int _type) {
7314 name = _name;
7315 sourcePackage = _sourcePackage;
7316 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007317 // Default to most conservative protection level.
7318 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7319 }
7320
7321 public String toString() {
7322 return "BasePermission{"
7323 + Integer.toHexString(System.identityHashCode(this))
7324 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007325 }
7326 }
7327
7328 static class PackageSignatures {
7329 private Signature[] mSignatures;
7330
7331 PackageSignatures(Signature[] sigs) {
7332 assignSignatures(sigs);
7333 }
7334
7335 PackageSignatures() {
7336 }
7337
7338 void writeXml(XmlSerializer serializer, String tagName,
7339 ArrayList<Signature> pastSignatures) throws IOException {
7340 if (mSignatures == null) {
7341 return;
7342 }
7343 serializer.startTag(null, tagName);
7344 serializer.attribute(null, "count",
7345 Integer.toString(mSignatures.length));
7346 for (int i=0; i<mSignatures.length; i++) {
7347 serializer.startTag(null, "cert");
7348 final Signature sig = mSignatures[i];
7349 final int sigHash = sig.hashCode();
7350 final int numPast = pastSignatures.size();
7351 int j;
7352 for (j=0; j<numPast; j++) {
7353 Signature pastSig = pastSignatures.get(j);
7354 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7355 serializer.attribute(null, "index", Integer.toString(j));
7356 break;
7357 }
7358 }
7359 if (j >= numPast) {
7360 pastSignatures.add(sig);
7361 serializer.attribute(null, "index", Integer.toString(numPast));
7362 serializer.attribute(null, "key", sig.toCharsString());
7363 }
7364 serializer.endTag(null, "cert");
7365 }
7366 serializer.endTag(null, tagName);
7367 }
7368
7369 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7370 throws IOException, XmlPullParserException {
7371 String countStr = parser.getAttributeValue(null, "count");
7372 if (countStr == null) {
7373 reportSettingsProblem(Log.WARN,
7374 "Error in package manager settings: <signatures> has"
7375 + " no count at " + parser.getPositionDescription());
7376 XmlUtils.skipCurrentTag(parser);
7377 }
7378 final int count = Integer.parseInt(countStr);
7379 mSignatures = new Signature[count];
7380 int pos = 0;
7381
7382 int outerDepth = parser.getDepth();
7383 int type;
7384 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7385 && (type != XmlPullParser.END_TAG
7386 || parser.getDepth() > outerDepth)) {
7387 if (type == XmlPullParser.END_TAG
7388 || type == XmlPullParser.TEXT) {
7389 continue;
7390 }
7391
7392 String tagName = parser.getName();
7393 if (tagName.equals("cert")) {
7394 if (pos < count) {
7395 String index = parser.getAttributeValue(null, "index");
7396 if (index != null) {
7397 try {
7398 int idx = Integer.parseInt(index);
7399 String key = parser.getAttributeValue(null, "key");
7400 if (key == null) {
7401 if (idx >= 0 && idx < pastSignatures.size()) {
7402 Signature sig = pastSignatures.get(idx);
7403 if (sig != null) {
7404 mSignatures[pos] = pastSignatures.get(idx);
7405 pos++;
7406 } else {
7407 reportSettingsProblem(Log.WARN,
7408 "Error in package manager settings: <cert> "
7409 + "index " + index + " is not defined at "
7410 + parser.getPositionDescription());
7411 }
7412 } else {
7413 reportSettingsProblem(Log.WARN,
7414 "Error in package manager settings: <cert> "
7415 + "index " + index + " is out of bounds at "
7416 + parser.getPositionDescription());
7417 }
7418 } else {
7419 while (pastSignatures.size() <= idx) {
7420 pastSignatures.add(null);
7421 }
7422 Signature sig = new Signature(key);
7423 pastSignatures.set(idx, sig);
7424 mSignatures[pos] = sig;
7425 pos++;
7426 }
7427 } catch (NumberFormatException e) {
7428 reportSettingsProblem(Log.WARN,
7429 "Error in package manager settings: <cert> "
7430 + "index " + index + " is not a number at "
7431 + parser.getPositionDescription());
7432 }
7433 } else {
7434 reportSettingsProblem(Log.WARN,
7435 "Error in package manager settings: <cert> has"
7436 + " no index at " + parser.getPositionDescription());
7437 }
7438 } else {
7439 reportSettingsProblem(Log.WARN,
7440 "Error in package manager settings: too "
7441 + "many <cert> tags, expected " + count
7442 + " at " + parser.getPositionDescription());
7443 }
7444 } else {
7445 reportSettingsProblem(Log.WARN,
7446 "Unknown element under <cert>: "
7447 + parser.getName());
7448 }
7449 XmlUtils.skipCurrentTag(parser);
7450 }
7451
7452 if (pos < count) {
7453 // Should never happen -- there is an error in the written
7454 // settings -- but if it does we don't want to generate
7455 // a bad array.
7456 Signature[] newSigs = new Signature[pos];
7457 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7458 mSignatures = newSigs;
7459 }
7460 }
7461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007462 private void assignSignatures(Signature[] sigs) {
7463 if (sigs == null) {
7464 mSignatures = null;
7465 return;
7466 }
7467 mSignatures = new Signature[sigs.length];
7468 for (int i=0; i<sigs.length; i++) {
7469 mSignatures[i] = sigs[i];
7470 }
7471 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007473 @Override
7474 public String toString() {
7475 StringBuffer buf = new StringBuffer(128);
7476 buf.append("PackageSignatures{");
7477 buf.append(Integer.toHexString(System.identityHashCode(this)));
7478 buf.append(" [");
7479 if (mSignatures != null) {
7480 for (int i=0; i<mSignatures.length; i++) {
7481 if (i > 0) buf.append(", ");
7482 buf.append(Integer.toHexString(
7483 System.identityHashCode(mSignatures[i])));
7484 }
7485 }
7486 buf.append("]}");
7487 return buf.toString();
7488 }
7489 }
7490
7491 static class PreferredActivity extends IntentFilter {
7492 final int mMatch;
7493 final String[] mSetPackages;
7494 final String[] mSetClasses;
7495 final String[] mSetComponents;
7496 final ComponentName mActivity;
7497 final String mShortActivity;
7498 String mParseError;
7499
7500 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7501 ComponentName activity) {
7502 super(filter);
7503 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7504 mActivity = activity;
7505 mShortActivity = activity.flattenToShortString();
7506 mParseError = null;
7507 if (set != null) {
7508 final int N = set.length;
7509 String[] myPackages = new String[N];
7510 String[] myClasses = new String[N];
7511 String[] myComponents = new String[N];
7512 for (int i=0; i<N; i++) {
7513 ComponentName cn = set[i];
7514 if (cn == null) {
7515 mSetPackages = null;
7516 mSetClasses = null;
7517 mSetComponents = null;
7518 return;
7519 }
7520 myPackages[i] = cn.getPackageName().intern();
7521 myClasses[i] = cn.getClassName().intern();
7522 myComponents[i] = cn.flattenToShortString().intern();
7523 }
7524 mSetPackages = myPackages;
7525 mSetClasses = myClasses;
7526 mSetComponents = myComponents;
7527 } else {
7528 mSetPackages = null;
7529 mSetClasses = null;
7530 mSetComponents = null;
7531 }
7532 }
7533
7534 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7535 IOException {
7536 mShortActivity = parser.getAttributeValue(null, "name");
7537 mActivity = ComponentName.unflattenFromString(mShortActivity);
7538 if (mActivity == null) {
7539 mParseError = "Bad activity name " + mShortActivity;
7540 }
7541 String matchStr = parser.getAttributeValue(null, "match");
7542 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7543 String setCountStr = parser.getAttributeValue(null, "set");
7544 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7545
7546 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7547 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7548 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7549
7550 int setPos = 0;
7551
7552 int outerDepth = parser.getDepth();
7553 int type;
7554 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7555 && (type != XmlPullParser.END_TAG
7556 || parser.getDepth() > outerDepth)) {
7557 if (type == XmlPullParser.END_TAG
7558 || type == XmlPullParser.TEXT) {
7559 continue;
7560 }
7561
7562 String tagName = parser.getName();
7563 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7564 // + parser.getDepth() + " tag=" + tagName);
7565 if (tagName.equals("set")) {
7566 String name = parser.getAttributeValue(null, "name");
7567 if (name == null) {
7568 if (mParseError == null) {
7569 mParseError = "No name in set tag in preferred activity "
7570 + mShortActivity;
7571 }
7572 } else if (setPos >= setCount) {
7573 if (mParseError == null) {
7574 mParseError = "Too many set tags in preferred activity "
7575 + mShortActivity;
7576 }
7577 } else {
7578 ComponentName cn = ComponentName.unflattenFromString(name);
7579 if (cn == null) {
7580 if (mParseError == null) {
7581 mParseError = "Bad set name " + name + " in preferred activity "
7582 + mShortActivity;
7583 }
7584 } else {
7585 myPackages[setPos] = cn.getPackageName();
7586 myClasses[setPos] = cn.getClassName();
7587 myComponents[setPos] = name;
7588 setPos++;
7589 }
7590 }
7591 XmlUtils.skipCurrentTag(parser);
7592 } else if (tagName.equals("filter")) {
7593 //Log.i(TAG, "Starting to parse filter...");
7594 readFromXml(parser);
7595 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7596 // + parser.getDepth() + " tag=" + parser.getName());
7597 } else {
7598 reportSettingsProblem(Log.WARN,
7599 "Unknown element under <preferred-activities>: "
7600 + parser.getName());
7601 XmlUtils.skipCurrentTag(parser);
7602 }
7603 }
7604
7605 if (setPos != setCount) {
7606 if (mParseError == null) {
7607 mParseError = "Not enough set tags (expected " + setCount
7608 + " but found " + setPos + ") in " + mShortActivity;
7609 }
7610 }
7611
7612 mSetPackages = myPackages;
7613 mSetClasses = myClasses;
7614 mSetComponents = myComponents;
7615 }
7616
7617 public void writeToXml(XmlSerializer serializer) throws IOException {
7618 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7619 serializer.attribute(null, "name", mShortActivity);
7620 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7621 serializer.attribute(null, "set", Integer.toString(NS));
7622 for (int s=0; s<NS; s++) {
7623 serializer.startTag(null, "set");
7624 serializer.attribute(null, "name", mSetComponents[s]);
7625 serializer.endTag(null, "set");
7626 }
7627 serializer.startTag(null, "filter");
7628 super.writeToXml(serializer);
7629 serializer.endTag(null, "filter");
7630 }
7631
7632 boolean sameSet(List<ResolveInfo> query, int priority) {
7633 if (mSetPackages == null) return false;
7634 final int NQ = query.size();
7635 final int NS = mSetPackages.length;
7636 int numMatch = 0;
7637 for (int i=0; i<NQ; i++) {
7638 ResolveInfo ri = query.get(i);
7639 if (ri.priority != priority) continue;
7640 ActivityInfo ai = ri.activityInfo;
7641 boolean good = false;
7642 for (int j=0; j<NS; j++) {
7643 if (mSetPackages[j].equals(ai.packageName)
7644 && mSetClasses[j].equals(ai.name)) {
7645 numMatch++;
7646 good = true;
7647 break;
7648 }
7649 }
7650 if (!good) return false;
7651 }
7652 return numMatch == NS;
7653 }
7654 }
7655
7656 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007657 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007659 HashSet<String> grantedPermissions = new HashSet<String>();
7660 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007662 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007663 setFlags(pkgFlags);
7664 }
7665
7666 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007667 this.pkgFlags = pkgFlags & (
7668 ApplicationInfo.FLAG_SYSTEM |
7669 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007670 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007671 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007672 }
7673 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007675 /**
7676 * Settings base class for pending and resolved classes.
7677 */
7678 static class PackageSettingBase extends GrantedPermissions {
7679 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007680 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007681 File codePath;
7682 String codePathString;
7683 File resourcePath;
7684 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007685 private long timeStamp;
7686 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007687 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007688
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007689 boolean uidError;
7690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007691 PackageSignatures signatures = new PackageSignatures();
7692
7693 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007694 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007696 /* Explicitly disabled components */
7697 HashSet<String> disabledComponents = new HashSet<String>(0);
7698 /* Explicitly enabled components */
7699 HashSet<String> enabledComponents = new HashSet<String>(0);
7700 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7701 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007702
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007703 PackageSettingBase origPackage;
7704
Jacek Surazski65e13172009-04-28 15:26:38 +02007705 /* package name of the app that installed this package */
7706 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007707
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007708 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007709 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007710 super(pkgFlags);
7711 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007712 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007713 init(codePath, resourcePath, pVersionCode);
7714 }
7715
7716 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007717 this.codePath = codePath;
7718 this.codePathString = codePath.toString();
7719 this.resourcePath = resourcePath;
7720 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007721 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007722 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007723
Jacek Surazski65e13172009-04-28 15:26:38 +02007724 public void setInstallerPackageName(String packageName) {
7725 installerPackageName = packageName;
7726 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007727
Jacek Surazski65e13172009-04-28 15:26:38 +02007728 String getInstallerPackageName() {
7729 return installerPackageName;
7730 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007732 public void setInstallStatus(int newStatus) {
7733 installStatus = newStatus;
7734 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007736 public int getInstallStatus() {
7737 return installStatus;
7738 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740 public void setTimeStamp(long newStamp) {
7741 if (newStamp != timeStamp) {
7742 timeStamp = newStamp;
7743 timeStampString = Long.toString(newStamp);
7744 }
7745 }
7746
7747 public void setTimeStamp(long newStamp, String newStampStr) {
7748 timeStamp = newStamp;
7749 timeStampString = newStampStr;
7750 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007752 public long getTimeStamp() {
7753 return timeStamp;
7754 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007756 public String getTimeStampStr() {
7757 return timeStampString;
7758 }
7759
7760 public void copyFrom(PackageSettingBase base) {
7761 grantedPermissions = base.grantedPermissions;
7762 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007764 timeStamp = base.timeStamp;
7765 timeStampString = base.timeStampString;
7766 signatures = base.signatures;
7767 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007768 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007769 disabledComponents = base.disabledComponents;
7770 enabledComponents = base.enabledComponents;
7771 enabled = base.enabled;
7772 installStatus = base.installStatus;
7773 }
7774
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007775 boolean enableComponentLP(String componentClassName) {
7776 boolean changed = disabledComponents.remove(componentClassName);
7777 changed |= enabledComponents.add(componentClassName);
7778 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007779 }
7780
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007781 boolean disableComponentLP(String componentClassName) {
7782 boolean changed = enabledComponents.remove(componentClassName);
7783 changed |= disabledComponents.add(componentClassName);
7784 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007785 }
7786
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007787 boolean restoreComponentLP(String componentClassName) {
7788 boolean changed = enabledComponents.remove(componentClassName);
7789 changed |= disabledComponents.remove(componentClassName);
7790 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007791 }
7792
7793 int currentEnabledStateLP(String componentName) {
7794 if (enabledComponents.contains(componentName)) {
7795 return COMPONENT_ENABLED_STATE_ENABLED;
7796 } else if (disabledComponents.contains(componentName)) {
7797 return COMPONENT_ENABLED_STATE_DISABLED;
7798 } else {
7799 return COMPONENT_ENABLED_STATE_DEFAULT;
7800 }
7801 }
7802 }
7803
7804 /**
7805 * Settings data for a particular package we know about.
7806 */
7807 static final class PackageSetting extends PackageSettingBase {
7808 int userId;
7809 PackageParser.Package pkg;
7810 SharedUserSetting sharedUser;
7811
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007812 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007813 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007814 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007815 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007817 @Override
7818 public String toString() {
7819 return "PackageSetting{"
7820 + Integer.toHexString(System.identityHashCode(this))
7821 + " " + name + "/" + userId + "}";
7822 }
7823 }
7824
7825 /**
7826 * Settings data for a particular shared user ID we know about.
7827 */
7828 static final class SharedUserSetting extends GrantedPermissions {
7829 final String name;
7830 int userId;
7831 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7832 final PackageSignatures signatures = new PackageSignatures();
7833
7834 SharedUserSetting(String _name, int _pkgFlags) {
7835 super(_pkgFlags);
7836 name = _name;
7837 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007839 @Override
7840 public String toString() {
7841 return "SharedUserSetting{"
7842 + Integer.toHexString(System.identityHashCode(this))
7843 + " " + name + "/" + userId + "}";
7844 }
7845 }
7846
7847 /**
7848 * Holds information about dynamic settings.
7849 */
7850 private static final class Settings {
7851 private final File mSettingsFilename;
7852 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007853 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007854 private final HashMap<String, PackageSetting> mPackages =
7855 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007856 // List of replaced system applications
7857 final HashMap<String, PackageSetting> mDisabledSysPackages =
7858 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007859
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007860 // These are the last platform API version we were using for
7861 // the apps installed on internal and external storage. It is
7862 // used to grant newer permissions one time during a system upgrade.
7863 int mInternalSdkPlatform;
7864 int mExternalSdkPlatform;
7865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007866 // The user's preferred activities associated with particular intent
7867 // filters.
7868 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7869 new IntentResolver<PreferredActivity, PreferredActivity>() {
7870 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007871 protected String packageForFilter(PreferredActivity filter) {
7872 return filter.mActivity.getPackageName();
7873 }
7874 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007875 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007876 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007877 out.print(prefix); out.print(
7878 Integer.toHexString(System.identityHashCode(filter)));
7879 out.print(' ');
7880 out.print(filter.mActivity.flattenToShortString());
7881 out.print(" match=0x");
7882 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007883 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007884 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007885 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007886 out.print(prefix); out.print(" ");
7887 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007888 }
7889 }
7890 }
7891 };
7892 private final HashMap<String, SharedUserSetting> mSharedUsers =
7893 new HashMap<String, SharedUserSetting>();
7894 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7895 private final SparseArray<Object> mOtherUserIds =
7896 new SparseArray<Object>();
7897
7898 // For reading/writing settings file.
7899 private final ArrayList<Signature> mPastSignatures =
7900 new ArrayList<Signature>();
7901
7902 // Mapping from permission names to info about them.
7903 final HashMap<String, BasePermission> mPermissions =
7904 new HashMap<String, BasePermission>();
7905
7906 // Mapping from permission tree names to info about them.
7907 final HashMap<String, BasePermission> mPermissionTrees =
7908 new HashMap<String, BasePermission>();
7909
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007910 // Packages that have been uninstalled and still need their external
7911 // storage data deleted.
7912 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7913
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007914 // Packages that have been renamed since they were first installed.
7915 // Keys are the new names of the packages, values are the original
7916 // names. The packages appear everwhere else under their original
7917 // names.
7918 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007920 private final StringBuilder mReadMessages = new StringBuilder();
7921
7922 private static final class PendingPackage extends PackageSettingBase {
7923 final int sharedId;
7924
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007925 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007926 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007927 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007928 this.sharedId = sharedId;
7929 }
7930 }
7931 private final ArrayList<PendingPackage> mPendingPackages
7932 = new ArrayList<PendingPackage>();
7933
7934 Settings() {
7935 File dataDir = Environment.getDataDirectory();
7936 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007937 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7938 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007939 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007940 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007941 FileUtils.setPermissions(systemDir.toString(),
7942 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7943 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7944 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007945 FileUtils.setPermissions(systemSecureDir.toString(),
7946 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7947 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7948 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007949 mSettingsFilename = new File(systemDir, "packages.xml");
7950 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007951 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007952 }
7953
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007954 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007955 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007956 int pkgFlags, boolean create, boolean add) {
7957 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007958 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007959 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007960 return p;
7961 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007962
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007963 PackageSetting peekPackageLP(String name) {
7964 return mPackages.get(name);
7965 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007966 PackageSetting p = mPackages.get(name);
7967 if (p != null && p.codePath.getPath().equals(codePath)) {
7968 return p;
7969 }
7970 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007971 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007972 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 void setInstallStatus(String pkgName, int status) {
7975 PackageSetting p = mPackages.get(pkgName);
7976 if(p != null) {
7977 if(p.getInstallStatus() != status) {
7978 p.setInstallStatus(status);
7979 }
7980 }
7981 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007982
Jacek Surazski65e13172009-04-28 15:26:38 +02007983 void setInstallerPackageName(String pkgName,
7984 String installerPkgName) {
7985 PackageSetting p = mPackages.get(pkgName);
7986 if(p != null) {
7987 p.setInstallerPackageName(installerPkgName);
7988 }
7989 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007990
Jacek Surazski65e13172009-04-28 15:26:38 +02007991 String getInstallerPackageName(String pkgName) {
7992 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007993 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007994 }
7995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007996 int getInstallStatus(String pkgName) {
7997 PackageSetting p = mPackages.get(pkgName);
7998 if(p != null) {
7999 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008001 return -1;
8002 }
8003
8004 SharedUserSetting getSharedUserLP(String name,
8005 int pkgFlags, boolean create) {
8006 SharedUserSetting s = mSharedUsers.get(name);
8007 if (s == null) {
8008 if (!create) {
8009 return null;
8010 }
8011 s = new SharedUserSetting(name, pkgFlags);
8012 if (MULTIPLE_APPLICATION_UIDS) {
8013 s.userId = newUserIdLP(s);
8014 } else {
8015 s.userId = FIRST_APPLICATION_UID;
8016 }
8017 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
8018 // < 0 means we couldn't assign a userid; fall out and return
8019 // s, which is currently null
8020 if (s.userId >= 0) {
8021 mSharedUsers.put(name, s);
8022 }
8023 }
8024
8025 return s;
8026 }
8027
8028 int disableSystemPackageLP(String name) {
8029 PackageSetting p = mPackages.get(name);
8030 if(p == null) {
8031 Log.w(TAG, "Package:"+name+" is not an installed package");
8032 return -1;
8033 }
8034 PackageSetting dp = mDisabledSysPackages.get(name);
8035 // always make sure the system package code and resource paths dont change
8036 if(dp == null) {
8037 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8038 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8039 }
8040 mDisabledSysPackages.put(name, p);
8041 }
8042 return removePackageLP(name);
8043 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008045 PackageSetting enableSystemPackageLP(String name) {
8046 PackageSetting p = mDisabledSysPackages.get(name);
8047 if(p == null) {
8048 Log.w(TAG, "Package:"+name+" is not disabled");
8049 return null;
8050 }
8051 // Reset flag in ApplicationInfo object
8052 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8053 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8054 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008055 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008056 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008057 mDisabledSysPackages.remove(name);
8058 return ret;
8059 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008060
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008061 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008062 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008063 PackageSetting p = mPackages.get(name);
8064 if (p != null) {
8065 if (p.userId == uid) {
8066 return p;
8067 }
8068 reportSettingsProblem(Log.ERROR,
8069 "Adding duplicate package, keeping first: " + name);
8070 return null;
8071 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008072 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008073 p.userId = uid;
8074 if (addUserIdLP(uid, p, name)) {
8075 mPackages.put(name, p);
8076 return p;
8077 }
8078 return null;
8079 }
8080
8081 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8082 SharedUserSetting s = mSharedUsers.get(name);
8083 if (s != null) {
8084 if (s.userId == uid) {
8085 return s;
8086 }
8087 reportSettingsProblem(Log.ERROR,
8088 "Adding duplicate shared user, keeping first: " + name);
8089 return null;
8090 }
8091 s = new SharedUserSetting(name, pkgFlags);
8092 s.userId = uid;
8093 if (addUserIdLP(uid, s, name)) {
8094 mSharedUsers.put(name, s);
8095 return s;
8096 }
8097 return null;
8098 }
8099
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008100 // Transfer ownership of permissions from one package to another.
8101 private void transferPermissions(String origPkg, String newPkg) {
8102 // Transfer ownership of permissions to the new package.
8103 for (int i=0; i<2; i++) {
8104 HashMap<String, BasePermission> permissions =
8105 i == 0 ? mPermissionTrees : mPermissions;
8106 for (BasePermission bp : permissions.values()) {
8107 if (origPkg.equals(bp.sourcePackage)) {
8108 if (DEBUG_UPGRADE) Log.v(TAG,
8109 "Moving permission " + bp.name
8110 + " from pkg " + bp.sourcePackage
8111 + " to " + newPkg);
8112 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008113 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008114 bp.perm = null;
8115 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008116 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008117 }
8118 bp.uid = 0;
8119 bp.gids = null;
8120 }
8121 }
8122 }
8123 }
8124
8125 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008126 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008127 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008128 PackageSetting p = mPackages.get(name);
8129 if (p != null) {
8130 if (!p.codePath.equals(codePath)) {
8131 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008132 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008133 // This is an updated system app with versions in both system
8134 // and data partition. Just let the most recent version
8135 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008136 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008137 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008138 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008139 // Just a change in the code path is not an issue, but
8140 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008141 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008142 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008143 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008144 }
8145 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008146 reportSettingsProblem(Log.WARN,
8147 "Package " + name + " shared user changed from "
8148 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8149 + " to "
8150 + (sharedUser != null ? sharedUser.name : "<nothing>")
8151 + "; replacing with new");
8152 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008153 } else {
8154 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8155 // If what we are scanning is a system package, then
8156 // make it so, regardless of whether it was previously
8157 // installed only in the data partition.
8158 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008160 }
8161 }
8162 if (p == null) {
8163 // Create a new PackageSettings entry. this can end up here because
8164 // of code path mismatch or user id mismatch of an updated system partition
8165 if (!create) {
8166 return null;
8167 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008168 if (origPackage != null) {
8169 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008170 p = new PackageSetting(origPackage.name, name, codePath,
8171 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008172 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8173 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008174 // Note that we will retain the new package's signature so
8175 // that we can keep its data.
8176 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008177 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008178 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008179 p.sharedUser = origPackage.sharedUser;
8180 p.userId = origPackage.userId;
8181 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008182 mRenamedPackages.put(name, origPackage.name);
8183 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008184 // Update new package state.
8185 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008186 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008187 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008188 p.setTimeStamp(codePath.lastModified());
8189 p.sharedUser = sharedUser;
8190 if (sharedUser != null) {
8191 p.userId = sharedUser.userId;
8192 } else if (MULTIPLE_APPLICATION_UIDS) {
8193 // Clone the setting here for disabled system packages
8194 PackageSetting dis = mDisabledSysPackages.get(name);
8195 if (dis != null) {
8196 // For disabled packages a new setting is created
8197 // from the existing user id. This still has to be
8198 // added to list of user id's
8199 // Copy signatures from previous setting
8200 if (dis.signatures.mSignatures != null) {
8201 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8202 }
8203 p.userId = dis.userId;
8204 // Clone permissions
8205 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008206 // Clone component info
8207 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8208 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8209 // Add new setting to list of user ids
8210 addUserIdLP(p.userId, p, name);
8211 } else {
8212 // Assign new user id
8213 p.userId = newUserIdLP(p);
8214 }
8215 } else {
8216 p.userId = FIRST_APPLICATION_UID;
8217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008218 }
8219 if (p.userId < 0) {
8220 reportSettingsProblem(Log.WARN,
8221 "Package " + name + " could not be assigned a valid uid");
8222 return null;
8223 }
8224 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008225 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008226 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008227 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008228 }
8229 }
8230 return p;
8231 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008232
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008233 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008234 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008235 String codePath = pkg.applicationInfo.sourceDir;
8236 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008237 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008238 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008239 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008240 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008241 p.codePath = new File(codePath);
8242 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008243 }
8244 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008245 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008246 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008247 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008248 p.resourcePath = new File(resourcePath);
8249 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008250 }
8251 // Update version code if needed
8252 if (pkg.mVersionCode != p.versionCode) {
8253 p.versionCode = pkg.mVersionCode;
8254 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008255 // Update signatures if needed.
8256 if (p.signatures.mSignatures == null) {
8257 p.signatures.assignSignatures(pkg.mSignatures);
8258 }
8259 // If this app defines a shared user id initialize
8260 // the shared user signatures as well.
8261 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8262 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8263 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008264 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8265 }
8266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008267 // Utility method that adds a PackageSetting to mPackages and
8268 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008269 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008270 SharedUserSetting sharedUser) {
8271 mPackages.put(name, p);
8272 if (sharedUser != null) {
8273 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8274 reportSettingsProblem(Log.ERROR,
8275 "Package " + p.name + " was user "
8276 + p.sharedUser + " but is now " + sharedUser
8277 + "; I am not changing its files so it will probably fail!");
8278 p.sharedUser.packages.remove(p);
8279 } else if (p.userId != sharedUser.userId) {
8280 reportSettingsProblem(Log.ERROR,
8281 "Package " + p.name + " was user id " + p.userId
8282 + " but is now user " + sharedUser
8283 + " with id " + sharedUser.userId
8284 + "; I am not changing its files so it will probably fail!");
8285 }
8286
8287 sharedUser.packages.add(p);
8288 p.sharedUser = sharedUser;
8289 p.userId = sharedUser.userId;
8290 }
8291 }
8292
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008293 /*
8294 * Update the shared user setting when a package using
8295 * specifying the shared user id is removed. The gids
8296 * associated with each permission of the deleted package
8297 * are removed from the shared user's gid list only if its
8298 * not in use by other permissions of packages in the
8299 * shared user setting.
8300 */
8301 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008302 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008303 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008304 return;
8305 }
8306 // No sharedUserId
8307 if (deletedPs.sharedUser == null) {
8308 return;
8309 }
8310 SharedUserSetting sus = deletedPs.sharedUser;
8311 // Update permissions
8312 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8313 boolean used = false;
8314 if (!sus.grantedPermissions.contains (eachPerm)) {
8315 continue;
8316 }
8317 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008318 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008319 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008320 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008321 used = true;
8322 break;
8323 }
8324 }
8325 if (!used) {
8326 // can safely delete this permission from list
8327 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008328 }
8329 }
8330 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008331 int newGids[] = globalGids;
8332 for (String eachPerm : sus.grantedPermissions) {
8333 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008334 if (bp != null) {
8335 newGids = appendInts(newGids, bp.gids);
8336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008337 }
8338 sus.gids = newGids;
8339 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008341 private int removePackageLP(String name) {
8342 PackageSetting p = mPackages.get(name);
8343 if (p != null) {
8344 mPackages.remove(name);
8345 if (p.sharedUser != null) {
8346 p.sharedUser.packages.remove(p);
8347 if (p.sharedUser.packages.size() == 0) {
8348 mSharedUsers.remove(p.sharedUser.name);
8349 removeUserIdLP(p.sharedUser.userId);
8350 return p.sharedUser.userId;
8351 }
8352 } else {
8353 removeUserIdLP(p.userId);
8354 return p.userId;
8355 }
8356 }
8357 return -1;
8358 }
8359
8360 private boolean addUserIdLP(int uid, Object obj, Object name) {
8361 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8362 return false;
8363 }
8364
8365 if (uid >= FIRST_APPLICATION_UID) {
8366 int N = mUserIds.size();
8367 final int index = uid - FIRST_APPLICATION_UID;
8368 while (index >= N) {
8369 mUserIds.add(null);
8370 N++;
8371 }
8372 if (mUserIds.get(index) != null) {
8373 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008374 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008375 + " name=" + name);
8376 return false;
8377 }
8378 mUserIds.set(index, obj);
8379 } else {
8380 if (mOtherUserIds.get(uid) != null) {
8381 reportSettingsProblem(Log.ERROR,
8382 "Adding duplicate shared id: " + uid
8383 + " name=" + name);
8384 return false;
8385 }
8386 mOtherUserIds.put(uid, obj);
8387 }
8388 return true;
8389 }
8390
8391 public Object getUserIdLP(int uid) {
8392 if (uid >= FIRST_APPLICATION_UID) {
8393 int N = mUserIds.size();
8394 final int index = uid - FIRST_APPLICATION_UID;
8395 return index < N ? mUserIds.get(index) : null;
8396 } else {
8397 return mOtherUserIds.get(uid);
8398 }
8399 }
8400
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008401 private Set<String> findPackagesWithFlag(int flag) {
8402 Set<String> ret = new HashSet<String>();
8403 for (PackageSetting ps : mPackages.values()) {
8404 // Has to match atleast all the flag bits set on flag
8405 if ((ps.pkgFlags & flag) == flag) {
8406 ret.add(ps.name);
8407 }
8408 }
8409 return ret;
8410 }
8411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008412 private void removeUserIdLP(int uid) {
8413 if (uid >= FIRST_APPLICATION_UID) {
8414 int N = mUserIds.size();
8415 final int index = uid - FIRST_APPLICATION_UID;
8416 if (index < N) mUserIds.set(index, null);
8417 } else {
8418 mOtherUserIds.remove(uid);
8419 }
8420 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008422 void writeLP() {
8423 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8424
8425 // Keep the old settings around until we know the new ones have
8426 // been successfully written.
8427 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008428 // Presence of backup settings file indicates that we failed
8429 // to persist settings earlier. So preserve the older
8430 // backup for future reference since the current settings
8431 // might have been corrupted.
8432 if (!mBackupSettingsFilename.exists()) {
8433 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008434 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008435 return;
8436 }
8437 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008438 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008439 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008441 }
8442
8443 mPastSignatures.clear();
8444
8445 try {
8446 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8447
8448 //XmlSerializer serializer = XmlUtils.serializerInstance();
8449 XmlSerializer serializer = new FastXmlSerializer();
8450 serializer.setOutput(str, "utf-8");
8451 serializer.startDocument(null, true);
8452 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8453
8454 serializer.startTag(null, "packages");
8455
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008456 serializer.startTag(null, "last-platform-version");
8457 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8458 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8459 serializer.endTag(null, "last-platform-version");
8460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008461 serializer.startTag(null, "permission-trees");
8462 for (BasePermission bp : mPermissionTrees.values()) {
8463 writePermission(serializer, bp);
8464 }
8465 serializer.endTag(null, "permission-trees");
8466
8467 serializer.startTag(null, "permissions");
8468 for (BasePermission bp : mPermissions.values()) {
8469 writePermission(serializer, bp);
8470 }
8471 serializer.endTag(null, "permissions");
8472
8473 for (PackageSetting pkg : mPackages.values()) {
8474 writePackage(serializer, pkg);
8475 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008477 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8478 writeDisabledSysPackage(serializer, pkg);
8479 }
8480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008481 serializer.startTag(null, "preferred-activities");
8482 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8483 serializer.startTag(null, "item");
8484 pa.writeToXml(serializer);
8485 serializer.endTag(null, "item");
8486 }
8487 serializer.endTag(null, "preferred-activities");
8488
8489 for (SharedUserSetting usr : mSharedUsers.values()) {
8490 serializer.startTag(null, "shared-user");
8491 serializer.attribute(null, "name", usr.name);
8492 serializer.attribute(null, "userId",
8493 Integer.toString(usr.userId));
8494 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8495 serializer.startTag(null, "perms");
8496 for (String name : usr.grantedPermissions) {
8497 serializer.startTag(null, "item");
8498 serializer.attribute(null, "name", name);
8499 serializer.endTag(null, "item");
8500 }
8501 serializer.endTag(null, "perms");
8502 serializer.endTag(null, "shared-user");
8503 }
8504
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008505 if (mPackagesToBeCleaned.size() > 0) {
8506 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8507 serializer.startTag(null, "cleaning-package");
8508 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8509 serializer.endTag(null, "cleaning-package");
8510 }
8511 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008512
8513 if (mRenamedPackages.size() > 0) {
8514 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8515 serializer.startTag(null, "renamed-package");
8516 serializer.attribute(null, "new", e.getKey());
8517 serializer.attribute(null, "old", e.getValue());
8518 serializer.endTag(null, "renamed-package");
8519 }
8520 }
8521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008522 serializer.endTag(null, "packages");
8523
8524 serializer.endDocument();
8525
8526 str.flush();
8527 str.close();
8528
8529 // New settings successfully written, old ones are no longer
8530 // needed.
8531 mBackupSettingsFilename.delete();
8532 FileUtils.setPermissions(mSettingsFilename.toString(),
8533 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8534 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8535 |FileUtils.S_IROTH,
8536 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008537
8538 // Write package list file now, use a JournaledFile.
8539 //
8540 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8541 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8542
8543 str = new FileOutputStream(journal.chooseForWrite());
8544 try {
8545 StringBuilder sb = new StringBuilder();
8546 for (PackageSetting pkg : mPackages.values()) {
8547 ApplicationInfo ai = pkg.pkg.applicationInfo;
8548 String dataPath = ai.dataDir;
8549 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8550
8551 // Avoid any application that has a space in its path
8552 // or that is handled by the system.
8553 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8554 continue;
8555
8556 // we store on each line the following information for now:
8557 //
8558 // pkgName - package name
8559 // userId - application-specific user id
8560 // debugFlag - 0 or 1 if the package is debuggable.
8561 // dataPath - path to package's data path
8562 //
8563 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8564 //
8565 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8566 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8567 // system/core/run-as/run-as.c
8568 //
8569 sb.setLength(0);
8570 sb.append(ai.packageName);
8571 sb.append(" ");
8572 sb.append((int)ai.uid);
8573 sb.append(isDebug ? " 1 " : " 0 ");
8574 sb.append(dataPath);
8575 sb.append("\n");
8576 str.write(sb.toString().getBytes());
8577 }
8578 str.flush();
8579 str.close();
8580 journal.commit();
8581 }
8582 catch (Exception e) {
8583 journal.rollback();
8584 }
8585
8586 FileUtils.setPermissions(mPackageListFilename.toString(),
8587 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8588 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8589 |FileUtils.S_IROTH,
8590 -1, -1);
8591
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008592 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008593
8594 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008595 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 -08008596 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008597 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 -08008598 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008599 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008600 if (mSettingsFilename.exists()) {
8601 if (!mSettingsFilename.delete()) {
8602 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8603 }
8604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008605 //Debug.stopMethodTracing();
8606 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008607
8608 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008609 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008610 serializer.startTag(null, "updated-package");
8611 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008612 if (pkg.realName != null) {
8613 serializer.attribute(null, "realName", pkg.realName);
8614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008615 serializer.attribute(null, "codePath", pkg.codePathString);
8616 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008617 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008618 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8619 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8620 }
8621 if (pkg.sharedUser == null) {
8622 serializer.attribute(null, "userId",
8623 Integer.toString(pkg.userId));
8624 } else {
8625 serializer.attribute(null, "sharedUserId",
8626 Integer.toString(pkg.userId));
8627 }
8628 serializer.startTag(null, "perms");
8629 if (pkg.sharedUser == null) {
8630 // If this is a shared user, the permissions will
8631 // be written there. We still need to write an
8632 // empty permissions list so permissionsFixed will
8633 // be set.
8634 for (final String name : pkg.grantedPermissions) {
8635 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008636 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008637 // We only need to write signature or system permissions but this wont
8638 // match the semantics of grantedPermissions. So write all permissions.
8639 serializer.startTag(null, "item");
8640 serializer.attribute(null, "name", name);
8641 serializer.endTag(null, "item");
8642 }
8643 }
8644 }
8645 serializer.endTag(null, "perms");
8646 serializer.endTag(null, "updated-package");
8647 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008648
8649 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008650 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008651 serializer.startTag(null, "package");
8652 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008653 if (pkg.realName != null) {
8654 serializer.attribute(null, "realName", pkg.realName);
8655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008656 serializer.attribute(null, "codePath", pkg.codePathString);
8657 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8658 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8659 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008660 serializer.attribute(null, "flags",
8661 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008662 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008663 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008664 if (pkg.sharedUser == null) {
8665 serializer.attribute(null, "userId",
8666 Integer.toString(pkg.userId));
8667 } else {
8668 serializer.attribute(null, "sharedUserId",
8669 Integer.toString(pkg.userId));
8670 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008671 if (pkg.uidError) {
8672 serializer.attribute(null, "uidError", "true");
8673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008674 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8675 serializer.attribute(null, "enabled",
8676 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8677 ? "true" : "false");
8678 }
8679 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8680 serializer.attribute(null, "installStatus", "false");
8681 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008682 if (pkg.installerPackageName != null) {
8683 serializer.attribute(null, "installer", pkg.installerPackageName);
8684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008685 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8686 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8687 serializer.startTag(null, "perms");
8688 if (pkg.sharedUser == null) {
8689 // If this is a shared user, the permissions will
8690 // be written there. We still need to write an
8691 // empty permissions list so permissionsFixed will
8692 // be set.
8693 for (final String name : pkg.grantedPermissions) {
8694 serializer.startTag(null, "item");
8695 serializer.attribute(null, "name", name);
8696 serializer.endTag(null, "item");
8697 }
8698 }
8699 serializer.endTag(null, "perms");
8700 }
8701 if (pkg.disabledComponents.size() > 0) {
8702 serializer.startTag(null, "disabled-components");
8703 for (final String name : pkg.disabledComponents) {
8704 serializer.startTag(null, "item");
8705 serializer.attribute(null, "name", name);
8706 serializer.endTag(null, "item");
8707 }
8708 serializer.endTag(null, "disabled-components");
8709 }
8710 if (pkg.enabledComponents.size() > 0) {
8711 serializer.startTag(null, "enabled-components");
8712 for (final String name : pkg.enabledComponents) {
8713 serializer.startTag(null, "item");
8714 serializer.attribute(null, "name", name);
8715 serializer.endTag(null, "item");
8716 }
8717 serializer.endTag(null, "enabled-components");
8718 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008720 serializer.endTag(null, "package");
8721 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008723 void writePermission(XmlSerializer serializer, BasePermission bp)
8724 throws XmlPullParserException, java.io.IOException {
8725 if (bp.type != BasePermission.TYPE_BUILTIN
8726 && bp.sourcePackage != null) {
8727 serializer.startTag(null, "item");
8728 serializer.attribute(null, "name", bp.name);
8729 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008730 if (bp.protectionLevel !=
8731 PermissionInfo.PROTECTION_NORMAL) {
8732 serializer.attribute(null, "protection",
8733 Integer.toString(bp.protectionLevel));
8734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008735 if (DEBUG_SETTINGS) Log.v(TAG,
8736 "Writing perm: name=" + bp.name + " type=" + bp.type);
8737 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8738 PermissionInfo pi = bp.perm != null ? bp.perm.info
8739 : bp.pendingInfo;
8740 if (pi != null) {
8741 serializer.attribute(null, "type", "dynamic");
8742 if (pi.icon != 0) {
8743 serializer.attribute(null, "icon",
8744 Integer.toString(pi.icon));
8745 }
8746 if (pi.nonLocalizedLabel != null) {
8747 serializer.attribute(null, "label",
8748 pi.nonLocalizedLabel.toString());
8749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008750 }
8751 }
8752 serializer.endTag(null, "item");
8753 }
8754 }
8755
8756 String getReadMessagesLP() {
8757 return mReadMessages.toString();
8758 }
8759
Oscar Montemayora8529f62009-11-18 10:14:20 -08008760 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008761 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8762 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008763 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008764 while(its.hasNext()) {
8765 String key = its.next();
8766 PackageSetting ps = mPackages.get(key);
8767 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008768 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008769 }
8770 }
8771 return ret;
8772 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008774 boolean readLP() {
8775 FileInputStream str = null;
8776 if (mBackupSettingsFilename.exists()) {
8777 try {
8778 str = new FileInputStream(mBackupSettingsFilename);
8779 mReadMessages.append("Reading from backup settings file\n");
8780 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008781 if (mSettingsFilename.exists()) {
8782 // If both the backup and settings file exist, we
8783 // ignore the settings since it might have been
8784 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008785 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008786 mSettingsFilename.delete();
8787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008788 } catch (java.io.IOException e) {
8789 // We'll try for the normal settings file.
8790 }
8791 }
8792
8793 mPastSignatures.clear();
8794
8795 try {
8796 if (str == null) {
8797 if (!mSettingsFilename.exists()) {
8798 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008799 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008800 return false;
8801 }
8802 str = new FileInputStream(mSettingsFilename);
8803 }
8804 XmlPullParser parser = Xml.newPullParser();
8805 parser.setInput(str, null);
8806
8807 int type;
8808 while ((type=parser.next()) != XmlPullParser.START_TAG
8809 && type != XmlPullParser.END_DOCUMENT) {
8810 ;
8811 }
8812
8813 if (type != XmlPullParser.START_TAG) {
8814 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008815 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008816 return false;
8817 }
8818
8819 int outerDepth = parser.getDepth();
8820 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8821 && (type != XmlPullParser.END_TAG
8822 || parser.getDepth() > outerDepth)) {
8823 if (type == XmlPullParser.END_TAG
8824 || type == XmlPullParser.TEXT) {
8825 continue;
8826 }
8827
8828 String tagName = parser.getName();
8829 if (tagName.equals("package")) {
8830 readPackageLP(parser);
8831 } else if (tagName.equals("permissions")) {
8832 readPermissionsLP(mPermissions, parser);
8833 } else if (tagName.equals("permission-trees")) {
8834 readPermissionsLP(mPermissionTrees, parser);
8835 } else if (tagName.equals("shared-user")) {
8836 readSharedUserLP(parser);
8837 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008838 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008839 } else if (tagName.equals("preferred-activities")) {
8840 readPreferredActivitiesLP(parser);
8841 } else if(tagName.equals("updated-package")) {
8842 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008843 } else if (tagName.equals("cleaning-package")) {
8844 String name = parser.getAttributeValue(null, "name");
8845 if (name != null) {
8846 mPackagesToBeCleaned.add(name);
8847 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008848 } else if (tagName.equals("renamed-package")) {
8849 String nname = parser.getAttributeValue(null, "new");
8850 String oname = parser.getAttributeValue(null, "old");
8851 if (nname != null && oname != null) {
8852 mRenamedPackages.put(nname, oname);
8853 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008854 } else if (tagName.equals("last-platform-version")) {
8855 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8856 try {
8857 String internal = parser.getAttributeValue(null, "internal");
8858 if (internal != null) {
8859 mInternalSdkPlatform = Integer.parseInt(internal);
8860 }
8861 String external = parser.getAttributeValue(null, "external");
8862 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008863 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008864 }
8865 } catch (NumberFormatException e) {
8866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008867 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008868 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008869 + parser.getName());
8870 XmlUtils.skipCurrentTag(parser);
8871 }
8872 }
8873
8874 str.close();
8875
8876 } catch(XmlPullParserException e) {
8877 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008878 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008879
8880 } catch(java.io.IOException e) {
8881 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008882 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008883
8884 }
8885
8886 int N = mPendingPackages.size();
8887 for (int i=0; i<N; i++) {
8888 final PendingPackage pp = mPendingPackages.get(i);
8889 Object idObj = getUserIdLP(pp.sharedId);
8890 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008891 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008892 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008893 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008894 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008895 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008896 + pp.name);
8897 continue;
8898 }
8899 p.copyFrom(pp);
8900 } else if (idObj != null) {
8901 String msg = "Bad package setting: package " + pp.name
8902 + " has shared uid " + pp.sharedId
8903 + " that is not a shared uid\n";
8904 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008905 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008906 } else {
8907 String msg = "Bad package setting: package " + pp.name
8908 + " has shared uid " + pp.sharedId
8909 + " that is not defined\n";
8910 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008911 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008912 }
8913 }
8914 mPendingPackages.clear();
8915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008916 mReadMessages.append("Read completed successfully: "
8917 + mPackages.size() + " packages, "
8918 + mSharedUsers.size() + " shared uids\n");
8919
8920 return true;
8921 }
8922
8923 private int readInt(XmlPullParser parser, String ns, String name,
8924 int defValue) {
8925 String v = parser.getAttributeValue(ns, name);
8926 try {
8927 if (v == null) {
8928 return defValue;
8929 }
8930 return Integer.parseInt(v);
8931 } catch (NumberFormatException e) {
8932 reportSettingsProblem(Log.WARN,
8933 "Error in package manager settings: attribute " +
8934 name + " has bad integer value " + v + " at "
8935 + parser.getPositionDescription());
8936 }
8937 return defValue;
8938 }
8939
8940 private void readPermissionsLP(HashMap<String, BasePermission> out,
8941 XmlPullParser parser)
8942 throws IOException, XmlPullParserException {
8943 int outerDepth = parser.getDepth();
8944 int type;
8945 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8946 && (type != XmlPullParser.END_TAG
8947 || parser.getDepth() > outerDepth)) {
8948 if (type == XmlPullParser.END_TAG
8949 || type == XmlPullParser.TEXT) {
8950 continue;
8951 }
8952
8953 String tagName = parser.getName();
8954 if (tagName.equals("item")) {
8955 String name = parser.getAttributeValue(null, "name");
8956 String sourcePackage = parser.getAttributeValue(null, "package");
8957 String ptype = parser.getAttributeValue(null, "type");
8958 if (name != null && sourcePackage != null) {
8959 boolean dynamic = "dynamic".equals(ptype);
8960 BasePermission bp = new BasePermission(name, sourcePackage,
8961 dynamic
8962 ? BasePermission.TYPE_DYNAMIC
8963 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008964 bp.protectionLevel = readInt(parser, null, "protection",
8965 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008966 if (dynamic) {
8967 PermissionInfo pi = new PermissionInfo();
8968 pi.packageName = sourcePackage.intern();
8969 pi.name = name.intern();
8970 pi.icon = readInt(parser, null, "icon", 0);
8971 pi.nonLocalizedLabel = parser.getAttributeValue(
8972 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008973 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008974 bp.pendingInfo = pi;
8975 }
8976 out.put(bp.name, bp);
8977 } else {
8978 reportSettingsProblem(Log.WARN,
8979 "Error in package manager settings: permissions has"
8980 + " no name at " + parser.getPositionDescription());
8981 }
8982 } else {
8983 reportSettingsProblem(Log.WARN,
8984 "Unknown element reading permissions: "
8985 + parser.getName() + " at "
8986 + parser.getPositionDescription());
8987 }
8988 XmlUtils.skipCurrentTag(parser);
8989 }
8990 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008992 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008993 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008994 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008995 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008996 String codePathStr = parser.getAttributeValue(null, "codePath");
8997 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008998 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008999 resourcePathStr = codePathStr;
9000 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009001 String version = parser.getAttributeValue(null, "version");
9002 int versionCode = 0;
9003 if (version != null) {
9004 try {
9005 versionCode = Integer.parseInt(version);
9006 } catch (NumberFormatException e) {
9007 }
9008 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009010 int pkgFlags = 0;
9011 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009012 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009013 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009014 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009015 String timeStampStr = parser.getAttributeValue(null, "ts");
9016 if (timeStampStr != null) {
9017 try {
9018 long timeStamp = Long.parseLong(timeStampStr);
9019 ps.setTimeStamp(timeStamp, timeStampStr);
9020 } catch (NumberFormatException e) {
9021 }
9022 }
9023 String idStr = parser.getAttributeValue(null, "userId");
9024 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
9025 if(ps.userId <= 0) {
9026 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9027 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
9028 }
9029 int outerDepth = parser.getDepth();
9030 int type;
9031 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9032 && (type != XmlPullParser.END_TAG
9033 || parser.getDepth() > outerDepth)) {
9034 if (type == XmlPullParser.END_TAG
9035 || type == XmlPullParser.TEXT) {
9036 continue;
9037 }
9038
9039 String tagName = parser.getName();
9040 if (tagName.equals("perms")) {
9041 readGrantedPermissionsLP(parser,
9042 ps.grantedPermissions);
9043 } else {
9044 reportSettingsProblem(Log.WARN,
9045 "Unknown element under <updated-package>: "
9046 + parser.getName());
9047 XmlUtils.skipCurrentTag(parser);
9048 }
9049 }
9050 mDisabledSysPackages.put(name, ps);
9051 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009053 private void readPackageLP(XmlPullParser parser)
9054 throws XmlPullParserException, IOException {
9055 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009056 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009057 String idStr = null;
9058 String sharedIdStr = null;
9059 String codePathStr = null;
9060 String resourcePathStr = null;
9061 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009062 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009063 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009064 int pkgFlags = 0;
9065 String timeStampStr;
9066 long timeStamp = 0;
9067 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009068 String version = null;
9069 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009070 try {
9071 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009072 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009073 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009074 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009075 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9076 codePathStr = parser.getAttributeValue(null, "codePath");
9077 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009078 version = parser.getAttributeValue(null, "version");
9079 if (version != null) {
9080 try {
9081 versionCode = Integer.parseInt(version);
9082 } catch (NumberFormatException e) {
9083 }
9084 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009085 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009086
9087 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009088 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009089 try {
9090 pkgFlags = Integer.parseInt(systemStr);
9091 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009092 }
9093 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009094 // For backward compatibility
9095 systemStr = parser.getAttributeValue(null, "system");
9096 if (systemStr != null) {
9097 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9098 } else {
9099 // Old settings that don't specify system... just treat
9100 // them as system, good enough.
9101 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009103 }
9104 timeStampStr = parser.getAttributeValue(null, "ts");
9105 if (timeStampStr != null) {
9106 try {
9107 timeStamp = Long.parseLong(timeStampStr);
9108 } catch (NumberFormatException e) {
9109 }
9110 }
9111 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9112 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9113 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9114 if (resourcePathStr == null) {
9115 resourcePathStr = codePathStr;
9116 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009117 if (realName != null) {
9118 realName = realName.intern();
9119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009120 if (name == null) {
9121 reportSettingsProblem(Log.WARN,
9122 "Error in package manager settings: <package> has no name at "
9123 + parser.getPositionDescription());
9124 } else if (codePathStr == null) {
9125 reportSettingsProblem(Log.WARN,
9126 "Error in package manager settings: <package> has no codePath at "
9127 + parser.getPositionDescription());
9128 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009129 packageSetting = addPackageLP(name.intern(), realName,
9130 new File(codePathStr), new File(resourcePathStr),
9131 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009132 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9133 + ": userId=" + userId + " pkg=" + packageSetting);
9134 if (packageSetting == null) {
9135 reportSettingsProblem(Log.ERROR,
9136 "Failure adding uid " + userId
9137 + " while parsing settings at "
9138 + parser.getPositionDescription());
9139 } else {
9140 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9141 }
9142 } else if (sharedIdStr != null) {
9143 userId = sharedIdStr != null
9144 ? Integer.parseInt(sharedIdStr) : 0;
9145 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009146 packageSetting = new PendingPackage(name.intern(), realName,
9147 new File(codePathStr), new File(resourcePathStr),
9148 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009149 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9150 mPendingPackages.add((PendingPackage) packageSetting);
9151 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9152 + ": sharedUserId=" + userId + " pkg="
9153 + packageSetting);
9154 } else {
9155 reportSettingsProblem(Log.WARN,
9156 "Error in package manager settings: package "
9157 + name + " has bad sharedId " + sharedIdStr
9158 + " at " + parser.getPositionDescription());
9159 }
9160 } else {
9161 reportSettingsProblem(Log.WARN,
9162 "Error in package manager settings: package "
9163 + name + " has bad userId " + idStr + " at "
9164 + parser.getPositionDescription());
9165 }
9166 } catch (NumberFormatException e) {
9167 reportSettingsProblem(Log.WARN,
9168 "Error in package manager settings: package "
9169 + name + " has bad userId " + idStr + " at "
9170 + parser.getPositionDescription());
9171 }
9172 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009173 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009174 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009175 final String enabledStr = parser.getAttributeValue(null, "enabled");
9176 if (enabledStr != null) {
9177 if (enabledStr.equalsIgnoreCase("true")) {
9178 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9179 } else if (enabledStr.equalsIgnoreCase("false")) {
9180 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9181 } else if (enabledStr.equalsIgnoreCase("default")) {
9182 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9183 } else {
9184 reportSettingsProblem(Log.WARN,
9185 "Error in package manager settings: package "
9186 + name + " has bad enabled value: " + idStr
9187 + " at " + parser.getPositionDescription());
9188 }
9189 } else {
9190 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9191 }
9192 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9193 if (installStatusStr != null) {
9194 if (installStatusStr.equalsIgnoreCase("false")) {
9195 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9196 } else {
9197 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9198 }
9199 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009201 int outerDepth = parser.getDepth();
9202 int type;
9203 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9204 && (type != XmlPullParser.END_TAG
9205 || parser.getDepth() > outerDepth)) {
9206 if (type == XmlPullParser.END_TAG
9207 || type == XmlPullParser.TEXT) {
9208 continue;
9209 }
9210
9211 String tagName = parser.getName();
9212 if (tagName.equals("disabled-components")) {
9213 readDisabledComponentsLP(packageSetting, parser);
9214 } else if (tagName.equals("enabled-components")) {
9215 readEnabledComponentsLP(packageSetting, parser);
9216 } else if (tagName.equals("sigs")) {
9217 packageSetting.signatures.readXml(parser, mPastSignatures);
9218 } else if (tagName.equals("perms")) {
9219 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009220 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009221 packageSetting.permissionsFixed = true;
9222 } else {
9223 reportSettingsProblem(Log.WARN,
9224 "Unknown element under <package>: "
9225 + parser.getName());
9226 XmlUtils.skipCurrentTag(parser);
9227 }
9228 }
9229 } else {
9230 XmlUtils.skipCurrentTag(parser);
9231 }
9232 }
9233
9234 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9235 XmlPullParser parser)
9236 throws IOException, XmlPullParserException {
9237 int outerDepth = parser.getDepth();
9238 int type;
9239 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9240 && (type != XmlPullParser.END_TAG
9241 || parser.getDepth() > outerDepth)) {
9242 if (type == XmlPullParser.END_TAG
9243 || type == XmlPullParser.TEXT) {
9244 continue;
9245 }
9246
9247 String tagName = parser.getName();
9248 if (tagName.equals("item")) {
9249 String name = parser.getAttributeValue(null, "name");
9250 if (name != null) {
9251 packageSetting.disabledComponents.add(name.intern());
9252 } else {
9253 reportSettingsProblem(Log.WARN,
9254 "Error in package manager settings: <disabled-components> has"
9255 + " no name at " + parser.getPositionDescription());
9256 }
9257 } else {
9258 reportSettingsProblem(Log.WARN,
9259 "Unknown element under <disabled-components>: "
9260 + parser.getName());
9261 }
9262 XmlUtils.skipCurrentTag(parser);
9263 }
9264 }
9265
9266 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9267 XmlPullParser parser)
9268 throws IOException, XmlPullParserException {
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("item")) {
9281 String name = parser.getAttributeValue(null, "name");
9282 if (name != null) {
9283 packageSetting.enabledComponents.add(name.intern());
9284 } else {
9285 reportSettingsProblem(Log.WARN,
9286 "Error in package manager settings: <enabled-components> has"
9287 + " no name at " + parser.getPositionDescription());
9288 }
9289 } else {
9290 reportSettingsProblem(Log.WARN,
9291 "Unknown element under <enabled-components>: "
9292 + parser.getName());
9293 }
9294 XmlUtils.skipCurrentTag(parser);
9295 }
9296 }
9297
9298 private void readSharedUserLP(XmlPullParser parser)
9299 throws XmlPullParserException, IOException {
9300 String name = null;
9301 String idStr = null;
9302 int pkgFlags = 0;
9303 SharedUserSetting su = null;
9304 try {
9305 name = parser.getAttributeValue(null, "name");
9306 idStr = parser.getAttributeValue(null, "userId");
9307 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9308 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9309 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9310 }
9311 if (name == null) {
9312 reportSettingsProblem(Log.WARN,
9313 "Error in package manager settings: <shared-user> has no name at "
9314 + parser.getPositionDescription());
9315 } else if (userId == 0) {
9316 reportSettingsProblem(Log.WARN,
9317 "Error in package manager settings: shared-user "
9318 + name + " has bad userId " + idStr + " at "
9319 + parser.getPositionDescription());
9320 } else {
9321 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9322 reportSettingsProblem(Log.ERROR,
9323 "Occurred while parsing settings at "
9324 + parser.getPositionDescription());
9325 }
9326 }
9327 } catch (NumberFormatException e) {
9328 reportSettingsProblem(Log.WARN,
9329 "Error in package manager settings: package "
9330 + name + " has bad userId " + idStr + " at "
9331 + parser.getPositionDescription());
9332 };
9333
9334 if (su != null) {
9335 int outerDepth = parser.getDepth();
9336 int type;
9337 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9338 && (type != XmlPullParser.END_TAG
9339 || parser.getDepth() > outerDepth)) {
9340 if (type == XmlPullParser.END_TAG
9341 || type == XmlPullParser.TEXT) {
9342 continue;
9343 }
9344
9345 String tagName = parser.getName();
9346 if (tagName.equals("sigs")) {
9347 su.signatures.readXml(parser, mPastSignatures);
9348 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009349 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009350 } else {
9351 reportSettingsProblem(Log.WARN,
9352 "Unknown element under <shared-user>: "
9353 + parser.getName());
9354 XmlUtils.skipCurrentTag(parser);
9355 }
9356 }
9357
9358 } else {
9359 XmlUtils.skipCurrentTag(parser);
9360 }
9361 }
9362
9363 private void readGrantedPermissionsLP(XmlPullParser parser,
9364 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9365 int outerDepth = parser.getDepth();
9366 int type;
9367 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9368 && (type != XmlPullParser.END_TAG
9369 || parser.getDepth() > outerDepth)) {
9370 if (type == XmlPullParser.END_TAG
9371 || type == XmlPullParser.TEXT) {
9372 continue;
9373 }
9374
9375 String tagName = parser.getName();
9376 if (tagName.equals("item")) {
9377 String name = parser.getAttributeValue(null, "name");
9378 if (name != null) {
9379 outPerms.add(name.intern());
9380 } else {
9381 reportSettingsProblem(Log.WARN,
9382 "Error in package manager settings: <perms> has"
9383 + " no name at " + parser.getPositionDescription());
9384 }
9385 } else {
9386 reportSettingsProblem(Log.WARN,
9387 "Unknown element under <perms>: "
9388 + parser.getName());
9389 }
9390 XmlUtils.skipCurrentTag(parser);
9391 }
9392 }
9393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009394 private void readPreferredActivitiesLP(XmlPullParser parser)
9395 throws XmlPullParserException, IOException {
9396 int outerDepth = parser.getDepth();
9397 int type;
9398 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9399 && (type != XmlPullParser.END_TAG
9400 || parser.getDepth() > outerDepth)) {
9401 if (type == XmlPullParser.END_TAG
9402 || type == XmlPullParser.TEXT) {
9403 continue;
9404 }
9405
9406 String tagName = parser.getName();
9407 if (tagName.equals("item")) {
9408 PreferredActivity pa = new PreferredActivity(parser);
9409 if (pa.mParseError == null) {
9410 mPreferredActivities.addFilter(pa);
9411 } else {
9412 reportSettingsProblem(Log.WARN,
9413 "Error in package manager settings: <preferred-activity> "
9414 + pa.mParseError + " at "
9415 + parser.getPositionDescription());
9416 }
9417 } else {
9418 reportSettingsProblem(Log.WARN,
9419 "Unknown element under <preferred-activities>: "
9420 + parser.getName());
9421 XmlUtils.skipCurrentTag(parser);
9422 }
9423 }
9424 }
9425
9426 // Returns -1 if we could not find an available UserId to assign
9427 private int newUserIdLP(Object obj) {
9428 // Let's be stupidly inefficient for now...
9429 final int N = mUserIds.size();
9430 for (int i=0; i<N; i++) {
9431 if (mUserIds.get(i) == null) {
9432 mUserIds.set(i, obj);
9433 return FIRST_APPLICATION_UID + i;
9434 }
9435 }
9436
9437 // None left?
9438 if (N >= MAX_APPLICATION_UIDS) {
9439 return -1;
9440 }
9441
9442 mUserIds.add(obj);
9443 return FIRST_APPLICATION_UID + N;
9444 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009446 public PackageSetting getDisabledSystemPkg(String name) {
9447 synchronized(mPackages) {
9448 PackageSetting ps = mDisabledSysPackages.get(name);
9449 return ps;
9450 }
9451 }
9452
9453 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9454 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9455 if (Config.LOGV) {
9456 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9457 + " componentName = " + componentInfo.name);
9458 Log.v(TAG, "enabledComponents: "
9459 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9460 Log.v(TAG, "disabledComponents: "
9461 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9462 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009463 if (packageSettings == null) {
9464 if (false) {
9465 Log.w(TAG, "WAITING FOR DEBUGGER");
9466 Debug.waitForDebugger();
9467 Log.i(TAG, "We will crash!");
9468 }
9469 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009470 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9471 || ((componentInfo.enabled
9472 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9473 || (componentInfo.applicationInfo.enabled
9474 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9475 && !packageSettings.disabledComponents.contains(componentInfo.name))
9476 || packageSettings.enabledComponents.contains(componentInfo.name));
9477 }
9478 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009479
9480 // ------- apps on sdcard specific code -------
9481 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009482 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009483 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009484 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009485 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009486
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009487 private String getEncryptKey() {
9488 try {
9489 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9490 if (sdEncKey == null) {
9491 sdEncKey = SystemKeyStore.getInstance().
9492 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9493 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009494 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009495 return null;
9496 }
9497 }
9498 return sdEncKey;
9499 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009500 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009501 return null;
9502 }
9503 }
9504
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009505 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009506 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009507 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009508 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009509 if (list != null) {
9510 int idx = 0;
9511 int idList[] = new int[MAX_CONTAINERS];
9512 boolean neverFound = true;
9513 for (String name : list) {
9514 // Ignore null entries
9515 if (name == null) {
9516 continue;
9517 }
9518 int sidx = name.indexOf(prefix);
9519 if (sidx == -1) {
9520 // Not a temp file. just ignore
9521 continue;
9522 }
9523 String subStr = name.substring(sidx + prefix.length());
9524 idList[idx] = -1;
9525 if (subStr != null) {
9526 try {
9527 int cid = Integer.parseInt(subStr);
9528 idList[idx++] = cid;
9529 neverFound = false;
9530 } catch (NumberFormatException e) {
9531 }
9532 }
9533 }
9534 if (!neverFound) {
9535 // Sort idList
9536 Arrays.sort(idList);
9537 for (int j = 1; j <= idList.length; j++) {
9538 if (idList[j-1] != j) {
9539 tmpIdx = j;
9540 break;
9541 }
9542 }
9543 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009544 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009545 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009546 }
9547
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009548 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009549 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009550 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009551 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
Marco Nelissen584f1372010-05-24 16:34:30 -07009552 int callingUid = Binder.getCallingUid();
9553 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009554 throw new SecurityException("Media status can only be updated by the system");
9555 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009556 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009557 Log.i(TAG, "Updating external media status from " +
9558 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9559 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009560 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9561 mediaStatus+", mMediaMounted=" + mMediaMounted);
9562 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009563 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9564 reportStatus ? 1 : 0, -1);
9565 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009566 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009567 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009568 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009569 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009570 // Queue up an async operation since the package installation may take a little while.
9571 mHandler.post(new Runnable() {
9572 public void run() {
9573 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009574 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009575 }
9576 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009577 }
9578
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009579 /*
9580 * Collect information of applications on external media, map them
9581 * against existing containers and update information based on current
9582 * mount status. Please note that we always have to report status
9583 * if reportStatus has been set to true especially when unloading packages.
9584 */
9585 private void updateExternalMediaStatusInner(boolean mediaStatus,
9586 boolean reportStatus) {
9587 // Collection of uids
9588 int uidArr[] = null;
9589 // Collection of stale containers
9590 HashSet<String> removeCids = new HashSet<String>();
9591 // Collection of packages on external media with valid containers.
9592 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9593 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009594 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009595 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009596 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009597 } else {
9598 // Process list of secure containers and categorize them
9599 // as active or stale based on their package internal state.
9600 int uidList[] = new int[list.length];
9601 int num = 0;
9602 synchronized (mPackages) {
9603 for (String cid : list) {
9604 SdInstallArgs args = new SdInstallArgs(cid);
9605 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009606 String pkgName = args.getPackageName();
9607 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009608 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9609 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009610 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009611 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009612 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9613 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009614 // The package status is changed only if the code path
9615 // matches between settings and the container id.
9616 if (ps != null && ps.codePathString != null &&
9617 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009618 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9619 " corresponds to pkg : " + pkgName +
9620 " at code path: " + ps.codePathString);
9621 // We do have a valid package installed on sdcard
9622 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009623 int uid = ps.userId;
9624 if (uid != -1) {
9625 uidList[num++] = uid;
9626 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009627 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009628 // Stale container on sdcard. Just delete
9629 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9630 removeCids.add(cid);
9631 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009632 }
9633 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009634
9635 if (num > 0) {
9636 // Sort uid list
9637 Arrays.sort(uidList, 0, num);
9638 // Throw away duplicates
9639 uidArr = new int[num];
9640 uidArr[0] = uidList[0];
9641 int di = 0;
9642 for (int i = 1; i < num; i++) {
9643 if (uidList[i-1] != uidList[i]) {
9644 uidArr[di++] = uidList[i];
9645 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009646 }
9647 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009648 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009649 // Process packages with valid entries.
9650 if (mediaStatus) {
9651 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009652 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009653 startCleaningPackages();
9654 } else {
9655 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009656 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009657 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009658 }
9659
9660 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009661 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009662 int size = pkgList.size();
9663 if (size > 0) {
9664 // Send broadcasts here
9665 Bundle extras = new Bundle();
9666 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9667 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009668 if (uidArr != null) {
9669 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9670 }
9671 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9672 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009673 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009674 }
9675 }
9676
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009677 /*
9678 * Look at potentially valid container ids from processCids
9679 * If package information doesn't match the one on record
9680 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009681 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009682 */
9683 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009684 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009685 ArrayList<String> pkgList = new ArrayList<String>();
9686 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009687 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009688 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009689 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009690 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9691 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009692 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009693 try {
9694 // Make sure there are no container errors first.
9695 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9696 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009697 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009698 " when installing from sdcard");
9699 continue;
9700 }
9701 // Check code path here.
9702 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009703 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009704 " does not match one in settings " + codePath);
9705 continue;
9706 }
9707 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009708 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009709 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009710 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009711 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9712 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009713 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009714 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009715 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009716 retCode = PackageManager.INSTALL_SUCCEEDED;
9717 pkgList.add(pkg.packageName);
9718 // Post process args
9719 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9720 }
9721 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009722 Slog.i(TAG, "Failed to install pkg from " +
9723 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009724 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009725 }
9726
9727 } finally {
9728 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9729 // Don't destroy container here. Wait till gc clears things up.
9730 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009731 }
9732 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009733 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009734 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009735 // If the platform SDK has changed since the last time we booted,
9736 // we need to re-grant app permission to catch any new ones that
9737 // appear. This is really a hack, and means that apps can in some
9738 // cases get permissions that the user didn't initially explicitly
9739 // allow... it would be nice to have some better way to handle
9740 // this situation.
9741 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9742 != mSdkVersion;
9743 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9744 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9745 + "; regranting permissions for external storage");
9746 mSettings.mExternalSdkPlatform = mSdkVersion;
9747
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009748 // Make sure group IDs have been assigned, and any permission
9749 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009750 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009751 // Persist settings
9752 mSettings.writeLP();
9753 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009754 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009755 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009756 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009757 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009758 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009759 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009760 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009761 }
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009762 // List stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009763 if (removeCids != null) {
9764 for (String cid : removeCids) {
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009765 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009766 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009767 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009768 }
9769
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009770 /*
9771 * Utility method to unload a list of specified containers
9772 */
9773 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9774 // Just unmount all valid containers.
9775 for (SdInstallArgs arg : cidArgs) {
9776 synchronized (mInstallLock) {
9777 arg.doPostDeleteLI(false);
9778 }
9779 }
9780 }
9781
9782 /*
9783 * Unload packages mounted on external media. This involves deleting
9784 * package data from internal structures, sending broadcasts about
9785 * diabled packages, gc'ing to free up references, unmounting all
9786 * secure containers corresponding to packages on external media, and
9787 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9788 * Please note that we always have to post this message if status has
9789 * been requested no matter what.
9790 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009791 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009792 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009793 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009794 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009795 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009796 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009797 for (SdInstallArgs args : keys) {
9798 String cid = args.cid;
9799 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009800 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009801 // Delete package internally
9802 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9803 synchronized (mInstallLock) {
9804 boolean res = deletePackageLI(pkgName, false,
9805 PackageManager.DONT_DELETE_DATA, outInfo);
9806 if (res) {
9807 pkgList.add(pkgName);
9808 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009809 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009810 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009811 }
9812 }
9813 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009814 // We have to absolutely send UPDATED_MEDIA_STATUS only
9815 // after confirming that all the receivers processed the ordered
9816 // broadcast when packages get disabled, force a gc to clean things up.
9817 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009818 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009819 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9820 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9821 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009822 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9823 reportStatus ? 1 : 0, 1, keys);
9824 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009825 }
9826 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009827 } else {
9828 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9829 reportStatus ? 1 : 0, -1, keys);
9830 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009831 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009832 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009833
9834 public void movePackage(final String packageName,
9835 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009836 mContext.enforceCallingOrSelfPermission(
9837 android.Manifest.permission.MOVE_PACKAGE, null);
9838 int returnCode = PackageManager.MOVE_SUCCEEDED;
9839 int currFlags = 0;
9840 int newFlags = 0;
9841 synchronized (mPackages) {
9842 PackageParser.Package pkg = mPackages.get(packageName);
9843 if (pkg == null) {
9844 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009845 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009846 // Disable moving fwd locked apps and system packages
9847 if (pkg.applicationInfo != null &&
9848 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9849 Slog.w(TAG, "Cannot move system application");
9850 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9851 } else if (pkg.applicationInfo != null &&
9852 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9853 Slog.w(TAG, "Cannot move forward locked app.");
9854 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009855 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009856 // Find install location first
9857 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9858 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9859 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009860 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009861 } else {
9862 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9863 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9864 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
9865 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9866 if (newFlags == currFlags) {
9867 Slog.w(TAG, "No move required. Trying to move to same location");
9868 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9869 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009870 }
9871 }
9872 }
9873 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07009874 processPendingMove(new MoveParams(null, observer, 0, packageName), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009875 } else {
9876 Message msg = mHandler.obtainMessage(INIT_COPY);
9877 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9878 pkg.applicationInfo.publicSourceDir);
9879 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9880 packageName);
9881 msg.obj = mp;
9882 mHandler.sendMessage(msg);
9883 }
9884 }
9885 }
9886
9887 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9888 // Queue up an async operation since the package deletion may take a little while.
9889 mHandler.post(new Runnable() {
9890 public void run() {
9891 mHandler.removeCallbacks(this);
9892 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009893 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9894 int uidArr[] = null;
9895 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009896 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009897 PackageParser.Package pkg = mPackages.get(mp.packageName);
9898 if (pkg == null ) {
9899 Slog.w(TAG, " Package " + mp.packageName +
9900 " doesn't exist. Aborting move");
9901 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9902 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9903 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9904 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9905 " Aborting move and returning error");
9906 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9907 } else {
9908 uidArr = new int[] { pkg.applicationInfo.uid };
9909 pkgList = new ArrayList<String>();
9910 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009911 }
9912 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009913 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9914 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009915 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009916 // Update package code and resource paths
9917 synchronized (mInstallLock) {
9918 synchronized (mPackages) {
9919 PackageParser.Package pkg = mPackages.get(mp.packageName);
9920 // Recheck for package again.
9921 if (pkg == null ) {
9922 Slog.w(TAG, " Package " + mp.packageName +
9923 " doesn't exist. Aborting move");
9924 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9925 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9926 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9927 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9928 " Aborting move and returning error");
9929 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9930 } else {
9931 String oldCodePath = pkg.mPath;
9932 String newCodePath = mp.targetArgs.getCodePath();
9933 String newResPath = mp.targetArgs.getResourcePath();
9934 pkg.mPath = newCodePath;
9935 // Move dex files around
9936 if (moveDexFilesLI(pkg)
9937 != PackageManager.INSTALL_SUCCEEDED) {
9938 // Moving of dex files failed. Set
9939 // error code and abort move.
9940 pkg.mPath = pkg.mScanPath;
9941 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9942 } else {
9943 pkg.mScanPath = newCodePath;
9944 pkg.applicationInfo.sourceDir = newCodePath;
9945 pkg.applicationInfo.publicSourceDir = newResPath;
9946 PackageSetting ps = (PackageSetting) pkg.mExtras;
9947 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9948 ps.codePathString = ps.codePath.getPath();
9949 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9950 ps.resourcePathString = ps.resourcePath.getPath();
9951 // Set the application info flag correctly.
9952 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9953 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9954 } else {
9955 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9956 }
9957 ps.setFlags(pkg.applicationInfo.flags);
9958 mAppDirs.remove(oldCodePath);
9959 mAppDirs.put(newCodePath, pkg);
9960 // Persist settings
9961 mSettings.writeLP();
9962 }
9963 }
9964 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009965 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07009966 // Send resources available broadcast
9967 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009968 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009969 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009970 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009971 // Clean up failed installation
9972 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009973 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009974 }
9975 } else {
9976 // Force a gc to clear things up.
9977 Runtime.getRuntime().gc();
9978 // Delete older code
9979 synchronized (mInstallLock) {
9980 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009981 }
9982 }
9983 IPackageMoveObserver observer = mp.observer;
9984 if (observer != null) {
9985 try {
9986 observer.packageMoved(mp.packageName, returnCode);
9987 } catch (RemoteException e) {
9988 Log.i(TAG, "Observer no longer exists.");
9989 }
9990 }
9991 }
9992 });
9993 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009994
9995 public boolean setInstallLocation(int loc) {
9996 mContext.enforceCallingOrSelfPermission(
9997 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9998 if (getInstallLocation() == loc) {
9999 return true;
10000 }
10001 if (loc == PackageHelper.APP_INSTALL_AUTO ||
10002 loc == PackageHelper.APP_INSTALL_INTERNAL ||
10003 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
10004 android.provider.Settings.System.putInt(mContext.getContentResolver(),
10005 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
10006 return true;
10007 }
10008 return false;
10009 }
10010
10011 public int getInstallLocation() {
10012 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
10013 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
10014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010015}