blob: 9d8c072a02cbc2e5209b890ca43b08ea5c1d32e1 [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();
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001498 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 }
1500 return generatePackageInfo(ps.pkg, flags);
1501 }
1502 return null;
1503 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1506 synchronized (mPackages) {
1507 PackageParser.Package p = mPackages.get(packageName);
1508 if (Config.LOGV) Log.v(
1509 TAG, "getApplicationInfo " + packageName
1510 + ": " + p);
1511 if (p != null) {
1512 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001513 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 }
1515 if ("android".equals(packageName)||"system".equals(packageName)) {
1516 return mAndroidApplication;
1517 }
1518 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1519 return generateApplicationInfoFromSettingsLP(packageName, flags);
1520 }
1521 }
1522 return null;
1523 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001524
1525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1527 mContext.enforceCallingOrSelfPermission(
1528 android.Manifest.permission.CLEAR_APP_CACHE, null);
1529 // Queue up an async operation since clearing cache may take a little while.
1530 mHandler.post(new Runnable() {
1531 public void run() {
1532 mHandler.removeCallbacks(this);
1533 int retCode = -1;
1534 if (mInstaller != null) {
1535 retCode = mInstaller.freeCache(freeStorageSize);
1536 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001537 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 }
1539 } //end if mInstaller
1540 if (observer != null) {
1541 try {
1542 observer.onRemoveCompleted(null, (retCode >= 0));
1543 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001544 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 }
1546 }
1547 }
1548 });
1549 }
1550
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001551 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001552 mContext.enforceCallingOrSelfPermission(
1553 android.Manifest.permission.CLEAR_APP_CACHE, null);
1554 // Queue up an async operation since clearing cache may take a little while.
1555 mHandler.post(new Runnable() {
1556 public void run() {
1557 mHandler.removeCallbacks(this);
1558 int retCode = -1;
1559 if (mInstaller != null) {
1560 retCode = mInstaller.freeCache(freeStorageSize);
1561 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001562 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001563 }
1564 }
1565 if(pi != null) {
1566 try {
1567 // Callback via pending intent
1568 int code = (retCode >= 0) ? 1 : 0;
1569 pi.sendIntent(null, code, null,
1570 null, null);
1571 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001572 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001573 }
1574 }
1575 }
1576 });
1577 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1580 synchronized (mPackages) {
1581 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001582
1583 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001585 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 }
1587 if (mResolveComponentName.equals(component)) {
1588 return mResolveActivity;
1589 }
1590 }
1591 return null;
1592 }
1593
1594 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1595 synchronized (mPackages) {
1596 PackageParser.Activity a = mReceivers.mActivities.get(component);
1597 if (Config.LOGV) Log.v(
1598 TAG, "getReceiverInfo " + component + ": " + a);
1599 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1600 return PackageParser.generateActivityInfo(a, flags);
1601 }
1602 }
1603 return null;
1604 }
1605
1606 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1607 synchronized (mPackages) {
1608 PackageParser.Service s = mServices.mServices.get(component);
1609 if (Config.LOGV) Log.v(
1610 TAG, "getServiceInfo " + component + ": " + s);
1611 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1612 return PackageParser.generateServiceInfo(s, flags);
1613 }
1614 }
1615 return null;
1616 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 public String[] getSystemSharedLibraryNames() {
1619 Set<String> libSet;
1620 synchronized (mPackages) {
1621 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001622 int size = libSet.size();
1623 if (size > 0) {
1624 String[] libs = new String[size];
1625 libSet.toArray(libs);
1626 return libs;
1627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001629 return null;
1630 }
1631
1632 public FeatureInfo[] getSystemAvailableFeatures() {
1633 Collection<FeatureInfo> featSet;
1634 synchronized (mPackages) {
1635 featSet = mAvailableFeatures.values();
1636 int size = featSet.size();
1637 if (size > 0) {
1638 FeatureInfo[] features = new FeatureInfo[size+1];
1639 featSet.toArray(features);
1640 FeatureInfo fi = new FeatureInfo();
1641 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1642 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1643 features[size] = fi;
1644 return features;
1645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 }
1647 return null;
1648 }
1649
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001650 public boolean hasSystemFeature(String name) {
1651 synchronized (mPackages) {
1652 return mAvailableFeatures.containsKey(name);
1653 }
1654 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 public int checkPermission(String permName, String pkgName) {
1657 synchronized (mPackages) {
1658 PackageParser.Package p = mPackages.get(pkgName);
1659 if (p != null && p.mExtras != null) {
1660 PackageSetting ps = (PackageSetting)p.mExtras;
1661 if (ps.sharedUser != null) {
1662 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1663 return PackageManager.PERMISSION_GRANTED;
1664 }
1665 } else if (ps.grantedPermissions.contains(permName)) {
1666 return PackageManager.PERMISSION_GRANTED;
1667 }
1668 }
1669 }
1670 return PackageManager.PERMISSION_DENIED;
1671 }
1672
1673 public int checkUidPermission(String permName, int uid) {
1674 synchronized (mPackages) {
1675 Object obj = mSettings.getUserIdLP(uid);
1676 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001677 GrantedPermissions gp = (GrantedPermissions)obj;
1678 if (gp.grantedPermissions.contains(permName)) {
1679 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 }
1681 } else {
1682 HashSet<String> perms = mSystemPermissions.get(uid);
1683 if (perms != null && perms.contains(permName)) {
1684 return PackageManager.PERMISSION_GRANTED;
1685 }
1686 }
1687 }
1688 return PackageManager.PERMISSION_DENIED;
1689 }
1690
1691 private BasePermission findPermissionTreeLP(String permName) {
1692 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1693 if (permName.startsWith(bp.name) &&
1694 permName.length() > bp.name.length() &&
1695 permName.charAt(bp.name.length()) == '.') {
1696 return bp;
1697 }
1698 }
1699 return null;
1700 }
1701
1702 private BasePermission checkPermissionTreeLP(String permName) {
1703 if (permName != null) {
1704 BasePermission bp = findPermissionTreeLP(permName);
1705 if (bp != null) {
1706 if (bp.uid == Binder.getCallingUid()) {
1707 return bp;
1708 }
1709 throw new SecurityException("Calling uid "
1710 + Binder.getCallingUid()
1711 + " is not allowed to add to permission tree "
1712 + bp.name + " owned by uid " + bp.uid);
1713 }
1714 }
1715 throw new SecurityException("No permission tree found for " + permName);
1716 }
1717
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001718 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1719 if (s1 == null) {
1720 return s2 == null;
1721 }
1722 if (s2 == null) {
1723 return false;
1724 }
1725 if (s1.getClass() != s2.getClass()) {
1726 return false;
1727 }
1728 return s1.equals(s2);
1729 }
1730
1731 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1732 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001733 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001734 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1735 if (!compareStrings(pi1.name, pi2.name)) return false;
1736 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1737 // We'll take care of setting this one.
1738 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1739 // These are not currently stored in settings.
1740 //if (!compareStrings(pi1.group, pi2.group)) return false;
1741 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1742 //if (pi1.labelRes != pi2.labelRes) return false;
1743 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1744 return true;
1745 }
1746
1747 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1748 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1749 throw new SecurityException("Label must be specified in permission");
1750 }
1751 BasePermission tree = checkPermissionTreeLP(info.name);
1752 BasePermission bp = mSettings.mPermissions.get(info.name);
1753 boolean added = bp == null;
1754 boolean changed = true;
1755 if (added) {
1756 bp = new BasePermission(info.name, tree.sourcePackage,
1757 BasePermission.TYPE_DYNAMIC);
1758 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1759 throw new SecurityException(
1760 "Not allowed to modify non-dynamic permission "
1761 + info.name);
1762 } else {
1763 if (bp.protectionLevel == info.protectionLevel
1764 && bp.perm.owner.equals(tree.perm.owner)
1765 && bp.uid == tree.uid
1766 && comparePermissionInfos(bp.perm.info, info)) {
1767 changed = false;
1768 }
1769 }
1770 bp.protectionLevel = info.protectionLevel;
1771 bp.perm = new PackageParser.Permission(tree.perm.owner,
1772 new PermissionInfo(info));
1773 bp.perm.info.packageName = tree.perm.info.packageName;
1774 bp.uid = tree.uid;
1775 if (added) {
1776 mSettings.mPermissions.put(info.name, bp);
1777 }
1778 if (changed) {
1779 if (!async) {
1780 mSettings.writeLP();
1781 } else {
1782 scheduleWriteSettingsLocked();
1783 }
1784 }
1785 return added;
1786 }
1787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 public boolean addPermission(PermissionInfo info) {
1789 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001790 return addPermissionLocked(info, false);
1791 }
1792 }
1793
1794 public boolean addPermissionAsync(PermissionInfo info) {
1795 synchronized (mPackages) {
1796 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 }
1798 }
1799
1800 public void removePermission(String name) {
1801 synchronized (mPackages) {
1802 checkPermissionTreeLP(name);
1803 BasePermission bp = mSettings.mPermissions.get(name);
1804 if (bp != null) {
1805 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1806 throw new SecurityException(
1807 "Not allowed to modify non-dynamic permission "
1808 + name);
1809 }
1810 mSettings.mPermissions.remove(name);
1811 mSettings.writeLP();
1812 }
1813 }
1814 }
1815
Dianne Hackborn854060af2009-07-09 18:14:31 -07001816 public boolean isProtectedBroadcast(String actionName) {
1817 synchronized (mPackages) {
1818 return mProtectedBroadcasts.contains(actionName);
1819 }
1820 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 public int checkSignatures(String pkg1, String pkg2) {
1823 synchronized (mPackages) {
1824 PackageParser.Package p1 = mPackages.get(pkg1);
1825 PackageParser.Package p2 = mPackages.get(pkg2);
1826 if (p1 == null || p1.mExtras == null
1827 || p2 == null || p2.mExtras == null) {
1828 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1829 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001830 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 }
1832 }
1833
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001834 public int checkUidSignatures(int uid1, int uid2) {
1835 synchronized (mPackages) {
1836 Signature[] s1;
1837 Signature[] s2;
1838 Object obj = mSettings.getUserIdLP(uid1);
1839 if (obj != null) {
1840 if (obj instanceof SharedUserSetting) {
1841 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1842 } else if (obj instanceof PackageSetting) {
1843 s1 = ((PackageSetting)obj).signatures.mSignatures;
1844 } else {
1845 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1846 }
1847 } else {
1848 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1849 }
1850 obj = mSettings.getUserIdLP(uid2);
1851 if (obj != null) {
1852 if (obj instanceof SharedUserSetting) {
1853 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1854 } else if (obj instanceof PackageSetting) {
1855 s2 = ((PackageSetting)obj).signatures.mSignatures;
1856 } else {
1857 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1858 }
1859 } else {
1860 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1861 }
1862 return checkSignaturesLP(s1, s2);
1863 }
1864 }
1865
1866 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1867 if (s1 == null) {
1868 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1870 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1871 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001872 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1874 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001875 HashSet<Signature> set1 = new HashSet<Signature>();
1876 for (Signature sig : s1) {
1877 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001879 HashSet<Signature> set2 = new HashSet<Signature>();
1880 for (Signature sig : s2) {
1881 set2.add(sig);
1882 }
1883 // Make sure s2 contains all signatures in s1.
1884 if (set1.equals(set2)) {
1885 return PackageManager.SIGNATURE_MATCH;
1886 }
1887 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 }
1889
1890 public String[] getPackagesForUid(int uid) {
1891 synchronized (mPackages) {
1892 Object obj = mSettings.getUserIdLP(uid);
1893 if (obj instanceof SharedUserSetting) {
1894 SharedUserSetting sus = (SharedUserSetting)obj;
1895 final int N = sus.packages.size();
1896 String[] res = new String[N];
1897 Iterator<PackageSetting> it = sus.packages.iterator();
1898 int i=0;
1899 while (it.hasNext()) {
1900 res[i++] = it.next().name;
1901 }
1902 return res;
1903 } else if (obj instanceof PackageSetting) {
1904 PackageSetting ps = (PackageSetting)obj;
1905 return new String[] { ps.name };
1906 }
1907 }
1908 return null;
1909 }
1910
1911 public String getNameForUid(int uid) {
1912 synchronized (mPackages) {
1913 Object obj = mSettings.getUserIdLP(uid);
1914 if (obj instanceof SharedUserSetting) {
1915 SharedUserSetting sus = (SharedUserSetting)obj;
1916 return sus.name + ":" + sus.userId;
1917 } else if (obj instanceof PackageSetting) {
1918 PackageSetting ps = (PackageSetting)obj;
1919 return ps.name;
1920 }
1921 }
1922 return null;
1923 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 public int getUidForSharedUser(String sharedUserName) {
1926 if(sharedUserName == null) {
1927 return -1;
1928 }
1929 synchronized (mPackages) {
1930 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1931 if(suid == null) {
1932 return -1;
1933 }
1934 return suid.userId;
1935 }
1936 }
1937
1938 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1939 int flags) {
1940 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001941 return chooseBestActivity(intent, resolvedType, flags, query);
1942 }
1943
Mihai Predaeae850c2009-05-13 10:13:48 +02001944 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1945 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 if (query != null) {
1947 final int N = query.size();
1948 if (N == 1) {
1949 return query.get(0);
1950 } else if (N > 1) {
1951 // If there is more than one activity with the same priority,
1952 // then let the user decide between them.
1953 ResolveInfo r0 = query.get(0);
1954 ResolveInfo r1 = query.get(1);
1955 if (false) {
1956 System.out.println(r0.activityInfo.name +
1957 "=" + r0.priority + " vs " +
1958 r1.activityInfo.name +
1959 "=" + r1.priority);
1960 }
1961 // If the first activity has a higher priority, or a different
1962 // default, then it is always desireable to pick it.
1963 if (r0.priority != r1.priority
1964 || r0.preferredOrder != r1.preferredOrder
1965 || r0.isDefault != r1.isDefault) {
1966 return query.get(0);
1967 }
1968 // If we have saved a preference for a preferred activity for
1969 // this Intent, use that.
1970 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1971 flags, query, r0.priority);
1972 if (ri != null) {
1973 return ri;
1974 }
1975 return mResolveInfo;
1976 }
1977 }
1978 return null;
1979 }
1980
1981 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1982 int flags, List<ResolveInfo> query, int priority) {
1983 synchronized (mPackages) {
1984 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1985 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001986 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1988 if (prefs != null && prefs.size() > 0) {
1989 // First figure out how good the original match set is.
1990 // We will only allow preferred activities that came
1991 // from the same match quality.
1992 int match = 0;
1993 final int N = query.size();
1994 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1995 for (int j=0; j<N; j++) {
1996 ResolveInfo ri = query.get(j);
1997 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1998 + ": 0x" + Integer.toHexString(match));
1999 if (ri.match > match) match = ri.match;
2000 }
2001 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2002 + Integer.toHexString(match));
2003 match &= IntentFilter.MATCH_CATEGORY_MASK;
2004 final int M = prefs.size();
2005 for (int i=0; i<M; i++) {
2006 PreferredActivity pa = prefs.get(i);
2007 if (pa.mMatch != match) {
2008 continue;
2009 }
2010 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2011 if (DEBUG_PREFERRED) {
2012 Log.v(TAG, "Got preferred activity:");
2013 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
2014 }
2015 if (ai != null) {
2016 for (int j=0; j<N; j++) {
2017 ResolveInfo ri = query.get(j);
2018 if (!ri.activityInfo.applicationInfo.packageName
2019 .equals(ai.applicationInfo.packageName)) {
2020 continue;
2021 }
2022 if (!ri.activityInfo.name.equals(ai.name)) {
2023 continue;
2024 }
2025
2026 // Okay we found a previously set preferred app.
2027 // If the result set is different from when this
2028 // was created, we need to clear it and re-ask the
2029 // user their preference.
2030 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002031 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 + intent + " type " + resolvedType);
2033 mSettings.mPreferredActivities.removeFilter(pa);
2034 return null;
2035 }
2036
2037 // Yay!
2038 return ri;
2039 }
2040 }
2041 }
2042 }
2043 }
2044 return null;
2045 }
2046
2047 public List<ResolveInfo> queryIntentActivities(Intent intent,
2048 String resolvedType, int flags) {
2049 ComponentName comp = intent.getComponent();
2050 if (comp != null) {
2051 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2052 ActivityInfo ai = getActivityInfo(comp, flags);
2053 if (ai != null) {
2054 ResolveInfo ri = new ResolveInfo();
2055 ri.activityInfo = ai;
2056 list.add(ri);
2057 }
2058 return list;
2059 }
2060
2061 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002062 String pkgName = intent.getPackage();
2063 if (pkgName == null) {
2064 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2065 resolvedType, flags);
2066 }
2067 PackageParser.Package pkg = mPackages.get(pkgName);
2068 if (pkg != null) {
2069 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2070 resolvedType, flags, pkg.activities);
2071 }
2072 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002073 }
2074 }
2075
2076 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2077 Intent[] specifics, String[] specificTypes, Intent intent,
2078 String resolvedType, int flags) {
2079 final String resultsAction = intent.getAction();
2080
2081 List<ResolveInfo> results = queryIntentActivities(
2082 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2083 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2084
2085 int specificsPos = 0;
2086 int N;
2087
2088 // todo: note that the algorithm used here is O(N^2). This
2089 // isn't a problem in our current environment, but if we start running
2090 // into situations where we have more than 5 or 10 matches then this
2091 // should probably be changed to something smarter...
2092
2093 // First we go through and resolve each of the specific items
2094 // that were supplied, taking care of removing any corresponding
2095 // duplicate items in the generic resolve list.
2096 if (specifics != null) {
2097 for (int i=0; i<specifics.length; i++) {
2098 final Intent sintent = specifics[i];
2099 if (sintent == null) {
2100 continue;
2101 }
2102
2103 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2104 String action = sintent.getAction();
2105 if (resultsAction != null && resultsAction.equals(action)) {
2106 // If this action was explicitly requested, then don't
2107 // remove things that have it.
2108 action = null;
2109 }
2110 ComponentName comp = sintent.getComponent();
2111 ResolveInfo ri = null;
2112 ActivityInfo ai = null;
2113 if (comp == null) {
2114 ri = resolveIntent(
2115 sintent,
2116 specificTypes != null ? specificTypes[i] : null,
2117 flags);
2118 if (ri == null) {
2119 continue;
2120 }
2121 if (ri == mResolveInfo) {
2122 // ACK! Must do something better with this.
2123 }
2124 ai = ri.activityInfo;
2125 comp = new ComponentName(ai.applicationInfo.packageName,
2126 ai.name);
2127 } else {
2128 ai = getActivityInfo(comp, flags);
2129 if (ai == null) {
2130 continue;
2131 }
2132 }
2133
2134 // Look for any generic query activities that are duplicates
2135 // of this specific one, and remove them from the results.
2136 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2137 N = results.size();
2138 int j;
2139 for (j=specificsPos; j<N; j++) {
2140 ResolveInfo sri = results.get(j);
2141 if ((sri.activityInfo.name.equals(comp.getClassName())
2142 && sri.activityInfo.applicationInfo.packageName.equals(
2143 comp.getPackageName()))
2144 || (action != null && sri.filter.matchAction(action))) {
2145 results.remove(j);
2146 if (Config.LOGV) Log.v(
2147 TAG, "Removing duplicate item from " + j
2148 + " due to specific " + specificsPos);
2149 if (ri == null) {
2150 ri = sri;
2151 }
2152 j--;
2153 N--;
2154 }
2155 }
2156
2157 // Add this specific item to its proper place.
2158 if (ri == null) {
2159 ri = new ResolveInfo();
2160 ri.activityInfo = ai;
2161 }
2162 results.add(specificsPos, ri);
2163 ri.specificIndex = i;
2164 specificsPos++;
2165 }
2166 }
2167
2168 // Now we go through the remaining generic results and remove any
2169 // duplicate actions that are found here.
2170 N = results.size();
2171 for (int i=specificsPos; i<N-1; i++) {
2172 final ResolveInfo rii = results.get(i);
2173 if (rii.filter == null) {
2174 continue;
2175 }
2176
2177 // Iterate over all of the actions of this result's intent
2178 // filter... typically this should be just one.
2179 final Iterator<String> it = rii.filter.actionsIterator();
2180 if (it == null) {
2181 continue;
2182 }
2183 while (it.hasNext()) {
2184 final String action = it.next();
2185 if (resultsAction != null && resultsAction.equals(action)) {
2186 // If this action was explicitly requested, then don't
2187 // remove things that have it.
2188 continue;
2189 }
2190 for (int j=i+1; j<N; j++) {
2191 final ResolveInfo rij = results.get(j);
2192 if (rij.filter != null && rij.filter.hasAction(action)) {
2193 results.remove(j);
2194 if (Config.LOGV) Log.v(
2195 TAG, "Removing duplicate item from " + j
2196 + " due to action " + action + " at " + i);
2197 j--;
2198 N--;
2199 }
2200 }
2201 }
2202
2203 // If the caller didn't request filter information, drop it now
2204 // so we don't have to marshall/unmarshall it.
2205 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2206 rii.filter = null;
2207 }
2208 }
2209
2210 // Filter out the caller activity if so requested.
2211 if (caller != null) {
2212 N = results.size();
2213 for (int i=0; i<N; i++) {
2214 ActivityInfo ainfo = results.get(i).activityInfo;
2215 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2216 && caller.getClassName().equals(ainfo.name)) {
2217 results.remove(i);
2218 break;
2219 }
2220 }
2221 }
2222
2223 // If the caller didn't request filter information,
2224 // drop them now so we don't have to
2225 // marshall/unmarshall it.
2226 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2227 N = results.size();
2228 for (int i=0; i<N; i++) {
2229 results.get(i).filter = null;
2230 }
2231 }
2232
2233 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2234 return results;
2235 }
2236
2237 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2238 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002239 ComponentName comp = intent.getComponent();
2240 if (comp != null) {
2241 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2242 ActivityInfo ai = getReceiverInfo(comp, flags);
2243 if (ai != null) {
2244 ResolveInfo ri = new ResolveInfo();
2245 ri.activityInfo = ai;
2246 list.add(ri);
2247 }
2248 return list;
2249 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002251 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002252 String pkgName = intent.getPackage();
2253 if (pkgName == null) {
2254 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2255 resolvedType, flags);
2256 }
2257 PackageParser.Package pkg = mPackages.get(pkgName);
2258 if (pkg != null) {
2259 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2260 resolvedType, flags, pkg.receivers);
2261 }
2262 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 }
2264 }
2265
2266 public ResolveInfo resolveService(Intent intent, String resolvedType,
2267 int flags) {
2268 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2269 flags);
2270 if (query != null) {
2271 if (query.size() >= 1) {
2272 // If there is more than one service with the same priority,
2273 // just arbitrarily pick the first one.
2274 return query.get(0);
2275 }
2276 }
2277 return null;
2278 }
2279
2280 public List<ResolveInfo> queryIntentServices(Intent intent,
2281 String resolvedType, int flags) {
2282 ComponentName comp = intent.getComponent();
2283 if (comp != null) {
2284 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2285 ServiceInfo si = getServiceInfo(comp, flags);
2286 if (si != null) {
2287 ResolveInfo ri = new ResolveInfo();
2288 ri.serviceInfo = si;
2289 list.add(ri);
2290 }
2291 return list;
2292 }
2293
2294 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002295 String pkgName = intent.getPackage();
2296 if (pkgName == null) {
2297 return (List<ResolveInfo>)mServices.queryIntent(intent,
2298 resolvedType, flags);
2299 }
2300 PackageParser.Package pkg = mPackages.get(pkgName);
2301 if (pkg != null) {
2302 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2303 resolvedType, flags, pkg.services);
2304 }
2305 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002306 }
2307 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002309 public List<PackageInfo> getInstalledPackages(int flags) {
2310 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2311
2312 synchronized (mPackages) {
2313 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2314 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2315 while (i.hasNext()) {
2316 final PackageSetting ps = i.next();
2317 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2318 if(psPkg != null) {
2319 finalList.add(psPkg);
2320 }
2321 }
2322 }
2323 else {
2324 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2325 while (i.hasNext()) {
2326 final PackageParser.Package p = i.next();
2327 if (p.applicationInfo != null) {
2328 PackageInfo pi = generatePackageInfo(p, flags);
2329 if(pi != null) {
2330 finalList.add(pi);
2331 }
2332 }
2333 }
2334 }
2335 }
2336 return finalList;
2337 }
2338
2339 public List<ApplicationInfo> getInstalledApplications(int flags) {
2340 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2341 synchronized(mPackages) {
2342 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2343 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2344 while (i.hasNext()) {
2345 final PackageSetting ps = i.next();
2346 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2347 if(ai != null) {
2348 finalList.add(ai);
2349 }
2350 }
2351 }
2352 else {
2353 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2354 while (i.hasNext()) {
2355 final PackageParser.Package p = i.next();
2356 if (p.applicationInfo != null) {
2357 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2358 if(ai != null) {
2359 finalList.add(ai);
2360 }
2361 }
2362 }
2363 }
2364 }
2365 return finalList;
2366 }
2367
2368 public List<ApplicationInfo> getPersistentApplications(int flags) {
2369 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2370
2371 synchronized (mPackages) {
2372 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2373 while (i.hasNext()) {
2374 PackageParser.Package p = i.next();
2375 if (p.applicationInfo != null
2376 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2377 && (!mSafeMode || (p.applicationInfo.flags
2378 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
Jey2eebf5c2009-11-18 18:37:31 -08002379 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380 }
2381 }
2382 }
2383
2384 return finalList;
2385 }
2386
2387 public ProviderInfo resolveContentProvider(String name, int flags) {
2388 synchronized (mPackages) {
2389 final PackageParser.Provider provider = mProviders.get(name);
2390 return provider != null
2391 && mSettings.isEnabledLP(provider.info, flags)
2392 && (!mSafeMode || (provider.info.applicationInfo.flags
2393 &ApplicationInfo.FLAG_SYSTEM) != 0)
2394 ? PackageParser.generateProviderInfo(provider, flags)
2395 : null;
2396 }
2397 }
2398
Fred Quintana718d8a22009-04-29 17:53:20 -07002399 /**
2400 * @deprecated
2401 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402 public void querySyncProviders(List outNames, List outInfo) {
2403 synchronized (mPackages) {
2404 Iterator<Map.Entry<String, PackageParser.Provider>> i
2405 = mProviders.entrySet().iterator();
2406
2407 while (i.hasNext()) {
2408 Map.Entry<String, PackageParser.Provider> entry = i.next();
2409 PackageParser.Provider p = entry.getValue();
2410
2411 if (p.syncable
2412 && (!mSafeMode || (p.info.applicationInfo.flags
2413 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2414 outNames.add(entry.getKey());
2415 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2416 }
2417 }
2418 }
2419 }
2420
2421 public List<ProviderInfo> queryContentProviders(String processName,
2422 int uid, int flags) {
2423 ArrayList<ProviderInfo> finalList = null;
2424
2425 synchronized (mPackages) {
2426 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2427 while (i.hasNext()) {
2428 PackageParser.Provider p = i.next();
2429 if (p.info.authority != null
2430 && (processName == null ||
2431 (p.info.processName.equals(processName)
2432 && p.info.applicationInfo.uid == uid))
2433 && mSettings.isEnabledLP(p.info, flags)
2434 && (!mSafeMode || (p.info.applicationInfo.flags
2435 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2436 if (finalList == null) {
2437 finalList = new ArrayList<ProviderInfo>(3);
2438 }
2439 finalList.add(PackageParser.generateProviderInfo(p,
2440 flags));
2441 }
2442 }
2443 }
2444
2445 if (finalList != null) {
2446 Collections.sort(finalList, mProviderInitOrderSorter);
2447 }
2448
2449 return finalList;
2450 }
2451
2452 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2453 int flags) {
2454 synchronized (mPackages) {
2455 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2456 return PackageParser.generateInstrumentationInfo(i, flags);
2457 }
2458 }
2459
2460 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2461 int flags) {
2462 ArrayList<InstrumentationInfo> finalList =
2463 new ArrayList<InstrumentationInfo>();
2464
2465 synchronized (mPackages) {
2466 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2467 while (i.hasNext()) {
2468 PackageParser.Instrumentation p = i.next();
2469 if (targetPackage == null
2470 || targetPackage.equals(p.info.targetPackage)) {
2471 finalList.add(PackageParser.generateInstrumentationInfo(p,
2472 flags));
2473 }
2474 }
2475 }
2476
2477 return finalList;
2478 }
2479
2480 private void scanDirLI(File dir, int flags, int scanMode) {
2481 Log.d(TAG, "Scanning app dir " + dir);
2482
2483 String[] files = dir.list();
2484
2485 int i;
2486 for (i=0; i<files.length; i++) {
2487 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002488 if (!isPackageFilename(files[i])) {
2489 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002490 continue;
2491 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002492 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002494 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002495 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2496 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002497 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002498 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002499 file.delete();
2500 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 }
2502 }
2503
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002504 private static File getSettingsProblemFile() {
2505 File dataDir = Environment.getDataDirectory();
2506 File systemDir = new File(dataDir, "system");
2507 File fname = new File(systemDir, "uiderrors.txt");
2508 return fname;
2509 }
2510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002511 private static void reportSettingsProblem(int priority, String msg) {
2512 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002513 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 FileOutputStream out = new FileOutputStream(fname, true);
2515 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002516 SimpleDateFormat formatter = new SimpleDateFormat();
2517 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2518 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 pw.close();
2520 FileUtils.setPermissions(
2521 fname.toString(),
2522 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2523 -1, -1);
2524 } catch (java.io.IOException e) {
2525 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002526 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 }
2528
2529 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2530 PackageParser.Package pkg, File srcFile, int parseFlags) {
2531 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002532 if (ps != null
2533 && ps.codePath.equals(srcFile)
2534 && ps.getTimeStamp() == srcFile.lastModified()) {
2535 if (ps.signatures.mSignatures != null
2536 && ps.signatures.mSignatures.length != 0) {
2537 // Optimization: reuse the existing cached certificates
2538 // if the package appears to be unchanged.
2539 pkg.mSignatures = ps.signatures.mSignatures;
2540 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 }
Jeff Browne7600722010-04-07 18:28:23 -07002542
2543 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002544 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002545 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2546 }
2547
2548 if (!pp.collectCertificates(pkg, parseFlags)) {
2549 mLastScanError = pp.getParseError();
2550 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 }
2552 }
2553 return true;
2554 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 /*
2557 * Scan a package and return the newly parsed package.
2558 * Returns null in case of errors and the error code is stored in mLastScanError
2559 */
2560 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002561 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002563 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002565 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002568 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 if (pkg == null) {
2570 mLastScanError = pp.getParseError();
2571 return null;
2572 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002573 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 PackageSetting updatedPkg;
2575 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002576 // Look to see if we already know about this package.
2577 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002578 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002579 // This package has been renamed to its original name. Let's
2580 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002581 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002582 }
2583 // If there was no original package, see one for the real package name.
2584 if (ps == null) {
2585 ps = mSettings.peekPackageLP(pkg.packageName);
2586 }
2587 // Check to see if this package could be hiding/updating a system
2588 // package. Must look for it either under the original or real
2589 // package name depending on our state.
2590 updatedPkg = mSettings.mDisabledSysPackages.get(
2591 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002593 // First check if this is a system package that may involve an update
2594 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2595 if (!ps.codePath.equals(scanFile)) {
2596 // The path has changed from what was last scanned... check the
2597 // version of the new path against what we have stored to determine
2598 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002599 if (pkg.mVersionCode < ps.versionCode) {
2600 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002601 // Ignore entry. Skip it.
2602 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2603 + "ignored: updated version " + ps.versionCode
2604 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002605 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2606 return null;
2607 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002608 // The current app on the system partion is better than
2609 // what we have updated to on the data partition; switch
2610 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002611 // At this point, its safely assumed that package installation for
2612 // apps in system partition will go through. If not there won't be a working
2613 // version of the app
2614 synchronized (mPackages) {
2615 // Just remove the loaded entries from package lists.
2616 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002617 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002618 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002619 + "reverting from " + ps.codePathString
2620 + ": new version " + pkg.mVersionCode
2621 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002622 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2623 args.cleanUpResourcesLI();
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07002624 removeNativeBinariesLI(pkg);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002625 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627 }
2628 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002629 if (updatedPkg != null) {
2630 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2631 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2632 }
2633 // Verify certificates against what was last scanned
2634 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002635 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002636 return null;
2637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638 // The apk is forward locked (not public) if its code and resources
2639 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002640 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002642 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002643 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002644
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002645 String codePath = null;
2646 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002647 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2648 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002649 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002650 } else {
2651 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002652 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002653 }
2654 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002655 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002656 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002657 codePath = pkg.mScanPath;
2658 // Set application objects path explicitly.
2659 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002661 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 }
2663
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002664 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2665 String destCodePath, String destResPath) {
2666 pkg.mPath = pkg.mScanPath = destCodePath;
2667 pkg.applicationInfo.sourceDir = destCodePath;
2668 pkg.applicationInfo.publicSourceDir = destResPath;
2669 }
2670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 private static String fixProcessName(String defProcessName,
2672 String processName, int uid) {
2673 if (processName == null) {
2674 return defProcessName;
2675 }
2676 return processName;
2677 }
2678
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002679 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002680 PackageParser.Package pkg) {
2681 if (pkgSetting.signatures.mSignatures != null) {
2682 // Already existing package. Make sure signatures match
2683 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2684 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002685 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002686 + " signatures do not match the previously installed version; ignoring!");
2687 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 return false;
2689 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002690 }
2691 // Check for shared user signatures
2692 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2693 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2694 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2695 Slog.e(TAG, "Package " + pkg.packageName
2696 + " has no signatures that match those in shared user "
2697 + pkgSetting.sharedUser.name + "; ignoring!");
2698 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2699 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701 }
2702 return true;
2703 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002704
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002705 public boolean performDexOpt(String packageName) {
2706 if (!mNoDexOpt) {
2707 return false;
2708 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002709
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002710 PackageParser.Package p;
2711 synchronized (mPackages) {
2712 p = mPackages.get(packageName);
2713 if (p == null || p.mDidDexOpt) {
2714 return false;
2715 }
2716 }
2717 synchronized (mInstallLock) {
2718 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2719 }
2720 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002721
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002722 static final int DEX_OPT_SKIPPED = 0;
2723 static final int DEX_OPT_PERFORMED = 1;
2724 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002725
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002726 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2727 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002728 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002729 String path = pkg.mScanPath;
2730 int ret = 0;
2731 try {
2732 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002733 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002734 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002735 pkg.mDidDexOpt = true;
2736 performed = true;
2737 }
2738 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002739 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002740 ret = -1;
2741 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002742 Slog.w(TAG, "IOException reading apk: " + path, e);
2743 ret = -1;
2744 } catch (dalvik.system.StaleDexCacheError e) {
2745 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2746 ret = -1;
2747 } catch (Exception e) {
2748 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002749 ret = -1;
2750 }
2751 if (ret < 0) {
2752 //error from installer
2753 return DEX_OPT_FAILED;
2754 }
2755 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002756
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002757 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2758 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002759
2760 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2761 return Environment.isEncryptedFilesystemEnabled() &&
2762 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2763 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002764
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002765 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2766 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002767 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002768 + " to " + newPkg.packageName
2769 + ": old package not in system partition");
2770 return false;
2771 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002772 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002773 + " to " + newPkg.packageName
2774 + ": old package still exists");
2775 return false;
2776 }
2777 return true;
2778 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002779
2780 private File getDataPathForPackage(PackageParser.Package pkg) {
2781 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2782 File dataPath;
2783 if (useEncryptedFSDir) {
2784 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2785 } else {
2786 dataPath = new File(mAppDataDir, pkg.packageName);
2787 }
2788 return dataPath;
2789 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002790
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002791 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2792 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002793 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002794 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2795 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002796 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002797 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002798 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2799 return null;
2800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 mScanningPath = scanFile;
2802 if (pkg == null) {
2803 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2804 return null;
2805 }
2806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002807 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2808 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2809 }
2810
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002811 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 synchronized (mPackages) {
2813 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002814 Slog.w(TAG, "*************************************************");
2815 Slog.w(TAG, "Core android package being redefined. Skipping.");
2816 Slog.w(TAG, " file=" + mScanningPath);
2817 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2819 return null;
2820 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 // Set up information for our fall-back user intent resolution
2823 // activity.
2824 mPlatformPackage = pkg;
2825 pkg.mVersionCode = mSdkVersion;
2826 mAndroidApplication = pkg.applicationInfo;
2827 mResolveActivity.applicationInfo = mAndroidApplication;
2828 mResolveActivity.name = ResolverActivity.class.getName();
2829 mResolveActivity.packageName = mAndroidApplication.packageName;
2830 mResolveActivity.processName = mAndroidApplication.processName;
2831 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2832 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2833 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2834 mResolveActivity.exported = true;
2835 mResolveActivity.enabled = true;
2836 mResolveInfo.activityInfo = mResolveActivity;
2837 mResolveInfo.priority = 0;
2838 mResolveInfo.preferredOrder = 0;
2839 mResolveInfo.match = 0;
2840 mResolveComponentName = new ComponentName(
2841 mAndroidApplication.packageName, mResolveActivity.name);
2842 }
2843 }
2844
2845 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002846 TAG, "Scanning package " + pkg.packageName);
2847 if (mPackages.containsKey(pkg.packageName)
2848 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002849 Slog.w(TAG, "*************************************************");
2850 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002852 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2854 return null;
2855 }
2856
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002857 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002858 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2859 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 SharedUserSetting suid = null;
2862 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002863
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002864 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2865 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002866 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002867 pkg.mRealPackage = null;
2868 pkg.mAdoptPermissions = null;
2869 }
2870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002871 synchronized (mPackages) {
2872 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002873 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2874 if (mTmpSharedLibraries == null ||
2875 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2876 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2877 }
2878 int num = 0;
2879 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2880 for (int i=0; i<N; i++) {
2881 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002883 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002885 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2887 return null;
2888 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002889 mTmpSharedLibraries[num] = file;
2890 num++;
2891 }
2892 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2893 for (int i=0; i<N; i++) {
2894 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2895 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002896 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002897 + " desires unavailable shared library "
2898 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2899 } else {
2900 mTmpSharedLibraries[num] = file;
2901 num++;
2902 }
2903 }
2904 if (num > 0) {
2905 pkg.usesLibraryFiles = new String[num];
2906 System.arraycopy(mTmpSharedLibraries, 0,
2907 pkg.usesLibraryFiles, 0, num);
2908 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002909
Dianne Hackborn49237342009-08-27 20:08:01 -07002910 if (pkg.reqFeatures != null) {
2911 N = pkg.reqFeatures.size();
2912 for (int i=0; i<N; i++) {
2913 FeatureInfo fi = pkg.reqFeatures.get(i);
2914 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2915 // Don't care.
2916 continue;
2917 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002918
Dianne Hackborn49237342009-08-27 20:08:01 -07002919 if (fi.name != null) {
2920 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002921 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002922 + " requires unavailable feature "
2923 + fi.name + "; failing!");
2924 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2925 return null;
2926 }
2927 }
2928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 }
2930 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 if (pkg.mSharedUserId != null) {
2933 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2934 pkg.applicationInfo.flags, true);
2935 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002936 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 + " for shared user failed");
2938 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2939 return null;
2940 }
2941 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2942 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2943 + suid.userId + "): packages=" + suid.packages);
2944 }
2945 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002946
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002947 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002948 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002949 Log.w(TAG, "WAITING FOR DEBUGGER");
2950 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002951 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2952 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002953 }
2954 }
2955
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002956 // Check if we are renaming from an original package name.
2957 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002958 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002959 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002960 // This package may need to be renamed to a previously
2961 // installed name. Let's check on that...
2962 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002963 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002964 // This package had originally been installed as the
2965 // original name, and we have already taken care of
2966 // transitioning to the new one. Just update the new
2967 // one to continue using the old name.
2968 realName = pkg.mRealPackage;
2969 if (!pkg.packageName.equals(renamed)) {
2970 // Callers into this function may have already taken
2971 // care of renaming the package; only do it here if
2972 // it is not already done.
2973 pkg.setPackageName(renamed);
2974 }
2975
Dianne Hackbornc1552392010-03-03 16:19:01 -08002976 } else {
2977 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2978 if ((origPackage=mSettings.peekPackageLP(
2979 pkg.mOriginalPackages.get(i))) != null) {
2980 // We do have the package already installed under its
2981 // original name... should we use it?
2982 if (!verifyPackageUpdate(origPackage, pkg)) {
2983 // New package is not compatible with original.
2984 origPackage = null;
2985 continue;
2986 } else if (origPackage.sharedUser != null) {
2987 // Make sure uid is compatible between packages.
2988 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002989 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002990 + " to " + pkg.packageName + ": old uid "
2991 + origPackage.sharedUser.name
2992 + " differs from " + pkg.mSharedUserId);
2993 origPackage = null;
2994 continue;
2995 }
2996 } else {
2997 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2998 + pkg.packageName + " to old name " + origPackage.name);
2999 }
3000 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003001 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003002 }
3003 }
3004 }
3005
3006 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003007 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003008 + " was transferred to another, but its .apk remains");
3009 }
3010
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003011 // Just create the setting, don't add it yet. For already existing packages
3012 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003013 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003014 destResourceFile, pkg.applicationInfo.flags, true, false);
3015 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003016 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3018 return null;
3019 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003020
3021 if (pkgSetting.origPackage != null) {
3022 // If we are first transitioning from an original package,
3023 // fix up the new package's name now. We need to do this after
3024 // looking up the package under its new name, so getPackageLP
3025 // can take care of fiddling things correctly.
3026 pkg.setPackageName(origPackage.name);
3027
3028 // File a report about this.
3029 String msg = "New package " + pkgSetting.realName
3030 + " renamed to replace old package " + pkgSetting.name;
3031 reportSettingsProblem(Log.WARN, msg);
3032
3033 // Make a note of it.
3034 mTransferedPackages.add(origPackage.name);
3035
3036 // No longer need to retain this.
3037 pkgSetting.origPackage = null;
3038 }
3039
3040 if (realName != null) {
3041 // Make a note of it.
3042 mTransferedPackages.add(pkg.packageName);
3043 }
3044
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003045 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003046 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3047 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 pkg.applicationInfo.uid = pkgSetting.userId;
3050 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003051
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003052 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003053 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 return null;
3055 }
3056 // The signature has changed, but this package is in the system
3057 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003058 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003059 // However... if this package is part of a shared user, but it
3060 // doesn't match the signature of the shared user, let's fail.
3061 // What this means is that you can't change the signatures
3062 // associated with an overall shared user, which doesn't seem all
3063 // that unreasonable.
3064 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003065 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3066 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3067 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003068 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3069 return null;
3070 }
3071 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003072 // File a report about this.
3073 String msg = "System package " + pkg.packageName
3074 + " signature changed; retaining data.";
3075 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003077
The Android Open Source Project10592532009-03-18 17:39:46 -07003078 // Verify that this new package doesn't have any content providers
3079 // that conflict with existing packages. Only do this if the
3080 // package isn't already installed, since we don't want to break
3081 // things that are installed.
3082 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3083 int N = pkg.providers.size();
3084 int i;
3085 for (i=0; i<N; i++) {
3086 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003087 if (p.info.authority != null) {
3088 String names[] = p.info.authority.split(";");
3089 for (int j = 0; j < names.length; j++) {
3090 if (mProviders.containsKey(names[j])) {
3091 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003092 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003093 " (in package " + pkg.applicationInfo.packageName +
3094 ") is already used by "
3095 + ((other != null && other.getComponentName() != null)
3096 ? other.getComponentName().getPackageName() : "?"));
3097 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3098 return null;
3099 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003100 }
3101 }
3102 }
3103 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104 }
3105
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003106 final String pkgName = pkg.packageName;
3107
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003108 if (pkg.mAdoptPermissions != null) {
3109 // This package wants to adopt ownership of permissions from
3110 // another package.
3111 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3112 String origName = pkg.mAdoptPermissions.get(i);
3113 PackageSetting orig = mSettings.peekPackageLP(origName);
3114 if (orig != null) {
3115 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003116 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003117 + origName + " to " + pkg.packageName);
3118 mSettings.transferPermissions(origName, pkg.packageName);
3119 }
3120 }
3121 }
3122 }
3123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003124 long scanFileTime = scanFile.lastModified();
3125 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3126 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3127 pkg.applicationInfo.processName = fixProcessName(
3128 pkg.applicationInfo.packageName,
3129 pkg.applicationInfo.processName,
3130 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003131
3132 File dataPath;
3133 if (mPlatformPackage == pkg) {
3134 // The system package is special.
3135 dataPath = new File (Environment.getDataDirectory(), "system");
3136 pkg.applicationInfo.dataDir = dataPath.getPath();
3137 } else {
3138 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003139 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003140 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003141
3142 boolean uidError = false;
3143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003144 if (dataPath.exists()) {
3145 mOutPermissions[1] = 0;
3146 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3147 if (mOutPermissions[1] == pkg.applicationInfo.uid
3148 || !Process.supportsProcesses()) {
3149 pkg.applicationInfo.dataDir = dataPath.getPath();
3150 } else {
3151 boolean recovered = false;
3152 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3153 // If this is a system app, we can at least delete its
3154 // current data so the application will still work.
3155 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003156 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003157 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 // Old data gone!
3159 String msg = "System package " + pkg.packageName
3160 + " has changed from uid: "
3161 + mOutPermissions[1] + " to "
3162 + pkg.applicationInfo.uid + "; old data erased";
3163 reportSettingsProblem(Log.WARN, msg);
3164 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003166 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003167 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003168 pkg.applicationInfo.uid);
3169 if (ret == -1) {
3170 // Ack should not happen!
3171 msg = "System package " + pkg.packageName
3172 + " could not have data directory re-created after delete.";
3173 reportSettingsProblem(Log.WARN, msg);
3174 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3175 return null;
3176 }
3177 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 if (!recovered) {
3180 mHasSystemUidErrors = true;
3181 }
3182 }
3183 if (!recovered) {
3184 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3185 + pkg.applicationInfo.uid + "/fs_"
3186 + mOutPermissions[1];
3187 String msg = "Package " + pkg.packageName
3188 + " has mismatched uid: "
3189 + mOutPermissions[1] + " on disk, "
3190 + pkg.applicationInfo.uid + " in settings";
3191 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003192 mSettings.mReadMessages.append(msg);
3193 mSettings.mReadMessages.append('\n');
3194 uidError = true;
3195 if (!pkgSetting.uidError) {
3196 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 }
3199 }
3200 }
3201 pkg.applicationInfo.dataDir = dataPath.getPath();
3202 } else {
3203 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3204 Log.v(TAG, "Want this data dir: " + dataPath);
3205 //invoke installer to do the actual installation
3206 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003207 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 pkg.applicationInfo.uid);
3209 if(ret < 0) {
3210 // Error from installer
3211 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3212 return null;
3213 }
3214 } else {
3215 dataPath.mkdirs();
3216 if (dataPath.exists()) {
3217 FileUtils.setPermissions(
3218 dataPath.toString(),
3219 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3220 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3221 }
3222 }
3223 if (dataPath.exists()) {
3224 pkg.applicationInfo.dataDir = dataPath.getPath();
3225 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003226 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003227 pkg.applicationInfo.dataDir = null;
3228 }
3229 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003230
3231 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003232 }
3233
3234 // Perform shared library installation and dex validation and
3235 // optimization, if this is not a system app.
3236 if (mInstaller != null) {
3237 String path = scanFile.getPath();
3238 if (scanFileNewer) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003239 // Note: We don't want to unpack the native binaries for
3240 // system applications, unless they have been updated
3241 // (the binaries are already under /system/lib).
3242 //
3243 // In other words, we're going to unpack the binaries
3244 // only for non-system apps and system app upgrades.
3245 //
3246 int flags = pkg.applicationInfo.flags;
3247 if ((flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
3248 (flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3249 Log.i(TAG, path + " changed; unpacking");
3250 int err = cachePackageSharedLibsLI(pkg, scanFile);
3251 if (err != PackageManager.INSTALL_SUCCEEDED) {
3252 mLastScanError = err;
3253 return null;
3254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 }
3256 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003257 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003258
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003259 if ((scanMode&SCAN_NO_DEX) == 0) {
3260 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3262 return null;
3263 }
3264 }
3265 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267 if (mFactoryTest && pkg.requestedPermissions.contains(
3268 android.Manifest.permission.FACTORY_TEST)) {
3269 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3270 }
3271
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003272 // Request the ActivityManager to kill the process(only for existing packages)
3273 // so that we do not end up in a confused state while the user is still using the older
3274 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003275 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003276 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003277 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003278 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003280 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003281 // We don't expect installation to fail beyond this point,
3282 if ((scanMode&SCAN_MONITOR) != 0) {
3283 mAppDirs.put(pkg.mPath, pkg);
3284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003286 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003288 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003289 // Make sure we don't accidentally delete its data.
3290 mSettings.mPackagesToBeCleaned.remove(pkgName);
3291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292 int N = pkg.providers.size();
3293 StringBuilder r = null;
3294 int i;
3295 for (i=0; i<N; i++) {
3296 PackageParser.Provider p = pkg.providers.get(i);
3297 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3298 p.info.processName, pkg.applicationInfo.uid);
3299 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3300 p.info.name), p);
3301 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003302 if (p.info.authority != null) {
3303 String names[] = p.info.authority.split(";");
3304 p.info.authority = null;
3305 for (int j = 0; j < names.length; j++) {
3306 if (j == 1 && p.syncable) {
3307 // We only want the first authority for a provider to possibly be
3308 // syncable, so if we already added this provider using a different
3309 // authority clear the syncable flag. We copy the provider before
3310 // changing it because the mProviders object contains a reference
3311 // to a provider that we don't want to change.
3312 // Only do this for the second authority since the resulting provider
3313 // object can be the same for all future authorities for this provider.
3314 p = new PackageParser.Provider(p);
3315 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003317 if (!mProviders.containsKey(names[j])) {
3318 mProviders.put(names[j], p);
3319 if (p.info.authority == null) {
3320 p.info.authority = names[j];
3321 } else {
3322 p.info.authority = p.info.authority + ";" + names[j];
3323 }
3324 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3325 Log.d(TAG, "Registered content provider: " + names[j] +
3326 ", className = " + p.info.name +
3327 ", isSyncable = " + p.info.isSyncable);
3328 } else {
3329 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003330 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003331 " (in package " + pkg.applicationInfo.packageName +
3332 "): name already used by "
3333 + ((other != null && other.getComponentName() != null)
3334 ? other.getComponentName().getPackageName() : "?"));
3335 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003336 }
3337 }
3338 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3339 if (r == null) {
3340 r = new StringBuilder(256);
3341 } else {
3342 r.append(' ');
3343 }
3344 r.append(p.info.name);
3345 }
3346 }
3347 if (r != null) {
3348 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3349 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 N = pkg.services.size();
3352 r = null;
3353 for (i=0; i<N; i++) {
3354 PackageParser.Service s = pkg.services.get(i);
3355 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3356 s.info.processName, pkg.applicationInfo.uid);
3357 mServices.addService(s);
3358 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3359 if (r == null) {
3360 r = new StringBuilder(256);
3361 } else {
3362 r.append(' ');
3363 }
3364 r.append(s.info.name);
3365 }
3366 }
3367 if (r != null) {
3368 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3369 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003371 N = pkg.receivers.size();
3372 r = null;
3373 for (i=0; i<N; i++) {
3374 PackageParser.Activity a = pkg.receivers.get(i);
3375 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3376 a.info.processName, pkg.applicationInfo.uid);
3377 mReceivers.addActivity(a, "receiver");
3378 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3379 if (r == null) {
3380 r = new StringBuilder(256);
3381 } else {
3382 r.append(' ');
3383 }
3384 r.append(a.info.name);
3385 }
3386 }
3387 if (r != null) {
3388 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3389 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003391 N = pkg.activities.size();
3392 r = null;
3393 for (i=0; i<N; i++) {
3394 PackageParser.Activity a = pkg.activities.get(i);
3395 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3396 a.info.processName, pkg.applicationInfo.uid);
3397 mActivities.addActivity(a, "activity");
3398 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3399 if (r == null) {
3400 r = new StringBuilder(256);
3401 } else {
3402 r.append(' ');
3403 }
3404 r.append(a.info.name);
3405 }
3406 }
3407 if (r != null) {
3408 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3409 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411 N = pkg.permissionGroups.size();
3412 r = null;
3413 for (i=0; i<N; i++) {
3414 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3415 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3416 if (cur == null) {
3417 mPermissionGroups.put(pg.info.name, pg);
3418 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3419 if (r == null) {
3420 r = new StringBuilder(256);
3421 } else {
3422 r.append(' ');
3423 }
3424 r.append(pg.info.name);
3425 }
3426 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003427 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 + pg.info.packageName + " ignored: original from "
3429 + cur.info.packageName);
3430 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3431 if (r == null) {
3432 r = new StringBuilder(256);
3433 } else {
3434 r.append(' ');
3435 }
3436 r.append("DUP:");
3437 r.append(pg.info.name);
3438 }
3439 }
3440 }
3441 if (r != null) {
3442 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3443 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003445 N = pkg.permissions.size();
3446 r = null;
3447 for (i=0; i<N; i++) {
3448 PackageParser.Permission p = pkg.permissions.get(i);
3449 HashMap<String, BasePermission> permissionMap =
3450 p.tree ? mSettings.mPermissionTrees
3451 : mSettings.mPermissions;
3452 p.group = mPermissionGroups.get(p.info.group);
3453 if (p.info.group == null || p.group != null) {
3454 BasePermission bp = permissionMap.get(p.info.name);
3455 if (bp == null) {
3456 bp = new BasePermission(p.info.name, p.info.packageName,
3457 BasePermission.TYPE_NORMAL);
3458 permissionMap.put(p.info.name, bp);
3459 }
3460 if (bp.perm == null) {
3461 if (bp.sourcePackage == null
3462 || bp.sourcePackage.equals(p.info.packageName)) {
3463 BasePermission tree = findPermissionTreeLP(p.info.name);
3464 if (tree == null
3465 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003466 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003467 bp.perm = p;
3468 bp.uid = pkg.applicationInfo.uid;
3469 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3470 if (r == null) {
3471 r = new StringBuilder(256);
3472 } else {
3473 r.append(' ');
3474 }
3475 r.append(p.info.name);
3476 }
3477 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003478 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 + p.info.packageName + " ignored: base tree "
3480 + tree.name + " is from package "
3481 + tree.sourcePackage);
3482 }
3483 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003484 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 + p.info.packageName + " ignored: original from "
3486 + bp.sourcePackage);
3487 }
3488 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3489 if (r == null) {
3490 r = new StringBuilder(256);
3491 } else {
3492 r.append(' ');
3493 }
3494 r.append("DUP:");
3495 r.append(p.info.name);
3496 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003497 if (bp.perm == p) {
3498 bp.protectionLevel = p.info.protectionLevel;
3499 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003501 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003502 + p.info.packageName + " ignored: no group "
3503 + p.group);
3504 }
3505 }
3506 if (r != null) {
3507 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3508 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003510 N = pkg.instrumentation.size();
3511 r = null;
3512 for (i=0; i<N; i++) {
3513 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3514 a.info.packageName = pkg.applicationInfo.packageName;
3515 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3516 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3517 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003518 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003519 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3520 if (r == null) {
3521 r = new StringBuilder(256);
3522 } else {
3523 r.append(' ');
3524 }
3525 r.append(a.info.name);
3526 }
3527 }
3528 if (r != null) {
3529 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3530 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003531
Dianne Hackborn854060af2009-07-09 18:14:31 -07003532 if (pkg.protectedBroadcasts != null) {
3533 N = pkg.protectedBroadcasts.size();
3534 for (i=0; i<N; i++) {
3535 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3536 }
3537 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 pkgSetting.setTimeStamp(scanFileTime);
3540 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003542 return pkg;
3543 }
3544
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003545 private void killApplication(String pkgName, int uid) {
3546 // Request the ActivityManager to kill the process(only for existing packages)
3547 // so that we do not end up in a confused state while the user is still using the older
3548 // version of the application while the new one gets installed.
3549 IActivityManager am = ActivityManagerNative.getDefault();
3550 if (am != null) {
3551 try {
3552 am.killApplicationWithUid(pkgName, uid);
3553 } catch (RemoteException e) {
3554 }
3555 }
3556 }
3557
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003558 // The following constants are returned by cachePackageSharedLibsForAbiLI
3559 // to indicate if native shared libraries were found in the package.
3560 // Values are:
3561 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3562 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3563 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3564 // in package (and not installed)
3565 //
3566 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3567 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3568 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003569
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003570 // Return the path of the directory that will contain the native binaries
3571 // of a given installed package. This is relative to the data path.
3572 //
3573 private static File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3574 return new File(pkg.applicationInfo.dataDir + "/lib");
3575 }
3576
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003577 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3578 // and automatically copy them to /data/data/<appname>/lib if present.
3579 //
3580 // NOTE: this method may throw an IOException if the library cannot
3581 // be copied to its final destination, e.g. if there isn't enough
3582 // room left on the data partition, or a ZipException if the package
3583 // file is malformed.
3584 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003585 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003586 File scanFile, String cpuAbi) throws IOException, ZipException {
3587 File sharedLibraryDir = getNativeBinaryDirForPackage(pkg);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003588 final String apkLib = "lib/";
3589 final int apkLibLen = apkLib.length();
3590 final int cpuAbiLen = cpuAbi.length();
3591 final String libPrefix = "lib";
3592 final int libPrefixLen = libPrefix.length();
3593 final String libSuffix = ".so";
3594 final int libSuffixLen = libSuffix.length();
3595 boolean hasNativeLibraries = false;
3596 boolean installedNativeLibraries = false;
3597
3598 // the minimum length of a valid native shared library of the form
3599 // lib/<something>/lib<name>.so.
3600 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3601
3602 ZipFile zipFile = new ZipFile(scanFile);
3603 Enumeration<ZipEntry> entries =
3604 (Enumeration<ZipEntry>) zipFile.entries();
3605
3606 while (entries.hasMoreElements()) {
3607 ZipEntry entry = entries.nextElement();
3608 // skip directories
3609 if (entry.isDirectory()) {
3610 continue;
3611 }
3612 String entryName = entry.getName();
3613
3614 // check that the entry looks like lib/<something>/lib<name>.so
3615 // here, but don't check the ABI just yet.
3616 //
3617 // - must be sufficiently long
3618 // - must end with libSuffix, i.e. ".so"
3619 // - must start with apkLib, i.e. "lib/"
3620 if (entryName.length() < minEntryLen ||
3621 !entryName.endsWith(libSuffix) ||
3622 !entryName.startsWith(apkLib) ) {
3623 continue;
3624 }
3625
3626 // file name must start with libPrefix, i.e. "lib"
3627 int lastSlash = entryName.lastIndexOf('/');
3628
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003629 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003630 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3631 continue;
3632 }
3633
3634 hasNativeLibraries = true;
3635
3636 // check the cpuAbi now, between lib/ and /lib<name>.so
3637 //
3638 if (lastSlash != apkLibLen + cpuAbiLen ||
3639 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3640 continue;
3641
3642 // extract the library file name, ensure it doesn't contain
3643 // weird characters. we're guaranteed here that it doesn't contain
3644 // a directory separator though.
3645 String libFileName = entryName.substring(lastSlash+1);
3646 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3647 continue;
3648 }
3649
3650 installedNativeLibraries = true;
3651
David 'Digit' Turner63909292010-06-03 14:37:42 -07003652 // Always extract the shared library
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003653 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3654 File.separator + libFileName;
3655 File sharedLibraryFile = new File(sharedLibraryFilePath);
David 'Digit' Turner63909292010-06-03 14:37:42 -07003656
3657 if (Config.LOGD) {
3658 Log.d(TAG, "Caching shared lib " + entry.getName());
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003659 }
David 'Digit' Turner63909292010-06-03 14:37:42 -07003660 if (mInstaller == null) {
3661 sharedLibraryDir.mkdir();
3662 }
3663 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
3664 sharedLibraryFile);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003665 }
3666 if (!hasNativeLibraries)
3667 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3668
3669 if (!installedNativeLibraries)
3670 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3671
3672 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3673 }
3674
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003675 // Find the gdbserver executable program in a package at
3676 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3677 //
3678 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3679 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3680 //
3681 private int cachePackageGdbServerLI(PackageParser.Package pkg,
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003682 File scanFile, String cpuAbi) throws IOException, ZipException {
3683 File installGdbServerDir = getNativeBinaryDirForPackage(pkg);
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003684 final String GDBSERVER = "gdbserver";
3685 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3686
3687 ZipFile zipFile = new ZipFile(scanFile);
3688 Enumeration<ZipEntry> entries =
3689 (Enumeration<ZipEntry>) zipFile.entries();
3690
3691 while (entries.hasMoreElements()) {
3692 ZipEntry entry = entries.nextElement();
3693 // skip directories
3694 if (entry.isDirectory()) {
3695 continue;
3696 }
3697 String entryName = entry.getName();
3698
3699 if (!entryName.equals(apkGdbServerPath)) {
3700 continue;
3701 }
3702
3703 String installGdbServerPath = installGdbServerDir.getPath() +
3704 "/" + GDBSERVER;
3705 File installGdbServerFile = new File(installGdbServerPath);
David 'Digit' Turner63909292010-06-03 14:37:42 -07003706
3707 if (Config.LOGD) {
3708 Log.d(TAG, "Caching gdbserver " + entry.getName());
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003709 }
David 'Digit' Turner63909292010-06-03 14:37:42 -07003710 if (mInstaller == null) {
3711 installGdbServerDir.mkdir();
3712 }
3713 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3714 installGdbServerFile);
3715
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003716 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3717 }
3718 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3719 }
3720
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003721 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3722 // and copy them to /data/data/<appname>/lib.
3723 //
3724 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3725 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3726 // one if ro.product.cpu.abi2 is defined.
3727 //
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003728 private int cachePackageSharedLibsLI(PackageParser.Package pkg, File scanFile) {
David 'Digit' Turner63909292010-06-03 14:37:42 -07003729 // Remove all native binaries from a directory. This is used when upgrading
3730 // a package: in case the new .apk doesn't contain a native binary that was
3731 // in the old one (and thus installed), we need to remove it from
3732 // /data/data/<appname>/lib
3733 //
3734 // The simplest way to do that is to remove all files in this directory,
3735 // since it is owned by "system", applications are not supposed to write
3736 // anything there.
3737 removeNativeBinariesLI(pkg);
3738
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003739 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003740 try {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003741 int result = cachePackageSharedLibsForAbiLI(pkg, scanFile, cpuAbi);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003742
3743 // some architectures are capable of supporting several CPU ABIs
3744 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3745 // this is indicated by the definition of the ro.product.cpu.abi2
3746 // system property.
3747 //
3748 // only scan the package twice in case of ABI mismatch
3749 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003750 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003751 if (cpuAbi2 != null) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003752 result = cachePackageSharedLibsForAbiLI(pkg, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003753 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003754
3755 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003756 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003757 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003758 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003759
3760 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3761 cpuAbi = cpuAbi2;
3762 }
3763 }
3764
3765 // for debuggable packages, also extract gdbserver from lib/<abi>
3766 // into /data/data/<appname>/lib too.
3767 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3768 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003769 int result2 = cachePackageGdbServerLI(pkg, scanFile, cpuAbi);
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003770 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3771 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003773 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003774 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003775 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003776 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003777 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003778 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003779 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003780 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003781 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003782 }
3783
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003784 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003785 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003786 File binaryDir,
3787 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003788 InputStream inputStream = zipFile.getInputStream(entry);
3789 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003790 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003791 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003792 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 // now need to be left as world readable and owned by the system.
3794 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3795 ! tempFile.setLastModified(entry.getTime()) ||
3796 FileUtils.setPermissions(tempFilePath,
3797 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003798 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003799 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003800 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 // Failed to properly write file.
3802 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003803 throw new IOException("Couldn't create cached binary "
3804 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 }
3806 } finally {
3807 inputStream.close();
3808 }
3809 }
3810
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003811 // Remove the native binaries of a given package. This simply
3812 // gets rid of the files in the 'lib' sub-directory.
3813 private void removeNativeBinariesLI(PackageParser.Package pkg) {
3814 File binaryDir = getNativeBinaryDirForPackage(pkg);
3815
3816 if (DEBUG_NATIVE) {
3817 Slog.w(TAG,"Deleting native binaries from: " + binaryDir.getPath());
3818 }
3819
3820 // Just remove any file in the directory. Since the directory
3821 // is owned by the 'system' UID, the application is not supposed
3822 // to have written anything there.
3823 //
3824 if (binaryDir.exists()) {
3825 File[] binaries = binaryDir.listFiles();
3826 if (binaries != null) {
3827 for (int nn=0; nn < binaries.length; nn++) {
3828 if (DEBUG_NATIVE) {
3829 Slog.d(TAG," Deleting " + binaries[nn].getName());
3830 }
3831 if (!binaries[nn].delete()) {
3832 Slog.w(TAG,"Could not delete native binary: " +
3833 binaries[nn].getPath());
3834 }
3835 }
3836 }
3837 // Do not delete 'lib' directory itself, or this will prevent
3838 // installation of future updates.
3839 }
3840 }
3841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3843 if (chatty && Config.LOGD) Log.d(
3844 TAG, "Removing package " + pkg.applicationInfo.packageName );
3845
3846 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003847 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 mPackages.remove(pkg.applicationInfo.packageName);
3850 if (pkg.mPath != null) {
3851 mAppDirs.remove(pkg.mPath);
3852 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003854 PackageSetting ps = (PackageSetting)pkg.mExtras;
3855 if (ps != null && ps.sharedUser != null) {
3856 // XXX don't do this until the data is removed.
3857 if (false) {
3858 ps.sharedUser.packages.remove(ps);
3859 if (ps.sharedUser.packages.size() == 0) {
3860 // Remove.
3861 }
3862 }
3863 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865 int N = pkg.providers.size();
3866 StringBuilder r = null;
3867 int i;
3868 for (i=0; i<N; i++) {
3869 PackageParser.Provider p = pkg.providers.get(i);
3870 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3871 p.info.name));
3872 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003874 /* The is another ContentProvider with this authority when
3875 * this app was installed so this authority is null,
3876 * Ignore it as we don't have to unregister the provider.
3877 */
3878 continue;
3879 }
3880 String names[] = p.info.authority.split(";");
3881 for (int j = 0; j < names.length; j++) {
3882 if (mProviders.get(names[j]) == p) {
3883 mProviders.remove(names[j]);
3884 if (chatty && Config.LOGD) Log.d(
3885 TAG, "Unregistered content provider: " + names[j] +
3886 ", className = " + p.info.name +
3887 ", isSyncable = " + p.info.isSyncable);
3888 }
3889 }
3890 if (chatty) {
3891 if (r == null) {
3892 r = new StringBuilder(256);
3893 } else {
3894 r.append(' ');
3895 }
3896 r.append(p.info.name);
3897 }
3898 }
3899 if (r != null) {
3900 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3901 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 N = pkg.services.size();
3904 r = null;
3905 for (i=0; i<N; i++) {
3906 PackageParser.Service s = pkg.services.get(i);
3907 mServices.removeService(s);
3908 if (chatty) {
3909 if (r == null) {
3910 r = new StringBuilder(256);
3911 } else {
3912 r.append(' ');
3913 }
3914 r.append(s.info.name);
3915 }
3916 }
3917 if (r != null) {
3918 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3919 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003921 N = pkg.receivers.size();
3922 r = null;
3923 for (i=0; i<N; i++) {
3924 PackageParser.Activity a = pkg.receivers.get(i);
3925 mReceivers.removeActivity(a, "receiver");
3926 if (chatty) {
3927 if (r == null) {
3928 r = new StringBuilder(256);
3929 } else {
3930 r.append(' ');
3931 }
3932 r.append(a.info.name);
3933 }
3934 }
3935 if (r != null) {
3936 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3937 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003939 N = pkg.activities.size();
3940 r = null;
3941 for (i=0; i<N; i++) {
3942 PackageParser.Activity a = pkg.activities.get(i);
3943 mActivities.removeActivity(a, "activity");
3944 if (chatty) {
3945 if (r == null) {
3946 r = new StringBuilder(256);
3947 } else {
3948 r.append(' ');
3949 }
3950 r.append(a.info.name);
3951 }
3952 }
3953 if (r != null) {
3954 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3955 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 N = pkg.permissions.size();
3958 r = null;
3959 for (i=0; i<N; i++) {
3960 PackageParser.Permission p = pkg.permissions.get(i);
3961 boolean tree = false;
3962 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3963 if (bp == null) {
3964 tree = true;
3965 bp = mSettings.mPermissionTrees.get(p.info.name);
3966 }
3967 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003968 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969 if (chatty) {
3970 if (r == null) {
3971 r = new StringBuilder(256);
3972 } else {
3973 r.append(' ');
3974 }
3975 r.append(p.info.name);
3976 }
3977 }
3978 }
3979 if (r != null) {
3980 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3981 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003983 N = pkg.instrumentation.size();
3984 r = null;
3985 for (i=0; i<N; i++) {
3986 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003987 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003988 if (chatty) {
3989 if (r == null) {
3990 r = new StringBuilder(256);
3991 } else {
3992 r.append(' ');
3993 }
3994 r.append(a.info.name);
3995 }
3996 }
3997 if (r != null) {
3998 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3999 }
4000 }
4001 }
4002
4003 private static final boolean isPackageFilename(String name) {
4004 return name != null && name.endsWith(".apk");
4005 }
4006
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004007 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
4008 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
4009 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
4010 return true;
4011 }
4012 }
4013 return false;
4014 }
4015
4016 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004017 PackageParser.Package pkgInfo, boolean grantPermissions,
4018 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 // Make sure there are no dangling permission trees.
4020 Iterator<BasePermission> it = mSettings.mPermissionTrees
4021 .values().iterator();
4022 while (it.hasNext()) {
4023 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004024 if (bp.packageSetting == null) {
4025 // We may not yet have parsed the package, so just see if
4026 // we still know about its settings.
4027 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4028 }
4029 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004030 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 + " from package " + bp.sourcePackage);
4032 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004033 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4034 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4035 Slog.i(TAG, "Removing old permission tree: " + bp.name
4036 + " from package " + bp.sourcePackage);
4037 grantPermissions = true;
4038 it.remove();
4039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040 }
4041 }
4042
4043 // Make sure all dynamic permissions have been assigned to a package,
4044 // and make sure there are no dangling permissions.
4045 it = mSettings.mPermissions.values().iterator();
4046 while (it.hasNext()) {
4047 BasePermission bp = it.next();
4048 if (bp.type == BasePermission.TYPE_DYNAMIC) {
4049 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
4050 + bp.name + " pkg=" + bp.sourcePackage
4051 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004052 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 BasePermission tree = findPermissionTreeLP(bp.name);
4054 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004055 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056 bp.perm = new PackageParser.Permission(tree.perm.owner,
4057 new PermissionInfo(bp.pendingInfo));
4058 bp.perm.info.packageName = tree.perm.info.packageName;
4059 bp.perm.info.name = bp.name;
4060 bp.uid = tree.uid;
4061 }
4062 }
4063 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004064 if (bp.packageSetting == null) {
4065 // We may not yet have parsed the package, so just see if
4066 // we still know about its settings.
4067 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4068 }
4069 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004070 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 + " from package " + bp.sourcePackage);
4072 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004073 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4074 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4075 Slog.i(TAG, "Removing old permission: " + bp.name
4076 + " from package " + bp.sourcePackage);
4077 grantPermissions = true;
4078 it.remove();
4079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080 }
4081 }
4082
4083 // Now update the permissions for all packages, in particular
4084 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004085 if (grantPermissions) {
4086 for (PackageParser.Package pkg : mPackages.values()) {
4087 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004088 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004089 }
4090 }
4091 }
4092
4093 if (pkgInfo != null) {
4094 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 }
4096 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
4099 final PackageSetting ps = (PackageSetting)pkg.mExtras;
4100 if (ps == null) {
4101 return;
4102 }
4103 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004104 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004106 if (replace) {
4107 ps.permissionsFixed = false;
4108 if (gp == ps) {
4109 gp.grantedPermissions.clear();
4110 gp.gids = mGlobalGids;
4111 }
4112 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004114 if (gp.gids == null) {
4115 gp.gids = mGlobalGids;
4116 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118 final int N = pkg.requestedPermissions.size();
4119 for (int i=0; i<N; i++) {
4120 String name = pkg.requestedPermissions.get(i);
4121 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004122 if (false) {
4123 if (gp != ps) {
4124 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004125 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 }
4127 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004128 if (bp != null && bp.packageSetting != null) {
4129 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004130 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004131 boolean allowedSig = false;
4132 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
4133 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07004135 } else if (bp.packageSetting == null) {
4136 // This permission is invalid; skip it.
4137 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004138 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
4139 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
4140 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004141 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004142 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004144 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4146 // For updated system applications, the signatureOrSystem permission
4147 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004148 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004149 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
4150 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
4151 if(sysPs.grantedPermissions.contains(perm)) {
4152 allowed = true;
4153 } else {
4154 allowed = false;
4155 }
4156 } else {
4157 allowed = true;
4158 }
4159 }
4160 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004161 if (allowed) {
4162 allowedSig = true;
4163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 } else {
4165 allowed = false;
4166 }
4167 if (false) {
4168 if (gp != ps) {
4169 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4170 }
4171 }
4172 if (allowed) {
4173 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4174 && ps.permissionsFixed) {
4175 // If this is an existing, non-system package, then
4176 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004177 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004178 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004179 // Except... if this is a permission that was added
4180 // to the platform (note: need to only do this when
4181 // updating the platform).
4182 final int NP = PackageParser.NEW_PERMISSIONS.length;
4183 for (int ip=0; ip<NP; ip++) {
4184 final PackageParser.NewPermissionInfo npi
4185 = PackageParser.NEW_PERMISSIONS[ip];
4186 if (npi.name.equals(perm)
4187 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4188 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004189 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004190 + pkg.packageName);
4191 break;
4192 }
4193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 }
4195 }
4196 if (allowed) {
4197 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004198 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 gp.grantedPermissions.add(perm);
4200 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004201 } else if (!ps.haveGids) {
4202 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004203 }
4204 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004205 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 + " to package " + pkg.packageName
4207 + " because it was previously installed without");
4208 }
4209 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004210 if (gp.grantedPermissions.remove(perm)) {
4211 changedPermission = true;
4212 gp.gids = removeInts(gp.gids, bp.gids);
4213 Slog.i(TAG, "Un-granting permission " + perm
4214 + " from package " + pkg.packageName
4215 + " (protectionLevel=" + bp.protectionLevel
4216 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4217 + ")");
4218 } else {
4219 Slog.w(TAG, "Not granting permission " + perm
4220 + " to package " + pkg.packageName
4221 + " (protectionLevel=" + bp.protectionLevel
4222 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4223 + ")");
4224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225 }
4226 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004227 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004228 + " in package " + pkg.packageName);
4229 }
4230 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004231
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004232 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004233 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4234 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004235 // This is the first that we have heard about this package, so the
4236 // permissions we have now selected are fixed until explicitly
4237 // changed.
4238 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004239 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004240 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004243 private final class ActivityIntentResolver
4244 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004245 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004246 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004247 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 }
4249
Mihai Preda074edef2009-05-18 17:13:31 +02004250 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004251 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004252 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004253 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4254 }
4255
Mihai Predaeae850c2009-05-13 10:13:48 +02004256 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4257 ArrayList<PackageParser.Activity> packageActivities) {
4258 if (packageActivities == null) {
4259 return null;
4260 }
4261 mFlags = flags;
4262 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4263 int N = packageActivities.size();
4264 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4265 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004266
4267 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004268 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004269 intentFilters = packageActivities.get(i).intents;
4270 if (intentFilters != null && intentFilters.size() > 0) {
4271 listCut.add(intentFilters);
4272 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004273 }
4274 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4275 }
4276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004277 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004278 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004279 if (SHOW_INFO || Config.LOGV) Log.v(
4280 TAG, " " + type + " " +
4281 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4282 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4283 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004284 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004285 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4286 if (SHOW_INFO || Config.LOGV) {
4287 Log.v(TAG, " IntentFilter:");
4288 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4289 }
4290 if (!intent.debugCheck()) {
4291 Log.w(TAG, "==> For Activity " + a.info.name);
4292 }
4293 addFilter(intent);
4294 }
4295 }
4296
4297 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004298 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 if (SHOW_INFO || Config.LOGV) Log.v(
4300 TAG, " " + type + " " +
4301 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4302 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4303 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004304 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004305 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4306 if (SHOW_INFO || Config.LOGV) {
4307 Log.v(TAG, " IntentFilter:");
4308 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4309 }
4310 removeFilter(intent);
4311 }
4312 }
4313
4314 @Override
4315 protected boolean allowFilterResult(
4316 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4317 ActivityInfo filterAi = filter.activity.info;
4318 for (int i=dest.size()-1; i>=0; i--) {
4319 ActivityInfo destAi = dest.get(i).activityInfo;
4320 if (destAi.name == filterAi.name
4321 && destAi.packageName == filterAi.packageName) {
4322 return false;
4323 }
4324 }
4325 return true;
4326 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004328 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004329 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4330 return info.activity.owner.packageName;
4331 }
4332
4333 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004334 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4335 int match) {
4336 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4337 return null;
4338 }
4339 final PackageParser.Activity activity = info.activity;
4340 if (mSafeMode && (activity.info.applicationInfo.flags
4341 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4342 return null;
4343 }
4344 final ResolveInfo res = new ResolveInfo();
4345 res.activityInfo = PackageParser.generateActivityInfo(activity,
4346 mFlags);
4347 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4348 res.filter = info;
4349 }
4350 res.priority = info.getPriority();
4351 res.preferredOrder = activity.owner.mPreferredOrder;
4352 //System.out.println("Result: " + res.activityInfo.className +
4353 // " = " + res.priority);
4354 res.match = match;
4355 res.isDefault = info.hasDefault;
4356 res.labelRes = info.labelRes;
4357 res.nonLocalizedLabel = info.nonLocalizedLabel;
4358 res.icon = info.icon;
4359 return res;
4360 }
4361
4362 @Override
4363 protected void sortResults(List<ResolveInfo> results) {
4364 Collections.sort(results, mResolvePrioritySorter);
4365 }
4366
4367 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004368 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004369 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004370 out.print(prefix); out.print(
4371 Integer.toHexString(System.identityHashCode(filter.activity)));
4372 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004373 out.print(filter.activity.getComponentShortName());
4374 out.print(" filter ");
4375 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004376 }
4377
4378// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4379// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4380// final List<ResolveInfo> retList = Lists.newArrayList();
4381// while (i.hasNext()) {
4382// final ResolveInfo resolveInfo = i.next();
4383// if (isEnabledLP(resolveInfo.activityInfo)) {
4384// retList.add(resolveInfo);
4385// }
4386// }
4387// return retList;
4388// }
4389
4390 // Keys are String (activity class name), values are Activity.
4391 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4392 = new HashMap<ComponentName, PackageParser.Activity>();
4393 private int mFlags;
4394 }
4395
4396 private final class ServiceIntentResolver
4397 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004398 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004399 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004400 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004401 }
4402
Mihai Preda074edef2009-05-18 17:13:31 +02004403 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004404 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004405 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004406 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4407 }
4408
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004409 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4410 ArrayList<PackageParser.Service> packageServices) {
4411 if (packageServices == null) {
4412 return null;
4413 }
4414 mFlags = flags;
4415 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4416 int N = packageServices.size();
4417 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4418 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4419
4420 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4421 for (int i = 0; i < N; ++i) {
4422 intentFilters = packageServices.get(i).intents;
4423 if (intentFilters != null && intentFilters.size() > 0) {
4424 listCut.add(intentFilters);
4425 }
4426 }
4427 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4428 }
4429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004430 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004431 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004432 if (SHOW_INFO || Config.LOGV) Log.v(
4433 TAG, " " + (s.info.nonLocalizedLabel != null
4434 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4435 if (SHOW_INFO || Config.LOGV) Log.v(
4436 TAG, " Class=" + s.info.name);
4437 int NI = s.intents.size();
4438 int j;
4439 for (j=0; j<NI; j++) {
4440 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4441 if (SHOW_INFO || Config.LOGV) {
4442 Log.v(TAG, " IntentFilter:");
4443 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4444 }
4445 if (!intent.debugCheck()) {
4446 Log.w(TAG, "==> For Service " + s.info.name);
4447 }
4448 addFilter(intent);
4449 }
4450 }
4451
4452 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004453 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004454 if (SHOW_INFO || Config.LOGV) Log.v(
4455 TAG, " " + (s.info.nonLocalizedLabel != null
4456 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4457 if (SHOW_INFO || Config.LOGV) Log.v(
4458 TAG, " Class=" + s.info.name);
4459 int NI = s.intents.size();
4460 int j;
4461 for (j=0; j<NI; j++) {
4462 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4463 if (SHOW_INFO || Config.LOGV) {
4464 Log.v(TAG, " IntentFilter:");
4465 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4466 }
4467 removeFilter(intent);
4468 }
4469 }
4470
4471 @Override
4472 protected boolean allowFilterResult(
4473 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4474 ServiceInfo filterSi = filter.service.info;
4475 for (int i=dest.size()-1; i>=0; i--) {
4476 ServiceInfo destAi = dest.get(i).serviceInfo;
4477 if (destAi.name == filterSi.name
4478 && destAi.packageName == filterSi.packageName) {
4479 return false;
4480 }
4481 }
4482 return true;
4483 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004486 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4487 return info.service.owner.packageName;
4488 }
4489
4490 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004491 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4492 int match) {
4493 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4494 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4495 return null;
4496 }
4497 final PackageParser.Service service = info.service;
4498 if (mSafeMode && (service.info.applicationInfo.flags
4499 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4500 return null;
4501 }
4502 final ResolveInfo res = new ResolveInfo();
4503 res.serviceInfo = PackageParser.generateServiceInfo(service,
4504 mFlags);
4505 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4506 res.filter = filter;
4507 }
4508 res.priority = info.getPriority();
4509 res.preferredOrder = service.owner.mPreferredOrder;
4510 //System.out.println("Result: " + res.activityInfo.className +
4511 // " = " + res.priority);
4512 res.match = match;
4513 res.isDefault = info.hasDefault;
4514 res.labelRes = info.labelRes;
4515 res.nonLocalizedLabel = info.nonLocalizedLabel;
4516 res.icon = info.icon;
4517 return res;
4518 }
4519
4520 @Override
4521 protected void sortResults(List<ResolveInfo> results) {
4522 Collections.sort(results, mResolvePrioritySorter);
4523 }
4524
4525 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004526 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004527 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004528 out.print(prefix); out.print(
4529 Integer.toHexString(System.identityHashCode(filter.service)));
4530 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004531 out.print(filter.service.getComponentShortName());
4532 out.print(" filter ");
4533 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004534 }
4535
4536// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4537// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4538// final List<ResolveInfo> retList = Lists.newArrayList();
4539// while (i.hasNext()) {
4540// final ResolveInfo resolveInfo = (ResolveInfo) i;
4541// if (isEnabledLP(resolveInfo.serviceInfo)) {
4542// retList.add(resolveInfo);
4543// }
4544// }
4545// return retList;
4546// }
4547
4548 // Keys are String (activity class name), values are Activity.
4549 private final HashMap<ComponentName, PackageParser.Service> mServices
4550 = new HashMap<ComponentName, PackageParser.Service>();
4551 private int mFlags;
4552 };
4553
4554 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4555 new Comparator<ResolveInfo>() {
4556 public int compare(ResolveInfo r1, ResolveInfo r2) {
4557 int v1 = r1.priority;
4558 int v2 = r2.priority;
4559 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4560 if (v1 != v2) {
4561 return (v1 > v2) ? -1 : 1;
4562 }
4563 v1 = r1.preferredOrder;
4564 v2 = r2.preferredOrder;
4565 if (v1 != v2) {
4566 return (v1 > v2) ? -1 : 1;
4567 }
4568 if (r1.isDefault != r2.isDefault) {
4569 return r1.isDefault ? -1 : 1;
4570 }
4571 v1 = r1.match;
4572 v2 = r2.match;
4573 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4574 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4575 }
4576 };
4577
4578 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4579 new Comparator<ProviderInfo>() {
4580 public int compare(ProviderInfo p1, ProviderInfo p2) {
4581 final int v1 = p1.initOrder;
4582 final int v2 = p2.initOrder;
4583 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4584 }
4585 };
4586
Kenny Root93565c4b2010-06-18 15:46:06 -07004587 private static final boolean DEBUG_OBB = false;
4588
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004589 private static final void sendPackageBroadcast(String action, String pkg,
4590 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004591 IActivityManager am = ActivityManagerNative.getDefault();
4592 if (am != null) {
4593 try {
4594 final Intent intent = new Intent(action,
4595 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4596 if (extras != null) {
4597 intent.putExtras(extras);
4598 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004599 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004600 am.broadcastIntent(null, intent, null, finishedReceiver,
4601 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004602 } catch (RemoteException ex) {
4603 }
4604 }
4605 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004606
4607 public String nextPackageToClean(String lastPackage) {
4608 synchronized (mPackages) {
4609 if (!mMediaMounted) {
4610 // If the external storage is no longer mounted at this point,
4611 // the caller may not have been able to delete all of this
4612 // packages files and can not delete any more. Bail.
4613 return null;
4614 }
4615 if (lastPackage != null) {
4616 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4617 }
4618 return mSettings.mPackagesToBeCleaned.size() > 0
4619 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4620 }
4621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004622
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004623 void schedulePackageCleaning(String packageName) {
4624 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4625 }
4626
4627 void startCleaningPackages() {
4628 synchronized (mPackages) {
4629 if (!mMediaMounted) {
4630 return;
4631 }
4632 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4633 return;
4634 }
4635 }
4636 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4637 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4638 IActivityManager am = ActivityManagerNative.getDefault();
4639 if (am != null) {
4640 try {
4641 am.startService(null, intent, null);
4642 } catch (RemoteException e) {
4643 }
4644 }
4645 }
4646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004647 private final class AppDirObserver extends FileObserver {
4648 public AppDirObserver(String path, int mask, boolean isrom) {
4649 super(path, mask);
4650 mRootDir = path;
4651 mIsRom = isrom;
4652 }
4653
4654 public void onEvent(int event, String path) {
4655 String removedPackage = null;
4656 int removedUid = -1;
4657 String addedPackage = null;
4658 int addedUid = -1;
4659
4660 synchronized (mInstallLock) {
4661 String fullPathStr = null;
4662 File fullPath = null;
4663 if (path != null) {
4664 fullPath = new File(mRootDir, path);
4665 fullPathStr = fullPath.getPath();
4666 }
4667
4668 if (Config.LOGV) Log.v(
4669 TAG, "File " + fullPathStr + " changed: "
4670 + Integer.toHexString(event));
4671
4672 if (!isPackageFilename(path)) {
4673 if (Config.LOGV) Log.v(
4674 TAG, "Ignoring change of non-package file: " + fullPathStr);
4675 return;
4676 }
4677
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004678 // Ignore packages that are being installed or
4679 // have just been installed.
4680 if (ignoreCodePath(fullPathStr)) {
4681 return;
4682 }
4683 PackageParser.Package p = null;
4684 synchronized (mPackages) {
4685 p = mAppDirs.get(fullPathStr);
4686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004687 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004688 if (p != null) {
4689 removePackageLI(p, true);
4690 removedPackage = p.applicationInfo.packageName;
4691 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004692 }
4693 }
4694
4695 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004696 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004697 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004698 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4699 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004700 PackageParser.PARSE_CHATTY |
4701 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004702 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004703 if (p != null) {
4704 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004705 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004706 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004707 }
4708 addedPackage = p.applicationInfo.packageName;
4709 addedUid = p.applicationInfo.uid;
4710 }
4711 }
4712 }
4713
4714 synchronized (mPackages) {
4715 mSettings.writeLP();
4716 }
4717 }
4718
4719 if (removedPackage != null) {
4720 Bundle extras = new Bundle(1);
4721 extras.putInt(Intent.EXTRA_UID, removedUid);
4722 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004723 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4724 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004725 }
4726 if (addedPackage != null) {
4727 Bundle extras = new Bundle(1);
4728 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004729 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4730 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004731 }
4732 }
4733
4734 private final String mRootDir;
4735 private final boolean mIsRom;
4736 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004738 /* Called when a downloaded package installation has been confirmed by the user */
4739 public void installPackage(
4740 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004741 installPackage(packageURI, observer, flags, null);
4742 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004743
Jacek Surazski65e13172009-04-28 15:26:38 +02004744 /* Called when a downloaded package installation has been confirmed by the user */
4745 public void installPackage(
4746 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4747 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004748 mContext.enforceCallingOrSelfPermission(
4749 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004750
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004751 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004752 msg.obj = new InstallParams(packageURI, observer, flags,
4753 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004754 mHandler.sendMessage(msg);
4755 }
4756
Christopher Tate1bb69062010-02-19 17:02:12 -08004757 public void finishPackageInstall(int token) {
4758 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4759 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4760 mHandler.sendMessage(msg);
4761 }
4762
Kenny Root93565c4b2010-06-18 15:46:06 -07004763 public void setPackageObbPath(String packageName, String path) {
4764 if (DEBUG_OBB)
4765 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4766 PackageSetting pkgSetting;
4767 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004768 final int permission = mContext.checkCallingPermission(
4769 android.Manifest.permission.INSTALL_PACKAGES);
4770 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004771 synchronized (mPackages) {
4772 pkgSetting = mSettings.mPackages.get(packageName);
4773 if (pkgSetting == null) {
4774 throw new IllegalArgumentException("Unknown package: " + packageName);
4775 }
4776 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4777 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4778 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4779 + pkgSetting.userId);
4780 }
4781 pkgSetting.obbPathString = path;
4782 mSettings.writeLP();
4783 }
4784 }
4785
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004786 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004787 // Queue up an async operation since the package installation may take a little while.
4788 mHandler.post(new Runnable() {
4789 public void run() {
4790 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004791 // Result object to be returned
4792 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004793 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004794 res.uid = -1;
4795 res.pkg = null;
4796 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004797 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004798 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004799 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004800 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004801 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004802 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004803 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004804
4805 // A restore should be performed at this point if (a) the install
4806 // succeeded, (b) the operation is not an update, and (c) the new
4807 // package has a backupAgent defined.
4808 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004809 boolean doRestore = (!update
4810 && res.pkg != null
4811 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004812
4813 // Set up the post-install work request bookkeeping. This will be used
4814 // and cleaned up by the post-install event handling regardless of whether
4815 // there's a restore pass performed. Token values are >= 1.
4816 int token;
4817 if (mNextInstallToken < 0) mNextInstallToken = 1;
4818 token = mNextInstallToken++;
4819
4820 PostInstallData data = new PostInstallData(args, res);
4821 mRunningInstalls.put(token, data);
4822 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4823
4824 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4825 // Pass responsibility to the Backup Manager. It will perform a
4826 // restore if appropriate, then pass responsibility back to the
4827 // Package Manager to run the post-install observer callbacks
4828 // and broadcasts.
4829 IBackupManager bm = IBackupManager.Stub.asInterface(
4830 ServiceManager.getService(Context.BACKUP_SERVICE));
4831 if (bm != null) {
4832 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4833 + " to BM for possible restore");
4834 try {
4835 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4836 } catch (RemoteException e) {
4837 // can't happen; the backup manager is local
4838 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004839 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004840 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004841 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004842 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004843 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004844 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004846 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004847
4848 if (!doRestore) {
4849 // No restore possible, or the Backup Manager was mysteriously not
4850 // available -- just fire the post-install work request directly.
4851 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4852 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4853 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004855 }
4856 });
4857 }
4858
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004859 abstract class HandlerParams {
4860 final static int MAX_RETRIES = 4;
4861 int retry = 0;
4862 final void startCopy() {
4863 try {
4864 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4865 retry++;
4866 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004867 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004868 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4869 handleServiceError();
4870 return;
4871 } else {
4872 handleStartCopy();
4873 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4874 mHandler.sendEmptyMessage(MCS_UNBIND);
4875 }
4876 } catch (RemoteException e) {
4877 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4878 mHandler.sendEmptyMessage(MCS_RECONNECT);
4879 }
4880 handleReturnCode();
4881 }
4882
4883 final void serviceError() {
4884 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4885 handleServiceError();
4886 handleReturnCode();
4887 }
4888 abstract void handleStartCopy() throws RemoteException;
4889 abstract void handleServiceError();
4890 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004891 }
4892
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004893 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004894 final IPackageInstallObserver observer;
4895 int flags;
4896 final Uri packageURI;
4897 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004898 private InstallArgs mArgs;
4899 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004900 InstallParams(Uri packageURI,
4901 IPackageInstallObserver observer, int flags,
4902 String installerPackageName) {
4903 this.packageURI = packageURI;
4904 this.flags = flags;
4905 this.observer = observer;
4906 this.installerPackageName = installerPackageName;
4907 }
4908
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004909 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4910 String packageName = pkgLite.packageName;
4911 int installLocation = pkgLite.installLocation;
4912 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4913 synchronized (mPackages) {
4914 PackageParser.Package pkg = mPackages.get(packageName);
4915 if (pkg != null) {
4916 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4917 // Check for updated system application.
4918 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4919 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004920 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004921 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4922 }
4923 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4924 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004925 if (onSd) {
4926 // Install flag overrides everything.
4927 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4928 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004929 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004930 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4931 // Application explicitly specified internal.
4932 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4933 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4934 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004935 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004936 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004937 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4938 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4939 }
4940 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004941 }
4942 }
4943 } else {
4944 // Invalid install. Return error code
4945 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4946 }
4947 }
4948 }
4949 // All the special cases have been taken care of.
4950 // Return result based on recommended install location.
4951 if (onSd) {
4952 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4953 }
4954 return pkgLite.recommendedInstallLocation;
4955 }
4956
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004957 /*
4958 * Invoke remote method to get package information and install
4959 * location values. Override install location based on default
4960 * policy if needed and then create install arguments based
4961 * on the install location.
4962 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004963 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004964 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004965 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4966 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004967 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4968 if (onInt && onSd) {
4969 // Check if both bits are set.
4970 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4971 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4972 } else if (fwdLocked && onSd) {
4973 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004974 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004975 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004976 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004977 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004978 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004979 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004980 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4981 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4982 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4983 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4984 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004985 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4986 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4987 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004988 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4989 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004990 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004991 // Override with defaults if needed.
4992 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004993 if (!onSd && !onInt) {
4994 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004995 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4996 // Set the flag to install on external media.
4997 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004998 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004999 } else {
5000 // Make sure the flag for installing on external
5001 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07005002 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005003 flags &= ~PackageManager.INSTALL_EXTERNAL;
5004 }
5005 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005006 }
5007 }
5008 // Create the file args now.
5009 mArgs = createInstallArgs(this);
5010 if (ret == PackageManager.INSTALL_SUCCEEDED) {
5011 // Create copy only if we are not in an erroneous state.
5012 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005013 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005014 }
5015 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005016 }
5017
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005018 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005019 void handleReturnCode() {
5020 processPendingInstall(mArgs, mRet);
5021 }
5022
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005023 @Override
5024 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005025 mArgs = createInstallArgs(this);
5026 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005027 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005028 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005029
5030 /*
5031 * Utility class used in movePackage api.
5032 * srcArgs and targetArgs are not set for invalid flags and make
5033 * sure to do null checks when invoking methods on them.
5034 * We probably want to return ErrorPrams for both failed installs
5035 * and moves.
5036 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005037 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005038 final IPackageMoveObserver observer;
5039 final int flags;
5040 final String packageName;
5041 final InstallArgs srcArgs;
5042 final InstallArgs targetArgs;
5043 int mRet;
5044 MoveParams(InstallArgs srcArgs,
5045 IPackageMoveObserver observer,
5046 int flags, String packageName) {
5047 this.srcArgs = srcArgs;
5048 this.observer = observer;
5049 this.flags = flags;
5050 this.packageName = packageName;
5051 if (srcArgs != null) {
5052 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
5053 targetArgs = createInstallArgs(packageUri, flags, packageName);
5054 } else {
5055 targetArgs = null;
5056 }
5057 }
5058
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005059 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005060 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5061 // Check for storage space on target medium
5062 if (!targetArgs.checkFreeStorage(mContainerService)) {
5063 Log.w(TAG, "Insufficient storage to install");
5064 return;
5065 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005066 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005067 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005068 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005069 if (DEBUG_SD_INSTALL) {
5070 StringBuilder builder = new StringBuilder();
5071 if (srcArgs != null) {
5072 builder.append("src: ");
5073 builder.append(srcArgs.getCodePath());
5074 }
5075 if (targetArgs != null) {
5076 builder.append(" target : ");
5077 builder.append(targetArgs.getCodePath());
5078 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005079 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005080 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005081 }
5082
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005083 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005084 void handleReturnCode() {
5085 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005086 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
5087 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
5088 currentStatus = PackageManager.MOVE_SUCCEEDED;
5089 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
5090 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
5091 }
5092 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005093 }
5094
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005095 @Override
5096 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005097 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005098 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005099 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005100
5101 private InstallArgs createInstallArgs(InstallParams params) {
5102 if (installOnSd(params.flags)) {
5103 return new SdInstallArgs(params);
5104 } else {
5105 return new FileInstallArgs(params);
5106 }
5107 }
5108
5109 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
5110 if (installOnSd(flags)) {
5111 return new SdInstallArgs(fullCodePath, fullResourcePath);
5112 } else {
5113 return new FileInstallArgs(fullCodePath, fullResourcePath);
5114 }
5115 }
5116
Suchi Amalapurapu9a212ad2010-05-18 11:06:53 -07005117 private InstallArgs createInstallArgs(Uri packageURI, int flags,
5118 String pkgName) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005119 if (installOnSd(flags)) {
5120 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
5121 return new SdInstallArgs(packageURI, cid);
5122 } else {
5123 return new FileInstallArgs(packageURI, pkgName);
5124 }
5125 }
5126
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005127 static abstract class InstallArgs {
5128 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005129 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005130 final int flags;
5131 final Uri packageURI;
5132 final String installerPackageName;
5133
5134 InstallArgs(Uri packageURI,
5135 IPackageInstallObserver observer, int flags,
5136 String installerPackageName) {
5137 this.packageURI = packageURI;
5138 this.flags = flags;
5139 this.observer = observer;
5140 this.installerPackageName = installerPackageName;
5141 }
5142
5143 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005144 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005145 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005146 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005147 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005148 abstract String getCodePath();
5149 abstract String getResourcePath();
5150 // Need installer lock especially for dex file removal.
5151 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005152 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005153 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005154 }
5155
5156 class FileInstallArgs extends InstallArgs {
5157 File installDir;
5158 String codeFileName;
5159 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005160 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005161
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005162 FileInstallArgs(InstallParams params) {
5163 super(params.packageURI, params.observer,
5164 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005165 }
5166
5167 FileInstallArgs(String fullCodePath, String fullResourcePath) {
5168 super(null, null, 0, null);
5169 File codeFile = new File(fullCodePath);
5170 installDir = codeFile.getParentFile();
5171 codeFileName = fullCodePath;
5172 resourceFileName = fullResourcePath;
5173 }
5174
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005175 FileInstallArgs(Uri packageURI, String pkgName) {
5176 super(packageURI, null, 0, null);
5177 boolean fwdLocked = isFwdLocked(flags);
5178 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5179 String apkName = getNextCodePath(null, pkgName, ".apk");
5180 codeFileName = new File(installDir, apkName + ".apk").getPath();
5181 resourceFileName = getResourcePathFromCodePath();
5182 }
5183
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005184 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5185 return imcs.checkFreeStorage(false, packageURI);
5186 }
5187
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005188 String getCodePath() {
5189 return codeFileName;
5190 }
5191
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005192 void createCopyFile() {
5193 boolean fwdLocked = isFwdLocked(flags);
5194 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5195 codeFileName = createTempPackageFile(installDir).getPath();
5196 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005197 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005198 }
5199
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005200 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005201 if (temp) {
5202 // Generate temp file name
5203 createCopyFile();
5204 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005205 // Get a ParcelFileDescriptor to write to the output file
5206 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005207 if (!created) {
5208 try {
5209 codeFile.createNewFile();
5210 // Set permissions
5211 if (!setPermissions()) {
5212 // Failed setting permissions.
5213 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5214 }
5215 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005216 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005217 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5218 }
5219 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005220 ParcelFileDescriptor out = null;
5221 try {
5222 out = ParcelFileDescriptor.open(codeFile,
5223 ParcelFileDescriptor.MODE_READ_WRITE);
5224 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005225 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005226 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5227 }
5228 // Copy the resource now
5229 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5230 try {
5231 if (imcs.copyResource(packageURI, out)) {
5232 ret = PackageManager.INSTALL_SUCCEEDED;
5233 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005234 } finally {
5235 try { if (out != null) out.close(); } catch (IOException e) {}
5236 }
5237 return ret;
5238 }
5239
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005240 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005241 if (status != PackageManager.INSTALL_SUCCEEDED) {
5242 cleanUp();
5243 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005244 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005245 }
5246
5247 boolean doRename(int status, final String pkgName, String oldCodePath) {
5248 if (status != PackageManager.INSTALL_SUCCEEDED) {
5249 cleanUp();
5250 return false;
5251 } else {
5252 // Rename based on packageName
5253 File codeFile = new File(getCodePath());
5254 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5255 File desFile = new File(installDir, apkName + ".apk");
5256 if (!codeFile.renameTo(desFile)) {
5257 return false;
5258 }
5259 // Reset paths since the file has been renamed.
5260 codeFileName = desFile.getPath();
5261 resourceFileName = getResourcePathFromCodePath();
5262 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005263 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005264 // Failed setting permissions.
5265 return false;
5266 }
5267 return true;
5268 }
5269 }
5270
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005271 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005272 if (status != PackageManager.INSTALL_SUCCEEDED) {
5273 cleanUp();
5274 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005275 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005276 }
5277
5278 String getResourcePath() {
5279 return resourceFileName;
5280 }
5281
5282 String getResourcePathFromCodePath() {
5283 String codePath = getCodePath();
5284 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5285 String apkNameOnly = getApkName(codePath);
5286 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5287 } else {
5288 return codePath;
5289 }
5290 }
5291
5292 private boolean cleanUp() {
5293 boolean ret = true;
5294 String sourceDir = getCodePath();
5295 String publicSourceDir = getResourcePath();
5296 if (sourceDir != null) {
5297 File sourceFile = new File(sourceDir);
5298 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005299 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005300 ret = false;
5301 }
5302 // Delete application's code and resources
5303 sourceFile.delete();
5304 }
5305 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5306 final File publicSourceFile = new File(publicSourceDir);
5307 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005308 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005309 }
5310 if (publicSourceFile.exists()) {
5311 publicSourceFile.delete();
5312 }
5313 }
5314 return ret;
5315 }
5316
5317 void cleanUpResourcesLI() {
5318 String sourceDir = getCodePath();
5319 if (cleanUp() && mInstaller != null) {
5320 int retCode = mInstaller.rmdex(sourceDir);
5321 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005322 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005323 + " at location "
5324 + sourceDir + ", retcode=" + retCode);
5325 // we don't consider this to be a failure of the core package deletion
5326 }
5327 }
5328 }
5329
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005330 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005331 // TODO Do this in a more elegant way later on. for now just a hack
5332 if (!isFwdLocked(flags)) {
5333 final int filePermissions =
5334 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5335 |FileUtils.S_IROTH;
5336 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5337 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005338 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005339 getCodePath()
5340 + ". The return code was: " + retCode);
5341 // TODO Define new internal error
5342 return false;
5343 }
5344 return true;
5345 }
5346 return true;
5347 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005348
5349 boolean doPostDeleteLI(boolean delete) {
5350 cleanUpResourcesLI();
5351 return true;
5352 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005353 }
5354
5355 class SdInstallArgs extends InstallArgs {
5356 String cid;
5357 String cachePath;
5358 static final String RES_FILE_NAME = "pkg.apk";
5359
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005360 SdInstallArgs(InstallParams params) {
5361 super(params.packageURI, params.observer,
5362 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005363 }
5364
5365 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005366 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005367 // Extract cid from fullCodePath
5368 int eidx = fullCodePath.lastIndexOf("/");
5369 String subStr1 = fullCodePath.substring(0, eidx);
5370 int sidx = subStr1.lastIndexOf("/");
5371 cid = subStr1.substring(sidx+1, eidx);
5372 cachePath = subStr1;
5373 }
5374
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005375 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005376 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5377 this.cid = cid;
Suchi Amalapurapu9a212ad2010-05-18 11:06:53 -07005378 cachePath = PackageHelper.getSdDir(cid);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005379 }
5380
5381 SdInstallArgs(Uri packageURI, String cid) {
5382 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005383 this.cid = cid;
5384 }
5385
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005386 void createCopyFile() {
5387 cid = getTempContainerId();
5388 }
5389
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005390 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5391 return imcs.checkFreeStorage(true, packageURI);
5392 }
5393
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005394 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005395 if (temp) {
5396 createCopyFile();
5397 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005398 cachePath = imcs.copyResourceToContainer(
5399 packageURI, cid,
5400 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005401 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5402 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005403 }
5404
5405 @Override
5406 String getCodePath() {
5407 return cachePath + "/" + RES_FILE_NAME;
5408 }
5409
5410 @Override
5411 String getResourcePath() {
5412 return cachePath + "/" + RES_FILE_NAME;
5413 }
5414
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005415 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005416 if (status != PackageManager.INSTALL_SUCCEEDED) {
5417 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005418 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005419 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005420 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005421 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005422 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005423 if (cachePath == null) {
5424 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5425 }
5426 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005427 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005428 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005429 }
5430
5431 boolean doRename(int status, final String pkgName,
5432 String oldCodePath) {
5433 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005434 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005435 if (PackageHelper.isContainerMounted(cid)) {
5436 // Unmount the container
5437 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005438 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005439 return false;
5440 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005441 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005442 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005443 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5444 " which might be stale. Will try to clean up.");
5445 // Clean up the stale container and proceed to recreate.
5446 if (!PackageHelper.destroySdDir(newCacheId)) {
5447 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5448 return false;
5449 }
5450 // Successfully cleaned up stale container. Try to rename again.
5451 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5452 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5453 + " inspite of cleaning it up.");
5454 return false;
5455 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005456 }
5457 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005458 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005459 newCachePath = PackageHelper.mountSdDir(newCacheId,
5460 getEncryptKey(), Process.SYSTEM_UID);
5461 } else {
5462 newCachePath = PackageHelper.getSdDir(newCacheId);
5463 }
5464 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005465 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005466 return false;
5467 }
5468 Log.i(TAG, "Succesfully renamed " + cid +
5469 " at path: " + cachePath + " to " + newCacheId +
5470 " at new path: " + newCachePath);
5471 cid = newCacheId;
5472 cachePath = newCachePath;
5473 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005474 }
5475
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005476 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005477 if (status != PackageManager.INSTALL_SUCCEEDED) {
5478 cleanUp();
5479 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005480 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005481 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005482 PackageHelper.mountSdDir(cid,
5483 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005484 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005485 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005486 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005487 }
5488
5489 private void cleanUp() {
5490 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005491 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005492 }
5493
5494 void cleanUpResourcesLI() {
5495 String sourceFile = getCodePath();
5496 // Remove dex file
5497 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005498 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005499 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005500 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005501 + " at location "
5502 + sourceFile.toString() + ", retcode=" + retCode);
5503 // we don't consider this to be a failure of the core package deletion
5504 }
5505 }
5506 cleanUp();
5507 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005508
5509 boolean matchContainer(String app) {
5510 if (cid.startsWith(app)) {
5511 return true;
5512 }
5513 return false;
5514 }
5515
5516 String getPackageName() {
5517 int idx = cid.lastIndexOf("-");
5518 if (idx == -1) {
5519 return cid;
5520 }
5521 return cid.substring(0, idx);
5522 }
5523
5524 boolean doPostDeleteLI(boolean delete) {
5525 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005526 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005527 if (mounted) {
5528 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005529 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005530 }
5531 if (ret && delete) {
5532 cleanUpResourcesLI();
5533 }
5534 return ret;
5535 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005536 };
5537
5538 // Utility method used to create code paths based on package name and available index.
5539 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5540 String idxStr = "";
5541 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005542 // Fall back to default value of idx=1 if prefix is not
5543 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005544 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005545 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005546 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005547 if (subStr.endsWith(suffix)) {
5548 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005549 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005550 // If oldCodePath already contains prefix find out the
5551 // ending index to either increment or decrement.
5552 int sidx = subStr.lastIndexOf(prefix);
5553 if (sidx != -1) {
5554 subStr = subStr.substring(sidx + prefix.length());
5555 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005556 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5557 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005558 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005559 try {
5560 idx = Integer.parseInt(subStr);
5561 if (idx <= 1) {
5562 idx++;
5563 } else {
5564 idx--;
5565 }
5566 } catch(NumberFormatException e) {
5567 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005568 }
5569 }
5570 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005571 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005572 return prefix + idxStr;
5573 }
5574
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005575 // Utility method used to ignore ADD/REMOVE events
5576 // by directory observer.
5577 private static boolean ignoreCodePath(String fullPathStr) {
5578 String apkName = getApkName(fullPathStr);
5579 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5580 if (idx != -1 && ((idx+1) < apkName.length())) {
5581 // Make sure the package ends with a numeral
5582 String version = apkName.substring(idx+1);
5583 try {
5584 Integer.parseInt(version);
5585 return true;
5586 } catch (NumberFormatException e) {}
5587 }
5588 return false;
5589 }
5590
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005591 // Utility method that returns the relative package path with respect
5592 // to the installation directory. Like say for /data/data/com.test-1.apk
5593 // string com.test-1 is returned.
5594 static String getApkName(String codePath) {
5595 if (codePath == null) {
5596 return null;
5597 }
5598 int sidx = codePath.lastIndexOf("/");
5599 int eidx = codePath.lastIndexOf(".");
5600 if (eidx == -1) {
5601 eidx = codePath.length();
5602 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005603 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005604 return null;
5605 }
5606 return codePath.substring(sidx+1, eidx);
5607 }
5608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005609 class PackageInstalledInfo {
5610 String name;
5611 int uid;
5612 PackageParser.Package pkg;
5613 int returnCode;
5614 PackageRemovedInfo removedInfo;
5615 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005617 /*
5618 * Install a non-existing package.
5619 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005620 private void installNewPackageLI(PackageParser.Package pkg,
5621 int parseFlags,
5622 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005623 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005624 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005625 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005626
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005627 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005628 res.name = pkgName;
5629 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005630 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5631 // A package with the same name is already installed, though
5632 // it has been renamed to an older name. The package we
5633 // are trying to install should be installed as an update to
5634 // the existing one, but that has not been requested, so bail.
5635 Slog.w(TAG, "Attempt to re-install " + pkgName
5636 + " without first uninstalling package running as "
5637 + mSettings.mRenamedPackages.get(pkgName));
5638 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5639 return;
5640 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005641 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005643 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005644 + " without first uninstalling.");
5645 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5646 return;
5647 }
5648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005650 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005652 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005653 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5654 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5655 }
5656 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005657 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005658 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005659 res);
5660 // delete the partially installed application. the data directory will have to be
5661 // restored if it was already existing
5662 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5663 // remove package from internal structures. Note that we want deletePackageX to
5664 // delete the package data and cache directories that it created in
5665 // scanPackageLocked, unless those directories existed before we even tried to
5666 // install.
5667 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005668 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005669 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5670 res.removedInfo);
5671 }
5672 }
5673 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005674
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005675 private void replacePackageLI(PackageParser.Package pkg,
5676 int parseFlags,
5677 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005678 String installerPackageName, PackageInstalledInfo res) {
5679
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005680 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005681 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005682 // First find the old package info and check signatures
5683 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005684 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005685 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005686 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005687 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5688 return;
5689 }
5690 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005691 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005692 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005693 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005694 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005695 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 }
5697 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005699 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005700 PackageParser.Package pkg,
5701 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005702 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005703 PackageParser.Package newPackage = null;
5704 String pkgName = deletedPackage.packageName;
5705 boolean deletedPkg = true;
5706 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005707
Jacek Surazski65e13172009-04-28 15:26:38 +02005708 String oldInstallerPackageName = null;
5709 synchronized (mPackages) {
5710 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5711 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005713 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005714 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005715 res.removedInfo)) {
5716 // If the existing package was'nt successfully deleted
5717 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5718 deletedPkg = false;
5719 } else {
5720 // Successfully deleted the old package. Now proceed with re-installation
5721 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005722 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005723 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005724 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005725 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5726 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005727 }
5728 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005729 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005730 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005731 res);
5732 updatedSettings = true;
5733 }
5734 }
5735
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005736 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005737 // remove package from internal structures. Note that we want deletePackageX to
5738 // delete the package data and cache directories that it created in
5739 // scanPackageLocked, unless those directories existed before we even tried to
5740 // install.
5741 if(updatedSettings) {
5742 deletePackageLI(
5743 pkgName, true,
5744 PackageManager.DONT_DELETE_DATA,
5745 res.removedInfo);
5746 }
5747 // Since we failed to install the new package we need to restore the old
5748 // package that we deleted.
5749 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005750 File restoreFile = new File(deletedPackage.mPath);
5751 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005752 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005753 return;
5754 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005755 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005756 boolean oldOnSd = isExternal(deletedPackage);
5757 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5758 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5759 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5760 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5761 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5762 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5763 return;
5764 }
5765 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005766 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005767 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005768 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005769 mSettings.writeLP();
5770 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005771 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005772 }
5773 }
5774 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005776 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005777 PackageParser.Package pkg,
5778 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005779 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005780 PackageParser.Package newPackage = null;
5781 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005782 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005783 PackageParser.PARSE_IS_SYSTEM;
5784 String packageName = deletedPackage.packageName;
5785 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5786 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005787 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005788 return;
5789 }
5790 PackageParser.Package oldPkg;
5791 PackageSetting oldPkgSetting;
5792 synchronized (mPackages) {
5793 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005794 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005795 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5796 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005797 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005798 return;
5799 }
5800 }
5801 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5802 res.removedInfo.removedPackage = packageName;
5803 // Remove existing system package
5804 removePackageLI(oldPkg, true);
5805 synchronized (mPackages) {
5806 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5807 }
5808
5809 // Successfully disabled the old package. Now proceed with re-installation
5810 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5811 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005812 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005813 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005814 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005815 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5816 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5817 }
5818 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005819 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005820 updatedSettings = true;
5821 }
5822
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005823 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005824 // Re installation failed. Restore old information
5825 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005826 if (newPackage != null) {
5827 removePackageLI(newPackage, true);
5828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005829 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005830 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005831 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005832 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005833 // Restore the old system information in Settings
5834 synchronized(mPackages) {
5835 if(updatedSettings) {
5836 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005837 mSettings.setInstallerPackageName(packageName,
5838 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005839 }
5840 mSettings.writeLP();
5841 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005842 } else {
5843 // If this is an update to an existing update, setup
5844 // to remove the existing update.
5845 synchronized (mPackages) {
5846 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5847 if (ps != null && ps.codePathString != null &&
5848 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
5849 int installFlags = 0;
5850 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
5851 oldPkgSetting.resourcePathString);
5852 }
5853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005854 }
5855 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005856
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005857 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005858 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005859 int retCode;
5860 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5861 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5862 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005863 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005864 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5865 }
5866 }
5867 return PackageManager.INSTALL_SUCCEEDED;
5868 }
5869
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005870 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005871 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005872 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005873 synchronized (mPackages) {
5874 //write settings. the installStatus will be incomplete at this stage.
5875 //note that the new package setting would have already been
5876 //added to mPackages. It hasn't been persisted yet.
5877 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5878 mSettings.writeLP();
5879 }
5880
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005881 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005882 != PackageManager.INSTALL_SUCCEEDED) {
5883 // Discontinue if moving dex files failed.
5884 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005885 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005886 if((res.returnCode = setPermissionsLI(newPackage))
5887 != PackageManager.INSTALL_SUCCEEDED) {
5888 if (mInstaller != null) {
5889 mInstaller.rmdex(newPackage.mScanPath);
5890 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005891 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005892 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005893 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005895 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005896 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005897 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005898 res.name = pkgName;
5899 res.uid = newPackage.applicationInfo.uid;
5900 res.pkg = newPackage;
5901 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005902 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005903 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5904 //to update install status
5905 mSettings.writeLP();
5906 }
5907 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005908
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005909 private void installPackageLI(InstallArgs args,
5910 boolean newInstall, PackageInstalledInfo res) {
5911 int pFlags = args.flags;
5912 String installerPackageName = args.installerPackageName;
5913 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005914 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005915 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005916 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005917 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005918 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005919 // Result object to be returned
5920 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5921
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005922 // Retrieve PackageSettings and parse package
5923 int parseFlags = PackageParser.PARSE_CHATTY |
5924 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5925 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5926 parseFlags |= mDefParseFlags;
5927 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5928 pp.setSeparateProcesses(mSeparateProcesses);
5929 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5930 null, mMetrics, parseFlags);
5931 if (pkg == null) {
5932 res.returnCode = pp.getParseError();
5933 return;
5934 }
5935 String pkgName = res.name = pkg.packageName;
5936 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5937 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5938 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5939 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005940 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005941 }
5942 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5943 res.returnCode = pp.getParseError();
5944 return;
5945 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005946 // Get rid of all references to package scan path via parser.
5947 pp = null;
5948 String oldCodePath = null;
5949 boolean systemApp = false;
5950 synchronized (mPackages) {
5951 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005952 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5953 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005954 if (pkg.mOriginalPackages != null
5955 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005956 && mPackages.containsKey(oldName)) {
5957 // This package is derived from an original package,
5958 // and this device has been updating from that original
5959 // name. We must continue using the original name, so
5960 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005961 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005962 pkgName = pkg.packageName;
5963 replace = true;
5964 } else if (mPackages.containsKey(pkgName)) {
5965 // This package, under its official name, already exists
5966 // on the device; we should replace it.
5967 replace = true;
5968 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005969 }
5970 PackageSetting ps = mSettings.mPackages.get(pkgName);
5971 if (ps != null) {
5972 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5973 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5974 systemApp = (ps.pkg.applicationInfo.flags &
5975 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005976 }
5977 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005978 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005979
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005980 if (systemApp && onSd) {
5981 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005982 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005983 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5984 return;
5985 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005986
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005987 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5988 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5989 return;
5990 }
5991 // Set application objects path explicitly after the rename
5992 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005993 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005994 replacePackageLI(pkg, parseFlags, scanMode,
5995 installerPackageName, res);
5996 } else {
5997 installNewPackageLI(pkg, parseFlags, scanMode,
5998 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005999 }
6000 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006001
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006002 private int setPermissionsLI(PackageParser.Package newPackage) {
6003 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006004 int retCode = 0;
6005 // TODO Gross hack but fix later. Ideally move this to be a post installation
6006 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006007 if ((newPackage.applicationInfo.flags
6008 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
6009 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006010 try {
6011 extractPublicFiles(newPackage, destResourceFile);
6012 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006013 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 -08006014 " forward-locked app.");
6015 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6016 } finally {
6017 //TODO clean up the extracted public files
6018 }
6019 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006020 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006021 newPackage.applicationInfo.uid);
6022 } else {
6023 final int filePermissions =
6024 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006025 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 newPackage.applicationInfo.uid);
6027 }
6028 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006029 // The permissions on the resource file was set when it was copied for
6030 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006033 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006034 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006035 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006036 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006037 // TODO Define new internal error
6038 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006039 }
6040 return PackageManager.INSTALL_SUCCEEDED;
6041 }
6042
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006043 private boolean isForwardLocked(PackageParser.Package pkg) {
6044 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006045 }
6046
Suchi Amalapurapuae181712010-03-30 14:01:02 -07006047 private boolean isExternal(PackageParser.Package pkg) {
6048 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
6049 }
6050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006051 private void extractPublicFiles(PackageParser.Package newPackage,
6052 File publicZipFile) throws IOException {
6053 final ZipOutputStream publicZipOutStream =
6054 new ZipOutputStream(new FileOutputStream(publicZipFile));
6055 final ZipFile privateZip = new ZipFile(newPackage.mPath);
6056
6057 // Copy manifest, resources.arsc and res directory to public zip
6058
6059 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
6060 while (privateZipEntries.hasMoreElements()) {
6061 final ZipEntry zipEntry = privateZipEntries.nextElement();
6062 final String zipEntryName = zipEntry.getName();
6063 if ("AndroidManifest.xml".equals(zipEntryName)
6064 || "resources.arsc".equals(zipEntryName)
6065 || zipEntryName.startsWith("res/")) {
6066 try {
6067 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
6068 } catch (IOException e) {
6069 try {
6070 publicZipOutStream.close();
6071 throw e;
6072 } finally {
6073 publicZipFile.delete();
6074 }
6075 }
6076 }
6077 }
6078
6079 publicZipOutStream.close();
6080 FileUtils.setPermissions(
6081 publicZipFile.getAbsolutePath(),
6082 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
6083 -1, -1);
6084 }
6085
6086 private static void copyZipEntry(ZipEntry zipEntry,
6087 ZipFile inZipFile,
6088 ZipOutputStream outZipStream) throws IOException {
6089 byte[] buffer = new byte[4096];
6090 int num;
6091
6092 ZipEntry newEntry;
6093 if (zipEntry.getMethod() == ZipEntry.STORED) {
6094 // Preserve the STORED method of the input entry.
6095 newEntry = new ZipEntry(zipEntry);
6096 } else {
6097 // Create a new entry so that the compressed len is recomputed.
6098 newEntry = new ZipEntry(zipEntry.getName());
6099 }
6100 outZipStream.putNextEntry(newEntry);
6101
6102 InputStream data = inZipFile.getInputStream(zipEntry);
6103 while ((num = data.read(buffer)) > 0) {
6104 outZipStream.write(buffer, 0, num);
6105 }
6106 outZipStream.flush();
6107 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006109 private void deleteTempPackageFiles() {
6110 FilenameFilter filter = new FilenameFilter() {
6111 public boolean accept(File dir, String name) {
6112 return name.startsWith("vmdl") && name.endsWith(".tmp");
6113 }
6114 };
6115 String tmpFilesList[] = mAppInstallDir.list(filter);
6116 if(tmpFilesList == null) {
6117 return;
6118 }
6119 for(int i = 0; i < tmpFilesList.length; i++) {
6120 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
6121 tmpFile.delete();
6122 }
6123 }
6124
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006125 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006126 File tmpPackageFile;
6127 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006128 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006129 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006130 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006131 return null;
6132 }
6133 try {
6134 FileUtils.setPermissions(
6135 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6136 -1, -1);
6137 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006138 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006139 return null;
6140 }
6141 return tmpPackageFile;
6142 }
6143
6144 public void deletePackage(final String packageName,
6145 final IPackageDeleteObserver observer,
6146 final int flags) {
6147 mContext.enforceCallingOrSelfPermission(
6148 android.Manifest.permission.DELETE_PACKAGES, null);
6149 // Queue up an async operation since the package deletion may take a little while.
6150 mHandler.post(new Runnable() {
6151 public void run() {
6152 mHandler.removeCallbacks(this);
6153 final boolean succeded = deletePackageX(packageName, true, true, flags);
6154 if (observer != null) {
6155 try {
6156 observer.packageDeleted(succeded);
6157 } catch (RemoteException e) {
6158 Log.i(TAG, "Observer no longer exists.");
6159 } //end catch
6160 } //end if
6161 } //end run
6162 });
6163 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006165 /**
6166 * This method is an internal method that could be get invoked either
6167 * to delete an installed package or to clean up a failed installation.
6168 * After deleting an installed package, a broadcast is sent to notify any
6169 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006170 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 * installation wouldn't have sent the initial broadcast either
6172 * The key steps in deleting a package are
6173 * deleting the package information in internal structures like mPackages,
6174 * deleting the packages base directories through installd
6175 * updating mSettings to reflect current status
6176 * persisting settings for later use
6177 * sending a broadcast if necessary
6178 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006179 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6180 boolean deleteCodeAndResources, int flags) {
6181 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006182 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006183
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006184 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6185 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6186 try {
6187 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006188 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006189 return false;
6190 }
6191 } catch (RemoteException e) {
6192 }
6193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006194 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006195 res = deletePackageLI(packageName, deleteCodeAndResources,
6196 flags | REMOVE_CHATTY, info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006200 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006201 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006202
6203 // If the removed package was a system update, the old system packaged
6204 // was re-enabled; we need to broadcast this information
6205 if (systemUpdate) {
6206 Bundle extras = new Bundle(1);
6207 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6208 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6209
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006210 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6211 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006213 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006214 // Force a gc here.
6215 Runtime.getRuntime().gc();
6216 // Delete the resources here after sending the broadcast to let
6217 // other processes clean up before deleting resources.
6218 if (info.args != null) {
6219 synchronized (mInstallLock) {
6220 info.args.doPostDeleteLI(deleteCodeAndResources);
6221 }
6222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006223 return res;
6224 }
6225
6226 static class PackageRemovedInfo {
6227 String removedPackage;
6228 int uid = -1;
6229 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006230 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006231 // Clean up resources deleted packages.
6232 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006233
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006234 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006235 Bundle extras = new Bundle(1);
6236 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6237 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6238 if (replacing) {
6239 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6240 }
6241 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006242 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006243 }
6244 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006245 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006246 }
6247 }
6248 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250 /*
6251 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6252 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006253 * 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 -08006254 * delete a partially installed application.
6255 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006256 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 int flags) {
6258 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006259 if (outInfo != null) {
6260 outInfo.removedPackage = packageName;
6261 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006262 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263 // Retrieve object to delete permissions for shared user later on
6264 PackageSetting deletedPs;
6265 synchronized (mPackages) {
6266 deletedPs = mSettings.mPackages.get(packageName);
6267 }
6268 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006269 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006270 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006271 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006272 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006273 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 + packageName + ", retcode=" + retCode);
6275 // we don't consider this to be a failure of the core package deletion
6276 }
6277 } else {
6278 //for emulator
6279 PackageParser.Package pkg = mPackages.get(packageName);
6280 File dataDir = new File(pkg.applicationInfo.dataDir);
6281 dataDir.delete();
6282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006283 }
6284 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006285 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006286 schedulePackageCleaning(packageName);
6287
6288 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6289 if (outInfo != null) {
6290 outInfo.removedUid = mSettings.removePackageLP(packageName);
6291 }
6292 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006293 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006294 if (deletedPs.sharedUser != null) {
6295 // remove permissions associated with package
6296 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6297 }
6298 }
6299 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006300 // remove from preferred activities.
6301 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6302 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6303 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6304 removed.add(pa);
6305 }
6306 }
6307 for (PreferredActivity pa : removed) {
6308 mSettings.mPreferredActivities.removeFilter(pa);
6309 }
6310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006311 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006312 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 }
6314 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006316 /*
6317 * Tries to delete system package.
6318 */
6319 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006320 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006321 ApplicationInfo applicationInfo = p.applicationInfo;
6322 //applicable for non-partially installed applications only
6323 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006324 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006325 return false;
6326 }
6327 PackageSetting ps = null;
6328 // Confirm if the system package has been updated
6329 // An updated system app can be deleted. This will also have to restore
6330 // the system pkg from system partition
6331 synchronized (mPackages) {
6332 ps = mSettings.getDisabledSystemPkg(p.packageName);
6333 }
6334 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006335 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 return false;
6337 } else {
6338 Log.i(TAG, "Deleting system pkg from data partition");
6339 }
6340 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006341 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006342 boolean deleteCodeAndResources = false;
6343 if (ps.versionCode < p.mVersionCode) {
6344 // Delete code and resources for downgrades
6345 deleteCodeAndResources = true;
6346 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6347 flags &= ~PackageManager.DONT_DELETE_DATA;
6348 }
6349 } else {
6350 // Preserve data by setting flag
6351 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6352 flags |= PackageManager.DONT_DELETE_DATA;
6353 }
6354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006355 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6356 if (!ret) {
6357 return false;
6358 }
6359 synchronized (mPackages) {
6360 // Reinstate the old system package
6361 mSettings.enableSystemPackageLP(p.packageName);
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07006362 // Remove any native libraries.
6363 removeNativeBinariesLI(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006364 }
6365 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006366 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006368 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006371 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006372 return false;
6373 }
6374 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006375 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006376 mSettings.writeLP();
6377 }
6378 return true;
6379 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006381 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6382 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6383 ApplicationInfo applicationInfo = p.applicationInfo;
6384 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006385 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006386 return false;
6387 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006388 if (outInfo != null) {
6389 outInfo.uid = applicationInfo.uid;
6390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391
6392 // Delete package data from internal structures and also remove data if flag is set
6393 removePackageDataLI(p, outInfo, flags);
6394
6395 // Delete application code and resources
6396 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006397 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006398 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006399 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006400 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6401 PackageManager.INSTALL_FORWARD_LOCK : 0;
6402 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006403 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 }
6405 return true;
6406 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006408 /*
6409 * This method handles package deletion in general
6410 */
6411 private boolean deletePackageLI(String packageName,
6412 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6413 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006414 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006415 return false;
6416 }
6417 PackageParser.Package p;
6418 boolean dataOnly = false;
6419 synchronized (mPackages) {
6420 p = mPackages.get(packageName);
6421 if (p == null) {
6422 //this retrieves partially installed apps
6423 dataOnly = true;
6424 PackageSetting ps = mSettings.mPackages.get(packageName);
6425 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006426 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006427 return false;
6428 }
6429 p = ps.pkg;
6430 }
6431 }
6432 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006433 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006434 return false;
6435 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006437 if (dataOnly) {
6438 // Delete application data first
6439 removePackageDataLI(p, outInfo, flags);
6440 return true;
6441 }
6442 // At this point the package should have ApplicationInfo associated with it
6443 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006444 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006445 return false;
6446 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006447 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006448 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6449 Log.i(TAG, "Removing system package:"+p.packageName);
6450 // When an updated system application is deleted we delete the existing resources as well and
6451 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006452 ret = deleteSystemPackageLI(p, flags, outInfo);
6453 } else {
6454 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006455 // Kill application pre-emptively especially for apps on sd.
6456 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006457 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006458 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006459 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006460 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 public void clearApplicationUserData(final String packageName,
6463 final IPackageDataObserver observer) {
6464 mContext.enforceCallingOrSelfPermission(
6465 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6466 // Queue up an async operation since the package deletion may take a little while.
6467 mHandler.post(new Runnable() {
6468 public void run() {
6469 mHandler.removeCallbacks(this);
6470 final boolean succeeded;
6471 synchronized (mInstallLock) {
6472 succeeded = clearApplicationUserDataLI(packageName);
6473 }
6474 if (succeeded) {
6475 // invoke DeviceStorageMonitor's update method to clear any notifications
6476 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6477 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6478 if (dsm != null) {
6479 dsm.updateMemory();
6480 }
6481 }
6482 if(observer != null) {
6483 try {
6484 observer.onRemoveCompleted(packageName, succeeded);
6485 } catch (RemoteException e) {
6486 Log.i(TAG, "Observer no longer exists.");
6487 }
6488 } //end if observer
6489 } //end run
6490 });
6491 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006493 private boolean clearApplicationUserDataLI(String packageName) {
6494 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006495 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006496 return false;
6497 }
6498 PackageParser.Package p;
6499 boolean dataOnly = false;
6500 synchronized (mPackages) {
6501 p = mPackages.get(packageName);
6502 if(p == null) {
6503 dataOnly = true;
6504 PackageSetting ps = mSettings.mPackages.get(packageName);
6505 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006506 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006507 return false;
6508 }
6509 p = ps.pkg;
6510 }
6511 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006512 boolean useEncryptedFSDir = false;
6513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006514 if(!dataOnly) {
6515 //need to check this only for fully installed applications
6516 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006517 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006518 return false;
6519 }
6520 final ApplicationInfo applicationInfo = p.applicationInfo;
6521 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006522 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006523 return false;
6524 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006525 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006526 }
6527 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006528 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006529 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006530 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531 + packageName);
6532 return false;
6533 }
6534 }
6535 return true;
6536 }
6537
6538 public void deleteApplicationCacheFiles(final String packageName,
6539 final IPackageDataObserver observer) {
6540 mContext.enforceCallingOrSelfPermission(
6541 android.Manifest.permission.DELETE_CACHE_FILES, null);
6542 // Queue up an async operation since the package deletion may take a little while.
6543 mHandler.post(new Runnable() {
6544 public void run() {
6545 mHandler.removeCallbacks(this);
6546 final boolean succeded;
6547 synchronized (mInstallLock) {
6548 succeded = deleteApplicationCacheFilesLI(packageName);
6549 }
6550 if(observer != null) {
6551 try {
6552 observer.onRemoveCompleted(packageName, succeded);
6553 } catch (RemoteException e) {
6554 Log.i(TAG, "Observer no longer exists.");
6555 }
6556 } //end if observer
6557 } //end run
6558 });
6559 }
6560
6561 private boolean deleteApplicationCacheFilesLI(String packageName) {
6562 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006563 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006564 return false;
6565 }
6566 PackageParser.Package p;
6567 synchronized (mPackages) {
6568 p = mPackages.get(packageName);
6569 }
6570 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006571 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006572 return false;
6573 }
6574 final ApplicationInfo applicationInfo = p.applicationInfo;
6575 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006576 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006577 return false;
6578 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006579 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006580 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006581 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006582 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006583 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006584 + packageName);
6585 return false;
6586 }
6587 }
6588 return true;
6589 }
6590
6591 public void getPackageSizeInfo(final String packageName,
6592 final IPackageStatsObserver observer) {
6593 mContext.enforceCallingOrSelfPermission(
6594 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6595 // Queue up an async operation since the package deletion may take a little while.
6596 mHandler.post(new Runnable() {
6597 public void run() {
6598 mHandler.removeCallbacks(this);
6599 PackageStats lStats = new PackageStats(packageName);
6600 final boolean succeded;
6601 synchronized (mInstallLock) {
6602 succeded = getPackageSizeInfoLI(packageName, lStats);
6603 }
6604 if(observer != null) {
6605 try {
6606 observer.onGetStatsCompleted(lStats, succeded);
6607 } catch (RemoteException e) {
6608 Log.i(TAG, "Observer no longer exists.");
6609 }
6610 } //end if observer
6611 } //end run
6612 });
6613 }
6614
6615 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6616 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006617 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006618 return false;
6619 }
6620 PackageParser.Package p;
6621 boolean dataOnly = false;
6622 synchronized (mPackages) {
6623 p = mPackages.get(packageName);
6624 if(p == null) {
6625 dataOnly = true;
6626 PackageSetting ps = mSettings.mPackages.get(packageName);
6627 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006628 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006629 return false;
6630 }
6631 p = ps.pkg;
6632 }
6633 }
6634 String publicSrcDir = null;
6635 if(!dataOnly) {
6636 final ApplicationInfo applicationInfo = p.applicationInfo;
6637 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006638 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006639 return false;
6640 }
6641 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6642 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006643 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006644 if (mInstaller != null) {
6645 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006646 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006647 if (res < 0) {
6648 return false;
6649 } else {
6650 return true;
6651 }
6652 }
6653 return true;
6654 }
6655
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006657 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006658 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006659 }
6660
6661 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006662 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006663 }
6664
6665 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006666 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 }
6668
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006669 int getUidTargetSdkVersionLockedLP(int uid) {
6670 Object obj = mSettings.getUserIdLP(uid);
6671 if (obj instanceof SharedUserSetting) {
6672 SharedUserSetting sus = (SharedUserSetting)obj;
6673 final int N = sus.packages.size();
6674 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6675 Iterator<PackageSetting> it = sus.packages.iterator();
6676 int i=0;
6677 while (it.hasNext()) {
6678 PackageSetting ps = it.next();
6679 if (ps.pkg != null) {
6680 int v = ps.pkg.applicationInfo.targetSdkVersion;
6681 if (v < vers) vers = v;
6682 }
6683 }
6684 return vers;
6685 } else if (obj instanceof PackageSetting) {
6686 PackageSetting ps = (PackageSetting)obj;
6687 if (ps.pkg != null) {
6688 return ps.pkg.applicationInfo.targetSdkVersion;
6689 }
6690 }
6691 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6692 }
6693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006694 public void addPreferredActivity(IntentFilter filter, int match,
6695 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006696 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006697 if (mContext.checkCallingOrSelfPermission(
6698 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6699 != PackageManager.PERMISSION_GRANTED) {
6700 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6701 < Build.VERSION_CODES.FROYO) {
6702 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6703 + Binder.getCallingUid());
6704 return;
6705 }
6706 mContext.enforceCallingOrSelfPermission(
6707 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6708 }
6709
6710 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006711 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6712 mSettings.mPreferredActivities.addFilter(
6713 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006714 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006715 }
6716 }
6717
Satish Sampath8dbe6122009-06-02 23:35:54 +01006718 public void replacePreferredActivity(IntentFilter filter, int match,
6719 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006720 if (filter.countActions() != 1) {
6721 throw new IllegalArgumentException(
6722 "replacePreferredActivity expects filter to have only 1 action.");
6723 }
6724 if (filter.countCategories() != 1) {
6725 throw new IllegalArgumentException(
6726 "replacePreferredActivity expects filter to have only 1 category.");
6727 }
6728 if (filter.countDataAuthorities() != 0
6729 || filter.countDataPaths() != 0
6730 || filter.countDataSchemes() != 0
6731 || filter.countDataTypes() != 0) {
6732 throw new IllegalArgumentException(
6733 "replacePreferredActivity expects filter to have no data authorities, " +
6734 "paths, schemes or types.");
6735 }
6736 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006737 if (mContext.checkCallingOrSelfPermission(
6738 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6739 != PackageManager.PERMISSION_GRANTED) {
6740 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6741 < Build.VERSION_CODES.FROYO) {
6742 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6743 + Binder.getCallingUid());
6744 return;
6745 }
6746 mContext.enforceCallingOrSelfPermission(
6747 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6748 }
6749
Satish Sampath8dbe6122009-06-02 23:35:54 +01006750 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6751 String action = filter.getAction(0);
6752 String category = filter.getCategory(0);
6753 while (it.hasNext()) {
6754 PreferredActivity pa = it.next();
6755 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6756 it.remove();
6757 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6758 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6759 }
6760 }
6761 addPreferredActivity(filter, match, set, activity);
6762 }
6763 }
6764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006765 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006766 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006767 int uid = Binder.getCallingUid();
6768 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006769 if (pkg == null || pkg.applicationInfo.uid != uid) {
6770 if (mContext.checkCallingOrSelfPermission(
6771 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6772 != PackageManager.PERMISSION_GRANTED) {
6773 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6774 < Build.VERSION_CODES.FROYO) {
6775 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6776 + Binder.getCallingUid());
6777 return;
6778 }
6779 mContext.enforceCallingOrSelfPermission(
6780 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6781 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006782 }
6783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006784 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006785 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006786 }
6787 }
6788 }
6789
6790 boolean clearPackagePreferredActivitiesLP(String packageName) {
6791 boolean changed = false;
6792 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6793 while (it.hasNext()) {
6794 PreferredActivity pa = it.next();
6795 if (pa.mActivity.getPackageName().equals(packageName)) {
6796 it.remove();
6797 changed = true;
6798 }
6799 }
6800 return changed;
6801 }
6802
6803 public int getPreferredActivities(List<IntentFilter> outFilters,
6804 List<ComponentName> outActivities, String packageName) {
6805
6806 int num = 0;
6807 synchronized (mPackages) {
6808 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6809 while (it.hasNext()) {
6810 PreferredActivity pa = it.next();
6811 if (packageName == null
6812 || pa.mActivity.getPackageName().equals(packageName)) {
6813 if (outFilters != null) {
6814 outFilters.add(new IntentFilter(pa));
6815 }
6816 if (outActivities != null) {
6817 outActivities.add(pa.mActivity);
6818 }
6819 }
6820 }
6821 }
6822
6823 return num;
6824 }
6825
6826 public void setApplicationEnabledSetting(String appPackageName,
6827 int newState, int flags) {
6828 setEnabledSetting(appPackageName, null, newState, flags);
6829 }
6830
6831 public void setComponentEnabledSetting(ComponentName componentName,
6832 int newState, int flags) {
6833 setEnabledSetting(componentName.getPackageName(),
6834 componentName.getClassName(), newState, flags);
6835 }
6836
6837 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006838 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006839 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6840 || newState == COMPONENT_ENABLED_STATE_ENABLED
6841 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6842 throw new IllegalArgumentException("Invalid new component state: "
6843 + newState);
6844 }
6845 PackageSetting pkgSetting;
6846 final int uid = Binder.getCallingUid();
6847 final int permission = mContext.checkCallingPermission(
6848 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6849 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006850 boolean sendNow = false;
6851 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006852 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006853 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006854 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006855 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006856 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006857 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006858 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006859 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006860 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006861 }
6862 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006863 "Unknown component: " + packageName
6864 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006865 }
6866 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6867 throw new SecurityException(
6868 "Permission Denial: attempt to change component state from pid="
6869 + Binder.getCallingPid()
6870 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6871 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006872 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006873 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006874 if (pkgSetting.enabled == newState) {
6875 // Nothing to do
6876 return;
6877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006878 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006879 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006880 } else {
6881 // We're dealing with a component level state change
6882 switch (newState) {
6883 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006884 if (!pkgSetting.enableComponentLP(className)) {
6885 return;
6886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006887 break;
6888 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006889 if (!pkgSetting.disableComponentLP(className)) {
6890 return;
6891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006892 break;
6893 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006894 if (!pkgSetting.restoreComponentLP(className)) {
6895 return;
6896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006897 break;
6898 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006899 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006900 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006901 }
6902 }
6903 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006904 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006905 components = mPendingBroadcasts.get(packageName);
6906 boolean newPackage = components == null;
6907 if (newPackage) {
6908 components = new ArrayList<String>();
6909 }
6910 if (!components.contains(componentName)) {
6911 components.add(componentName);
6912 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006913 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6914 sendNow = true;
6915 // Purge entry from pending broadcast list if another one exists already
6916 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006917 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006918 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006919 if (newPackage) {
6920 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006921 }
6922 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6923 // Schedule a message
6924 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6925 }
6926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006927 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006929 long callingId = Binder.clearCallingIdentity();
6930 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006931 if (sendNow) {
6932 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006933 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006935 } finally {
6936 Binder.restoreCallingIdentity(callingId);
6937 }
6938 }
6939
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006940 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006941 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6942 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6943 + " components=" + componentNames);
6944 Bundle extras = new Bundle(4);
6945 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6946 String nameList[] = new String[componentNames.size()];
6947 componentNames.toArray(nameList);
6948 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006949 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6950 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006951 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006952 }
6953
Jacek Surazski65e13172009-04-28 15:26:38 +02006954 public String getInstallerPackageName(String packageName) {
6955 synchronized (mPackages) {
6956 PackageSetting pkg = mSettings.mPackages.get(packageName);
6957 if (pkg == null) {
6958 throw new IllegalArgumentException("Unknown package: " + packageName);
6959 }
6960 return pkg.installerPackageName;
6961 }
6962 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006964 public int getApplicationEnabledSetting(String appPackageName) {
6965 synchronized (mPackages) {
6966 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6967 if (pkg == null) {
6968 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6969 }
6970 return pkg.enabled;
6971 }
6972 }
6973
6974 public int getComponentEnabledSetting(ComponentName componentName) {
6975 synchronized (mPackages) {
6976 final String packageNameStr = componentName.getPackageName();
6977 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6978 if (pkg == null) {
6979 throw new IllegalArgumentException("Unknown component: " + componentName);
6980 }
6981 final String classNameStr = componentName.getClassName();
6982 return pkg.currentEnabledStateLP(classNameStr);
6983 }
6984 }
6985
6986 public void enterSafeMode() {
6987 if (!mSystemReady) {
6988 mSafeMode = true;
6989 }
6990 }
6991
6992 public void systemReady() {
6993 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006994
6995 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006996 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006997 mContext.getContentResolver(),
6998 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006999 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007000 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07007001 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007003 }
7004
7005 public boolean isSafeMode() {
7006 return mSafeMode;
7007 }
7008
7009 public boolean hasSystemUidErrors() {
7010 return mHasSystemUidErrors;
7011 }
7012
7013 static String arrayToString(int[] array) {
7014 StringBuffer buf = new StringBuffer(128);
7015 buf.append('[');
7016 if (array != null) {
7017 for (int i=0; i<array.length; i++) {
7018 if (i > 0) buf.append(", ");
7019 buf.append(array[i]);
7020 }
7021 }
7022 buf.append(']');
7023 return buf.toString();
7024 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007026 @Override
7027 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
7028 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
7029 != PackageManager.PERMISSION_GRANTED) {
7030 pw.println("Permission Denial: can't dump ActivityManager from from pid="
7031 + Binder.getCallingPid()
7032 + ", uid=" + Binder.getCallingUid()
7033 + " without permission "
7034 + android.Manifest.permission.DUMP);
7035 return;
7036 }
7037
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007038 String packageName = null;
7039
7040 int opti = 0;
7041 while (opti < args.length) {
7042 String opt = args[opti];
7043 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
7044 break;
7045 }
7046 opti++;
7047 if ("-a".equals(opt)) {
7048 // Right now we only know how to print all.
7049 } else if ("-h".equals(opt)) {
7050 pw.println("Package manager dump options:");
7051 pw.println(" [-h] [cmd] ...");
7052 pw.println(" cmd may be one of:");
7053 pw.println(" [package.name]: info about given package");
7054 return;
7055 } else {
7056 pw.println("Unknown argument: " + opt + "; use -h for help");
7057 }
7058 }
7059
7060 // Is the caller requesting to dump a particular piece of data?
7061 if (opti < args.length) {
7062 String cmd = args[opti];
7063 opti++;
7064 // Is this a package name?
7065 if ("android".equals(cmd) || cmd.contains(".")) {
7066 packageName = cmd;
7067 }
7068 }
7069
7070 boolean printedTitle = false;
7071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007072 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007073 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
7074 printedTitle = true;
7075 }
7076 if (mReceivers.dump(pw, printedTitle
7077 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
7078 " ", packageName)) {
7079 printedTitle = true;
7080 }
7081 if (mServices.dump(pw, printedTitle
7082 ? "\nService Resolver Table:" : "Service Resolver Table:",
7083 " ", packageName)) {
7084 printedTitle = true;
7085 }
7086 if (mSettings.mPreferredActivities.dump(pw, printedTitle
7087 ? "\nPreferred Activities:" : "Preferred Activities:",
7088 " ", packageName)) {
7089 printedTitle = true;
7090 }
7091 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007092 {
7093 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007094 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7095 continue;
7096 }
7097 if (!printedSomething) {
7098 if (printedTitle) pw.println(" ");
7099 pw.println("Permissions:");
7100 printedSomething = true;
7101 printedTitle = true;
7102 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007103 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7104 pw.print(Integer.toHexString(System.identityHashCode(p)));
7105 pw.println("):");
7106 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7107 pw.print(" uid="); pw.print(p.uid);
7108 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007109 pw.print(" type="); pw.print(p.type);
7110 pw.print(" prot="); pw.println(p.protectionLevel);
7111 if (p.packageSetting != null) {
7112 pw.print(" packageSetting="); pw.println(p.packageSetting);
7113 }
7114 if (p.perm != null) {
7115 pw.print(" perm="); pw.println(p.perm);
7116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007117 }
7118 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007119 printedSomething = false;
7120 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007121 {
7122 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007123 if (packageName != null && !packageName.equals(ps.realName)
7124 && !packageName.equals(ps.name)) {
7125 continue;
7126 }
7127 if (!printedSomething) {
7128 if (printedTitle) pw.println(" ");
7129 pw.println("Packages:");
7130 printedSomething = true;
7131 printedTitle = true;
7132 }
7133 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007134 pw.print(" Package [");
7135 pw.print(ps.realName != null ? ps.realName : ps.name);
7136 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007137 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7138 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007139 if (ps.realName != null) {
7140 pw.print(" compat name="); pw.println(ps.name);
7141 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007142 pw.print(" userId="); pw.print(ps.userId);
7143 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7144 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7145 pw.print(" pkg="); pw.println(ps.pkg);
7146 pw.print(" codePath="); pw.println(ps.codePathString);
7147 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07007148 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007149 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007150 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007151 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007152 pw.print(" supportsScreens=[");
7153 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007154 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007155 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7156 if (!first) pw.print(", ");
7157 first = false;
7158 pw.print("small");
7159 }
7160 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007161 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007162 if (!first) pw.print(", ");
7163 first = false;
7164 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007165 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007166 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007167 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007168 if (!first) pw.print(", ");
7169 first = false;
7170 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007171 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007172 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007173 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007174 if (!first) pw.print(", ");
7175 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007176 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007177 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007178 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007179 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007180 if (!first) pw.print(", ");
7181 first = false;
7182 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007183 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007184 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007185 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7186 if (!first) pw.print(", ");
7187 first = false;
7188 pw.print("anyDensity");
7189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007190 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007191 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007192 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7193 pw.print(" signatures="); pw.println(ps.signatures);
7194 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007195 pw.print(" haveGids="); pw.println(ps.haveGids);
7196 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007197 pw.print(" installStatus="); pw.print(ps.installStatus);
7198 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007199 if (ps.disabledComponents.size() > 0) {
7200 pw.println(" disabledComponents:");
7201 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007202 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007203 }
7204 }
7205 if (ps.enabledComponents.size() > 0) {
7206 pw.println(" enabledComponents:");
7207 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007208 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007209 }
7210 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007211 if (ps.grantedPermissions.size() > 0) {
7212 pw.println(" grantedPermissions:");
7213 for (String s : ps.grantedPermissions) {
7214 pw.print(" "); pw.println(s);
7215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007217 }
7218 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007219 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007220 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007221 for (HashMap.Entry<String, String> e
7222 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007223 if (packageName != null && !packageName.equals(e.getKey())
7224 && !packageName.equals(e.getValue())) {
7225 continue;
7226 }
7227 if (!printedSomething) {
7228 if (printedTitle) pw.println(" ");
7229 pw.println("Renamed packages:");
7230 printedSomething = true;
7231 printedTitle = true;
7232 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007233 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7234 pw.println(e.getValue());
7235 }
7236 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007237 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007238 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007239 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007240 if (packageName != null && !packageName.equals(ps.realName)
7241 && !packageName.equals(ps.name)) {
7242 continue;
7243 }
7244 if (!printedSomething) {
7245 if (printedTitle) pw.println(" ");
7246 pw.println("Hidden system packages:");
7247 printedSomething = true;
7248 printedTitle = true;
7249 }
7250 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007251 pw.print(ps.realName != null ? ps.realName : ps.name);
7252 pw.print("] (");
7253 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7254 pw.println("):");
7255 if (ps.realName != null) {
7256 pw.print(" compat name="); pw.println(ps.name);
7257 }
7258 pw.print(" userId="); pw.println(ps.userId);
7259 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7260 pw.print(" codePath="); pw.println(ps.codePathString);
7261 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7262 }
7263 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007264 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007265 {
7266 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007267 if (packageName != null && su != packageSharedUser) {
7268 continue;
7269 }
7270 if (!printedSomething) {
7271 if (printedTitle) pw.println(" ");
7272 pw.println("Shared users:");
7273 printedSomething = true;
7274 printedTitle = true;
7275 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007276 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7277 pw.print(Integer.toHexString(System.identityHashCode(su)));
7278 pw.println("):");
7279 pw.print(" userId="); pw.print(su.userId);
7280 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007281 pw.println(" grantedPermissions:");
7282 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007283 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007285 }
7286 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007287
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007288 if (packageName == null) {
7289 if (printedTitle) pw.println(" ");
7290 printedTitle = true;
7291 pw.println("Settings parse messages:");
7292 pw.println(mSettings.mReadMessages.toString());
7293
7294 pw.println(" ");
7295 pw.println("Package warning messages:");
7296 File fname = getSettingsProblemFile();
7297 FileInputStream in;
7298 try {
7299 in = new FileInputStream(fname);
7300 int avail = in.available();
7301 byte[] data = new byte[avail];
7302 in.read(data);
7303 pw.println(new String(data));
7304 } catch (FileNotFoundException e) {
7305 } catch (IOException e) {
7306 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007308 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007309
7310 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007311 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007312 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007313 if (packageName != null && !packageName.equals(p.info.packageName)) {
7314 continue;
7315 }
7316 if (!printedSomething) {
7317 if (printedTitle) pw.println(" ");
7318 pw.println("Registered ContentProviders:");
7319 printedSomething = true;
7320 printedTitle = true;
7321 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007322 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007323 pw.println(p.toString());
7324 }
7325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007326 }
7327
7328 static final class BasePermission {
7329 final static int TYPE_NORMAL = 0;
7330 final static int TYPE_BUILTIN = 1;
7331 final static int TYPE_DYNAMIC = 2;
7332
7333 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007334 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007335 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007336 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007337 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007338 PackageParser.Permission perm;
7339 PermissionInfo pendingInfo;
7340 int uid;
7341 int[] gids;
7342
7343 BasePermission(String _name, String _sourcePackage, int _type) {
7344 name = _name;
7345 sourcePackage = _sourcePackage;
7346 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007347 // Default to most conservative protection level.
7348 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7349 }
7350
7351 public String toString() {
7352 return "BasePermission{"
7353 + Integer.toHexString(System.identityHashCode(this))
7354 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007355 }
7356 }
7357
7358 static class PackageSignatures {
7359 private Signature[] mSignatures;
7360
7361 PackageSignatures(Signature[] sigs) {
7362 assignSignatures(sigs);
7363 }
7364
7365 PackageSignatures() {
7366 }
7367
7368 void writeXml(XmlSerializer serializer, String tagName,
7369 ArrayList<Signature> pastSignatures) throws IOException {
7370 if (mSignatures == null) {
7371 return;
7372 }
7373 serializer.startTag(null, tagName);
7374 serializer.attribute(null, "count",
7375 Integer.toString(mSignatures.length));
7376 for (int i=0; i<mSignatures.length; i++) {
7377 serializer.startTag(null, "cert");
7378 final Signature sig = mSignatures[i];
7379 final int sigHash = sig.hashCode();
7380 final int numPast = pastSignatures.size();
7381 int j;
7382 for (j=0; j<numPast; j++) {
7383 Signature pastSig = pastSignatures.get(j);
7384 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7385 serializer.attribute(null, "index", Integer.toString(j));
7386 break;
7387 }
7388 }
7389 if (j >= numPast) {
7390 pastSignatures.add(sig);
7391 serializer.attribute(null, "index", Integer.toString(numPast));
7392 serializer.attribute(null, "key", sig.toCharsString());
7393 }
7394 serializer.endTag(null, "cert");
7395 }
7396 serializer.endTag(null, tagName);
7397 }
7398
7399 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7400 throws IOException, XmlPullParserException {
7401 String countStr = parser.getAttributeValue(null, "count");
7402 if (countStr == null) {
7403 reportSettingsProblem(Log.WARN,
7404 "Error in package manager settings: <signatures> has"
7405 + " no count at " + parser.getPositionDescription());
7406 XmlUtils.skipCurrentTag(parser);
7407 }
7408 final int count = Integer.parseInt(countStr);
7409 mSignatures = new Signature[count];
7410 int pos = 0;
7411
7412 int outerDepth = parser.getDepth();
7413 int type;
7414 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7415 && (type != XmlPullParser.END_TAG
7416 || parser.getDepth() > outerDepth)) {
7417 if (type == XmlPullParser.END_TAG
7418 || type == XmlPullParser.TEXT) {
7419 continue;
7420 }
7421
7422 String tagName = parser.getName();
7423 if (tagName.equals("cert")) {
7424 if (pos < count) {
7425 String index = parser.getAttributeValue(null, "index");
7426 if (index != null) {
7427 try {
7428 int idx = Integer.parseInt(index);
7429 String key = parser.getAttributeValue(null, "key");
7430 if (key == null) {
7431 if (idx >= 0 && idx < pastSignatures.size()) {
7432 Signature sig = pastSignatures.get(idx);
7433 if (sig != null) {
7434 mSignatures[pos] = pastSignatures.get(idx);
7435 pos++;
7436 } else {
7437 reportSettingsProblem(Log.WARN,
7438 "Error in package manager settings: <cert> "
7439 + "index " + index + " is not defined at "
7440 + parser.getPositionDescription());
7441 }
7442 } else {
7443 reportSettingsProblem(Log.WARN,
7444 "Error in package manager settings: <cert> "
7445 + "index " + index + " is out of bounds at "
7446 + parser.getPositionDescription());
7447 }
7448 } else {
7449 while (pastSignatures.size() <= idx) {
7450 pastSignatures.add(null);
7451 }
7452 Signature sig = new Signature(key);
7453 pastSignatures.set(idx, sig);
7454 mSignatures[pos] = sig;
7455 pos++;
7456 }
7457 } catch (NumberFormatException e) {
7458 reportSettingsProblem(Log.WARN,
7459 "Error in package manager settings: <cert> "
7460 + "index " + index + " is not a number at "
7461 + parser.getPositionDescription());
7462 }
7463 } else {
7464 reportSettingsProblem(Log.WARN,
7465 "Error in package manager settings: <cert> has"
7466 + " no index at " + parser.getPositionDescription());
7467 }
7468 } else {
7469 reportSettingsProblem(Log.WARN,
7470 "Error in package manager settings: too "
7471 + "many <cert> tags, expected " + count
7472 + " at " + parser.getPositionDescription());
7473 }
7474 } else {
7475 reportSettingsProblem(Log.WARN,
7476 "Unknown element under <cert>: "
7477 + parser.getName());
7478 }
7479 XmlUtils.skipCurrentTag(parser);
7480 }
7481
7482 if (pos < count) {
7483 // Should never happen -- there is an error in the written
7484 // settings -- but if it does we don't want to generate
7485 // a bad array.
7486 Signature[] newSigs = new Signature[pos];
7487 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7488 mSignatures = newSigs;
7489 }
7490 }
7491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007492 private void assignSignatures(Signature[] sigs) {
7493 if (sigs == null) {
7494 mSignatures = null;
7495 return;
7496 }
7497 mSignatures = new Signature[sigs.length];
7498 for (int i=0; i<sigs.length; i++) {
7499 mSignatures[i] = sigs[i];
7500 }
7501 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007503 @Override
7504 public String toString() {
7505 StringBuffer buf = new StringBuffer(128);
7506 buf.append("PackageSignatures{");
7507 buf.append(Integer.toHexString(System.identityHashCode(this)));
7508 buf.append(" [");
7509 if (mSignatures != null) {
7510 for (int i=0; i<mSignatures.length; i++) {
7511 if (i > 0) buf.append(", ");
7512 buf.append(Integer.toHexString(
7513 System.identityHashCode(mSignatures[i])));
7514 }
7515 }
7516 buf.append("]}");
7517 return buf.toString();
7518 }
7519 }
7520
7521 static class PreferredActivity extends IntentFilter {
7522 final int mMatch;
7523 final String[] mSetPackages;
7524 final String[] mSetClasses;
7525 final String[] mSetComponents;
7526 final ComponentName mActivity;
7527 final String mShortActivity;
7528 String mParseError;
7529
7530 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7531 ComponentName activity) {
7532 super(filter);
7533 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7534 mActivity = activity;
7535 mShortActivity = activity.flattenToShortString();
7536 mParseError = null;
7537 if (set != null) {
7538 final int N = set.length;
7539 String[] myPackages = new String[N];
7540 String[] myClasses = new String[N];
7541 String[] myComponents = new String[N];
7542 for (int i=0; i<N; i++) {
7543 ComponentName cn = set[i];
7544 if (cn == null) {
7545 mSetPackages = null;
7546 mSetClasses = null;
7547 mSetComponents = null;
7548 return;
7549 }
7550 myPackages[i] = cn.getPackageName().intern();
7551 myClasses[i] = cn.getClassName().intern();
7552 myComponents[i] = cn.flattenToShortString().intern();
7553 }
7554 mSetPackages = myPackages;
7555 mSetClasses = myClasses;
7556 mSetComponents = myComponents;
7557 } else {
7558 mSetPackages = null;
7559 mSetClasses = null;
7560 mSetComponents = null;
7561 }
7562 }
7563
7564 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7565 IOException {
7566 mShortActivity = parser.getAttributeValue(null, "name");
7567 mActivity = ComponentName.unflattenFromString(mShortActivity);
7568 if (mActivity == null) {
7569 mParseError = "Bad activity name " + mShortActivity;
7570 }
7571 String matchStr = parser.getAttributeValue(null, "match");
7572 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7573 String setCountStr = parser.getAttributeValue(null, "set");
7574 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7575
7576 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7577 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7578 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7579
7580 int setPos = 0;
7581
7582 int outerDepth = parser.getDepth();
7583 int type;
7584 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7585 && (type != XmlPullParser.END_TAG
7586 || parser.getDepth() > outerDepth)) {
7587 if (type == XmlPullParser.END_TAG
7588 || type == XmlPullParser.TEXT) {
7589 continue;
7590 }
7591
7592 String tagName = parser.getName();
7593 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7594 // + parser.getDepth() + " tag=" + tagName);
7595 if (tagName.equals("set")) {
7596 String name = parser.getAttributeValue(null, "name");
7597 if (name == null) {
7598 if (mParseError == null) {
7599 mParseError = "No name in set tag in preferred activity "
7600 + mShortActivity;
7601 }
7602 } else if (setPos >= setCount) {
7603 if (mParseError == null) {
7604 mParseError = "Too many set tags in preferred activity "
7605 + mShortActivity;
7606 }
7607 } else {
7608 ComponentName cn = ComponentName.unflattenFromString(name);
7609 if (cn == null) {
7610 if (mParseError == null) {
7611 mParseError = "Bad set name " + name + " in preferred activity "
7612 + mShortActivity;
7613 }
7614 } else {
7615 myPackages[setPos] = cn.getPackageName();
7616 myClasses[setPos] = cn.getClassName();
7617 myComponents[setPos] = name;
7618 setPos++;
7619 }
7620 }
7621 XmlUtils.skipCurrentTag(parser);
7622 } else if (tagName.equals("filter")) {
7623 //Log.i(TAG, "Starting to parse filter...");
7624 readFromXml(parser);
7625 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7626 // + parser.getDepth() + " tag=" + parser.getName());
7627 } else {
7628 reportSettingsProblem(Log.WARN,
7629 "Unknown element under <preferred-activities>: "
7630 + parser.getName());
7631 XmlUtils.skipCurrentTag(parser);
7632 }
7633 }
7634
7635 if (setPos != setCount) {
7636 if (mParseError == null) {
7637 mParseError = "Not enough set tags (expected " + setCount
7638 + " but found " + setPos + ") in " + mShortActivity;
7639 }
7640 }
7641
7642 mSetPackages = myPackages;
7643 mSetClasses = myClasses;
7644 mSetComponents = myComponents;
7645 }
7646
7647 public void writeToXml(XmlSerializer serializer) throws IOException {
7648 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7649 serializer.attribute(null, "name", mShortActivity);
7650 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7651 serializer.attribute(null, "set", Integer.toString(NS));
7652 for (int s=0; s<NS; s++) {
7653 serializer.startTag(null, "set");
7654 serializer.attribute(null, "name", mSetComponents[s]);
7655 serializer.endTag(null, "set");
7656 }
7657 serializer.startTag(null, "filter");
7658 super.writeToXml(serializer);
7659 serializer.endTag(null, "filter");
7660 }
7661
7662 boolean sameSet(List<ResolveInfo> query, int priority) {
7663 if (mSetPackages == null) return false;
7664 final int NQ = query.size();
7665 final int NS = mSetPackages.length;
7666 int numMatch = 0;
7667 for (int i=0; i<NQ; i++) {
7668 ResolveInfo ri = query.get(i);
7669 if (ri.priority != priority) continue;
7670 ActivityInfo ai = ri.activityInfo;
7671 boolean good = false;
7672 for (int j=0; j<NS; j++) {
7673 if (mSetPackages[j].equals(ai.packageName)
7674 && mSetClasses[j].equals(ai.name)) {
7675 numMatch++;
7676 good = true;
7677 break;
7678 }
7679 }
7680 if (!good) return false;
7681 }
7682 return numMatch == NS;
7683 }
7684 }
7685
7686 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007687 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007689 HashSet<String> grantedPermissions = new HashSet<String>();
7690 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007692 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007693 setFlags(pkgFlags);
7694 }
7695
7696 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007697 this.pkgFlags = pkgFlags & (
7698 ApplicationInfo.FLAG_SYSTEM |
7699 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007700 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007701 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007702 }
7703 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007705 /**
7706 * Settings base class for pending and resolved classes.
7707 */
7708 static class PackageSettingBase extends GrantedPermissions {
7709 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007710 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007711 File codePath;
7712 String codePathString;
7713 File resourcePath;
7714 String resourcePathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007715 String obbPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007716 private long timeStamp;
7717 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007718 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007719
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007720 boolean uidError;
7721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007722 PackageSignatures signatures = new PackageSignatures();
7723
7724 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007725 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007727 /* Explicitly disabled components */
7728 HashSet<String> disabledComponents = new HashSet<String>(0);
7729 /* Explicitly enabled components */
7730 HashSet<String> enabledComponents = new HashSet<String>(0);
7731 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7732 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007733
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007734 PackageSettingBase origPackage;
7735
Jacek Surazski65e13172009-04-28 15:26:38 +02007736 /* package name of the app that installed this package */
7737 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007738
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007739 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007740 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007741 super(pkgFlags);
7742 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007743 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007744 init(codePath, resourcePath, pVersionCode);
7745 }
7746
7747 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007748 this.codePath = codePath;
7749 this.codePathString = codePath.toString();
7750 this.resourcePath = resourcePath;
7751 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007752 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007753 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007754
Jacek Surazski65e13172009-04-28 15:26:38 +02007755 public void setInstallerPackageName(String packageName) {
7756 installerPackageName = packageName;
7757 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007758
Jacek Surazski65e13172009-04-28 15:26:38 +02007759 String getInstallerPackageName() {
7760 return installerPackageName;
7761 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007763 public void setInstallStatus(int newStatus) {
7764 installStatus = newStatus;
7765 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007767 public int getInstallStatus() {
7768 return installStatus;
7769 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007771 public void setTimeStamp(long newStamp) {
7772 if (newStamp != timeStamp) {
7773 timeStamp = newStamp;
7774 timeStampString = Long.toString(newStamp);
7775 }
7776 }
7777
7778 public void setTimeStamp(long newStamp, String newStampStr) {
7779 timeStamp = newStamp;
7780 timeStampString = newStampStr;
7781 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007783 public long getTimeStamp() {
7784 return timeStamp;
7785 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007787 public String getTimeStampStr() {
7788 return timeStampString;
7789 }
7790
7791 public void copyFrom(PackageSettingBase base) {
7792 grantedPermissions = base.grantedPermissions;
7793 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007795 timeStamp = base.timeStamp;
7796 timeStampString = base.timeStampString;
7797 signatures = base.signatures;
7798 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007799 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007800 disabledComponents = base.disabledComponents;
7801 enabledComponents = base.enabledComponents;
7802 enabled = base.enabled;
7803 installStatus = base.installStatus;
7804 }
7805
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007806 boolean enableComponentLP(String componentClassName) {
7807 boolean changed = disabledComponents.remove(componentClassName);
7808 changed |= enabledComponents.add(componentClassName);
7809 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007810 }
7811
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007812 boolean disableComponentLP(String componentClassName) {
7813 boolean changed = enabledComponents.remove(componentClassName);
7814 changed |= disabledComponents.add(componentClassName);
7815 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007816 }
7817
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007818 boolean restoreComponentLP(String componentClassName) {
7819 boolean changed = enabledComponents.remove(componentClassName);
7820 changed |= disabledComponents.remove(componentClassName);
7821 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007822 }
7823
7824 int currentEnabledStateLP(String componentName) {
7825 if (enabledComponents.contains(componentName)) {
7826 return COMPONENT_ENABLED_STATE_ENABLED;
7827 } else if (disabledComponents.contains(componentName)) {
7828 return COMPONENT_ENABLED_STATE_DISABLED;
7829 } else {
7830 return COMPONENT_ENABLED_STATE_DEFAULT;
7831 }
7832 }
7833 }
7834
7835 /**
7836 * Settings data for a particular package we know about.
7837 */
7838 static final class PackageSetting extends PackageSettingBase {
7839 int userId;
7840 PackageParser.Package pkg;
7841 SharedUserSetting sharedUser;
7842
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007843 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007844 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007845 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007846 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007848 @Override
7849 public String toString() {
7850 return "PackageSetting{"
7851 + Integer.toHexString(System.identityHashCode(this))
7852 + " " + name + "/" + userId + "}";
7853 }
7854 }
7855
7856 /**
7857 * Settings data for a particular shared user ID we know about.
7858 */
7859 static final class SharedUserSetting extends GrantedPermissions {
7860 final String name;
7861 int userId;
7862 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7863 final PackageSignatures signatures = new PackageSignatures();
7864
7865 SharedUserSetting(String _name, int _pkgFlags) {
7866 super(_pkgFlags);
7867 name = _name;
7868 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007870 @Override
7871 public String toString() {
7872 return "SharedUserSetting{"
7873 + Integer.toHexString(System.identityHashCode(this))
7874 + " " + name + "/" + userId + "}";
7875 }
7876 }
7877
7878 /**
7879 * Holds information about dynamic settings.
7880 */
7881 private static final class Settings {
7882 private final File mSettingsFilename;
7883 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007884 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007885 private final HashMap<String, PackageSetting> mPackages =
7886 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007887 // List of replaced system applications
7888 final HashMap<String, PackageSetting> mDisabledSysPackages =
7889 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007890
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007891 // These are the last platform API version we were using for
7892 // the apps installed on internal and external storage. It is
7893 // used to grant newer permissions one time during a system upgrade.
7894 int mInternalSdkPlatform;
7895 int mExternalSdkPlatform;
7896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007897 // The user's preferred activities associated with particular intent
7898 // filters.
7899 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7900 new IntentResolver<PreferredActivity, PreferredActivity>() {
7901 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007902 protected String packageForFilter(PreferredActivity filter) {
7903 return filter.mActivity.getPackageName();
7904 }
7905 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007906 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007907 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007908 out.print(prefix); out.print(
7909 Integer.toHexString(System.identityHashCode(filter)));
7910 out.print(' ');
7911 out.print(filter.mActivity.flattenToShortString());
7912 out.print(" match=0x");
7913 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007914 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007915 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007916 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007917 out.print(prefix); out.print(" ");
7918 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007919 }
7920 }
7921 }
7922 };
7923 private final HashMap<String, SharedUserSetting> mSharedUsers =
7924 new HashMap<String, SharedUserSetting>();
7925 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7926 private final SparseArray<Object> mOtherUserIds =
7927 new SparseArray<Object>();
7928
7929 // For reading/writing settings file.
7930 private final ArrayList<Signature> mPastSignatures =
7931 new ArrayList<Signature>();
7932
7933 // Mapping from permission names to info about them.
7934 final HashMap<String, BasePermission> mPermissions =
7935 new HashMap<String, BasePermission>();
7936
7937 // Mapping from permission tree names to info about them.
7938 final HashMap<String, BasePermission> mPermissionTrees =
7939 new HashMap<String, BasePermission>();
7940
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007941 // Packages that have been uninstalled and still need their external
7942 // storage data deleted.
7943 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7944
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007945 // Packages that have been renamed since they were first installed.
7946 // Keys are the new names of the packages, values are the original
7947 // names. The packages appear everwhere else under their original
7948 // names.
7949 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007951 private final StringBuilder mReadMessages = new StringBuilder();
7952
7953 private static final class PendingPackage extends PackageSettingBase {
7954 final int sharedId;
7955
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007956 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007957 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007958 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007959 this.sharedId = sharedId;
7960 }
7961 }
7962 private final ArrayList<PendingPackage> mPendingPackages
7963 = new ArrayList<PendingPackage>();
7964
7965 Settings() {
7966 File dataDir = Environment.getDataDirectory();
7967 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007968 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7969 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007970 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007971 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007972 FileUtils.setPermissions(systemDir.toString(),
7973 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7974 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7975 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007976 FileUtils.setPermissions(systemSecureDir.toString(),
7977 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7978 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7979 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007980 mSettingsFilename = new File(systemDir, "packages.xml");
7981 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007982 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007983 }
7984
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007985 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007986 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007987 int pkgFlags, boolean create, boolean add) {
7988 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007989 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007990 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007991 return p;
7992 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007993
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007994 PackageSetting peekPackageLP(String name) {
7995 return mPackages.get(name);
7996 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007997 PackageSetting p = mPackages.get(name);
7998 if (p != null && p.codePath.getPath().equals(codePath)) {
7999 return p;
8000 }
8001 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008002 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008003 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008005 void setInstallStatus(String pkgName, int status) {
8006 PackageSetting p = mPackages.get(pkgName);
8007 if(p != null) {
8008 if(p.getInstallStatus() != status) {
8009 p.setInstallStatus(status);
8010 }
8011 }
8012 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008013
Jacek Surazski65e13172009-04-28 15:26:38 +02008014 void setInstallerPackageName(String pkgName,
8015 String installerPkgName) {
8016 PackageSetting p = mPackages.get(pkgName);
8017 if(p != null) {
8018 p.setInstallerPackageName(installerPkgName);
8019 }
8020 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008021
Jacek Surazski65e13172009-04-28 15:26:38 +02008022 String getInstallerPackageName(String pkgName) {
8023 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008024 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02008025 }
8026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008027 int getInstallStatus(String pkgName) {
8028 PackageSetting p = mPackages.get(pkgName);
8029 if(p != null) {
8030 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008032 return -1;
8033 }
8034
8035 SharedUserSetting getSharedUserLP(String name,
8036 int pkgFlags, boolean create) {
8037 SharedUserSetting s = mSharedUsers.get(name);
8038 if (s == null) {
8039 if (!create) {
8040 return null;
8041 }
8042 s = new SharedUserSetting(name, pkgFlags);
8043 if (MULTIPLE_APPLICATION_UIDS) {
8044 s.userId = newUserIdLP(s);
8045 } else {
8046 s.userId = FIRST_APPLICATION_UID;
8047 }
8048 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
8049 // < 0 means we couldn't assign a userid; fall out and return
8050 // s, which is currently null
8051 if (s.userId >= 0) {
8052 mSharedUsers.put(name, s);
8053 }
8054 }
8055
8056 return s;
8057 }
8058
8059 int disableSystemPackageLP(String name) {
8060 PackageSetting p = mPackages.get(name);
8061 if(p == null) {
8062 Log.w(TAG, "Package:"+name+" is not an installed package");
8063 return -1;
8064 }
8065 PackageSetting dp = mDisabledSysPackages.get(name);
8066 // always make sure the system package code and resource paths dont change
8067 if(dp == null) {
8068 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8069 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8070 }
8071 mDisabledSysPackages.put(name, p);
8072 }
8073 return removePackageLP(name);
8074 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008076 PackageSetting enableSystemPackageLP(String name) {
8077 PackageSetting p = mDisabledSysPackages.get(name);
8078 if(p == null) {
8079 Log.w(TAG, "Package:"+name+" is not disabled");
8080 return null;
8081 }
8082 // Reset flag in ApplicationInfo object
8083 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8084 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8085 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008086 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008087 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008088 mDisabledSysPackages.remove(name);
8089 return ret;
8090 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008091
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008092 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008093 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008094 PackageSetting p = mPackages.get(name);
8095 if (p != null) {
8096 if (p.userId == uid) {
8097 return p;
8098 }
8099 reportSettingsProblem(Log.ERROR,
8100 "Adding duplicate package, keeping first: " + name);
8101 return null;
8102 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008103 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008104 p.userId = uid;
8105 if (addUserIdLP(uid, p, name)) {
8106 mPackages.put(name, p);
8107 return p;
8108 }
8109 return null;
8110 }
8111
8112 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8113 SharedUserSetting s = mSharedUsers.get(name);
8114 if (s != null) {
8115 if (s.userId == uid) {
8116 return s;
8117 }
8118 reportSettingsProblem(Log.ERROR,
8119 "Adding duplicate shared user, keeping first: " + name);
8120 return null;
8121 }
8122 s = new SharedUserSetting(name, pkgFlags);
8123 s.userId = uid;
8124 if (addUserIdLP(uid, s, name)) {
8125 mSharedUsers.put(name, s);
8126 return s;
8127 }
8128 return null;
8129 }
8130
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008131 // Transfer ownership of permissions from one package to another.
8132 private void transferPermissions(String origPkg, String newPkg) {
8133 // Transfer ownership of permissions to the new package.
8134 for (int i=0; i<2; i++) {
8135 HashMap<String, BasePermission> permissions =
8136 i == 0 ? mPermissionTrees : mPermissions;
8137 for (BasePermission bp : permissions.values()) {
8138 if (origPkg.equals(bp.sourcePackage)) {
8139 if (DEBUG_UPGRADE) Log.v(TAG,
8140 "Moving permission " + bp.name
8141 + " from pkg " + bp.sourcePackage
8142 + " to " + newPkg);
8143 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008144 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008145 bp.perm = null;
8146 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008147 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008148 }
8149 bp.uid = 0;
8150 bp.gids = null;
8151 }
8152 }
8153 }
8154 }
8155
8156 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008157 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008158 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008159 PackageSetting p = mPackages.get(name);
8160 if (p != null) {
8161 if (!p.codePath.equals(codePath)) {
8162 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008163 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008164 // This is an updated system app with versions in both system
8165 // and data partition. Just let the most recent version
8166 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008167 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008168 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008169 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008170 // Just a change in the code path is not an issue, but
8171 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008172 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008173 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008174 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008175 }
8176 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008177 reportSettingsProblem(Log.WARN,
8178 "Package " + name + " shared user changed from "
8179 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8180 + " to "
8181 + (sharedUser != null ? sharedUser.name : "<nothing>")
8182 + "; replacing with new");
8183 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008184 } else {
8185 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8186 // If what we are scanning is a system package, then
8187 // make it so, regardless of whether it was previously
8188 // installed only in the data partition.
8189 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008191 }
8192 }
8193 if (p == null) {
8194 // Create a new PackageSettings entry. this can end up here because
8195 // of code path mismatch or user id mismatch of an updated system partition
8196 if (!create) {
8197 return null;
8198 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008199 if (origPackage != null) {
8200 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008201 p = new PackageSetting(origPackage.name, name, codePath,
8202 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008203 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8204 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008205 // Note that we will retain the new package's signature so
8206 // that we can keep its data.
8207 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008208 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008209 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008210 p.sharedUser = origPackage.sharedUser;
8211 p.userId = origPackage.userId;
8212 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008213 mRenamedPackages.put(name, origPackage.name);
8214 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008215 // Update new package state.
8216 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008217 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008218 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008219 p.setTimeStamp(codePath.lastModified());
8220 p.sharedUser = sharedUser;
8221 if (sharedUser != null) {
8222 p.userId = sharedUser.userId;
8223 } else if (MULTIPLE_APPLICATION_UIDS) {
8224 // Clone the setting here for disabled system packages
8225 PackageSetting dis = mDisabledSysPackages.get(name);
8226 if (dis != null) {
8227 // For disabled packages a new setting is created
8228 // from the existing user id. This still has to be
8229 // added to list of user id's
8230 // Copy signatures from previous setting
8231 if (dis.signatures.mSignatures != null) {
8232 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8233 }
8234 p.userId = dis.userId;
8235 // Clone permissions
8236 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008237 // Clone component info
8238 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8239 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8240 // Add new setting to list of user ids
8241 addUserIdLP(p.userId, p, name);
8242 } else {
8243 // Assign new user id
8244 p.userId = newUserIdLP(p);
8245 }
8246 } else {
8247 p.userId = FIRST_APPLICATION_UID;
8248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008249 }
8250 if (p.userId < 0) {
8251 reportSettingsProblem(Log.WARN,
8252 "Package " + name + " could not be assigned a valid uid");
8253 return null;
8254 }
8255 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008256 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008257 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008258 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008259 }
8260 }
8261 return p;
8262 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008263
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008264 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008265 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008266 pkg.mSetEnabled = p.enabled;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008267 String codePath = pkg.applicationInfo.sourceDir;
8268 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008269 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008270 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008271 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008272 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008273 p.codePath = new File(codePath);
8274 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008275 }
8276 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008277 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008278 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008279 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008280 p.resourcePath = new File(resourcePath);
8281 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008282 }
8283 // Update version code if needed
8284 if (pkg.mVersionCode != p.versionCode) {
8285 p.versionCode = pkg.mVersionCode;
8286 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008287 // Update signatures if needed.
8288 if (p.signatures.mSignatures == null) {
8289 p.signatures.assignSignatures(pkg.mSignatures);
8290 }
8291 // If this app defines a shared user id initialize
8292 // the shared user signatures as well.
8293 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8294 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8295 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008296 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8297 }
8298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008299 // Utility method that adds a PackageSetting to mPackages and
8300 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008301 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008302 SharedUserSetting sharedUser) {
8303 mPackages.put(name, p);
8304 if (sharedUser != null) {
8305 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8306 reportSettingsProblem(Log.ERROR,
8307 "Package " + p.name + " was user "
8308 + p.sharedUser + " but is now " + sharedUser
8309 + "; I am not changing its files so it will probably fail!");
8310 p.sharedUser.packages.remove(p);
8311 } else if (p.userId != sharedUser.userId) {
8312 reportSettingsProblem(Log.ERROR,
8313 "Package " + p.name + " was user id " + p.userId
8314 + " but is now user " + sharedUser
8315 + " with id " + sharedUser.userId
8316 + "; I am not changing its files so it will probably fail!");
8317 }
8318
8319 sharedUser.packages.add(p);
8320 p.sharedUser = sharedUser;
8321 p.userId = sharedUser.userId;
8322 }
8323 }
8324
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008325 /*
8326 * Update the shared user setting when a package using
8327 * specifying the shared user id is removed. The gids
8328 * associated with each permission of the deleted package
8329 * are removed from the shared user's gid list only if its
8330 * not in use by other permissions of packages in the
8331 * shared user setting.
8332 */
8333 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008334 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008335 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008336 return;
8337 }
8338 // No sharedUserId
8339 if (deletedPs.sharedUser == null) {
8340 return;
8341 }
8342 SharedUserSetting sus = deletedPs.sharedUser;
8343 // Update permissions
8344 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8345 boolean used = false;
8346 if (!sus.grantedPermissions.contains (eachPerm)) {
8347 continue;
8348 }
8349 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008350 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008351 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008352 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008353 used = true;
8354 break;
8355 }
8356 }
8357 if (!used) {
8358 // can safely delete this permission from list
8359 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008360 }
8361 }
8362 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008363 int newGids[] = globalGids;
8364 for (String eachPerm : sus.grantedPermissions) {
8365 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008366 if (bp != null) {
8367 newGids = appendInts(newGids, bp.gids);
8368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008369 }
8370 sus.gids = newGids;
8371 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008373 private int removePackageLP(String name) {
8374 PackageSetting p = mPackages.get(name);
8375 if (p != null) {
8376 mPackages.remove(name);
8377 if (p.sharedUser != null) {
8378 p.sharedUser.packages.remove(p);
8379 if (p.sharedUser.packages.size() == 0) {
8380 mSharedUsers.remove(p.sharedUser.name);
8381 removeUserIdLP(p.sharedUser.userId);
8382 return p.sharedUser.userId;
8383 }
8384 } else {
8385 removeUserIdLP(p.userId);
8386 return p.userId;
8387 }
8388 }
8389 return -1;
8390 }
8391
8392 private boolean addUserIdLP(int uid, Object obj, Object name) {
8393 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8394 return false;
8395 }
8396
8397 if (uid >= FIRST_APPLICATION_UID) {
8398 int N = mUserIds.size();
8399 final int index = uid - FIRST_APPLICATION_UID;
8400 while (index >= N) {
8401 mUserIds.add(null);
8402 N++;
8403 }
8404 if (mUserIds.get(index) != null) {
8405 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008406 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008407 + " name=" + name);
8408 return false;
8409 }
8410 mUserIds.set(index, obj);
8411 } else {
8412 if (mOtherUserIds.get(uid) != null) {
8413 reportSettingsProblem(Log.ERROR,
8414 "Adding duplicate shared id: " + uid
8415 + " name=" + name);
8416 return false;
8417 }
8418 mOtherUserIds.put(uid, obj);
8419 }
8420 return true;
8421 }
8422
8423 public Object getUserIdLP(int uid) {
8424 if (uid >= FIRST_APPLICATION_UID) {
8425 int N = mUserIds.size();
8426 final int index = uid - FIRST_APPLICATION_UID;
8427 return index < N ? mUserIds.get(index) : null;
8428 } else {
8429 return mOtherUserIds.get(uid);
8430 }
8431 }
8432
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008433 private Set<String> findPackagesWithFlag(int flag) {
8434 Set<String> ret = new HashSet<String>();
8435 for (PackageSetting ps : mPackages.values()) {
8436 // Has to match atleast all the flag bits set on flag
8437 if ((ps.pkgFlags & flag) == flag) {
8438 ret.add(ps.name);
8439 }
8440 }
8441 return ret;
8442 }
8443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008444 private void removeUserIdLP(int uid) {
8445 if (uid >= FIRST_APPLICATION_UID) {
8446 int N = mUserIds.size();
8447 final int index = uid - FIRST_APPLICATION_UID;
8448 if (index < N) mUserIds.set(index, null);
8449 } else {
8450 mOtherUserIds.remove(uid);
8451 }
8452 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008454 void writeLP() {
8455 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8456
8457 // Keep the old settings around until we know the new ones have
8458 // been successfully written.
8459 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008460 // Presence of backup settings file indicates that we failed
8461 // to persist settings earlier. So preserve the older
8462 // backup for future reference since the current settings
8463 // might have been corrupted.
8464 if (!mBackupSettingsFilename.exists()) {
8465 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008466 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008467 return;
8468 }
8469 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008470 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008471 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008473 }
8474
8475 mPastSignatures.clear();
8476
8477 try {
8478 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8479
8480 //XmlSerializer serializer = XmlUtils.serializerInstance();
8481 XmlSerializer serializer = new FastXmlSerializer();
8482 serializer.setOutput(str, "utf-8");
8483 serializer.startDocument(null, true);
8484 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8485
8486 serializer.startTag(null, "packages");
8487
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008488 serializer.startTag(null, "last-platform-version");
8489 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8490 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8491 serializer.endTag(null, "last-platform-version");
8492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008493 serializer.startTag(null, "permission-trees");
8494 for (BasePermission bp : mPermissionTrees.values()) {
8495 writePermission(serializer, bp);
8496 }
8497 serializer.endTag(null, "permission-trees");
8498
8499 serializer.startTag(null, "permissions");
8500 for (BasePermission bp : mPermissions.values()) {
8501 writePermission(serializer, bp);
8502 }
8503 serializer.endTag(null, "permissions");
8504
8505 for (PackageSetting pkg : mPackages.values()) {
8506 writePackage(serializer, pkg);
8507 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008509 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8510 writeDisabledSysPackage(serializer, pkg);
8511 }
8512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008513 serializer.startTag(null, "preferred-activities");
8514 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8515 serializer.startTag(null, "item");
8516 pa.writeToXml(serializer);
8517 serializer.endTag(null, "item");
8518 }
8519 serializer.endTag(null, "preferred-activities");
8520
8521 for (SharedUserSetting usr : mSharedUsers.values()) {
8522 serializer.startTag(null, "shared-user");
8523 serializer.attribute(null, "name", usr.name);
8524 serializer.attribute(null, "userId",
8525 Integer.toString(usr.userId));
8526 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8527 serializer.startTag(null, "perms");
8528 for (String name : usr.grantedPermissions) {
8529 serializer.startTag(null, "item");
8530 serializer.attribute(null, "name", name);
8531 serializer.endTag(null, "item");
8532 }
8533 serializer.endTag(null, "perms");
8534 serializer.endTag(null, "shared-user");
8535 }
8536
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008537 if (mPackagesToBeCleaned.size() > 0) {
8538 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8539 serializer.startTag(null, "cleaning-package");
8540 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8541 serializer.endTag(null, "cleaning-package");
8542 }
8543 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008544
8545 if (mRenamedPackages.size() > 0) {
8546 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8547 serializer.startTag(null, "renamed-package");
8548 serializer.attribute(null, "new", e.getKey());
8549 serializer.attribute(null, "old", e.getValue());
8550 serializer.endTag(null, "renamed-package");
8551 }
8552 }
8553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008554 serializer.endTag(null, "packages");
8555
8556 serializer.endDocument();
8557
8558 str.flush();
8559 str.close();
8560
8561 // New settings successfully written, old ones are no longer
8562 // needed.
8563 mBackupSettingsFilename.delete();
8564 FileUtils.setPermissions(mSettingsFilename.toString(),
8565 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8566 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8567 |FileUtils.S_IROTH,
8568 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008569
8570 // Write package list file now, use a JournaledFile.
8571 //
8572 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8573 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8574
8575 str = new FileOutputStream(journal.chooseForWrite());
8576 try {
8577 StringBuilder sb = new StringBuilder();
8578 for (PackageSetting pkg : mPackages.values()) {
8579 ApplicationInfo ai = pkg.pkg.applicationInfo;
8580 String dataPath = ai.dataDir;
8581 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8582
8583 // Avoid any application that has a space in its path
8584 // or that is handled by the system.
8585 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8586 continue;
8587
8588 // we store on each line the following information for now:
8589 //
8590 // pkgName - package name
8591 // userId - application-specific user id
8592 // debugFlag - 0 or 1 if the package is debuggable.
8593 // dataPath - path to package's data path
8594 //
8595 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8596 //
8597 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8598 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8599 // system/core/run-as/run-as.c
8600 //
8601 sb.setLength(0);
8602 sb.append(ai.packageName);
8603 sb.append(" ");
8604 sb.append((int)ai.uid);
8605 sb.append(isDebug ? " 1 " : " 0 ");
8606 sb.append(dataPath);
8607 sb.append("\n");
8608 str.write(sb.toString().getBytes());
8609 }
8610 str.flush();
8611 str.close();
8612 journal.commit();
8613 }
8614 catch (Exception e) {
8615 journal.rollback();
8616 }
8617
8618 FileUtils.setPermissions(mPackageListFilename.toString(),
8619 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8620 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8621 |FileUtils.S_IROTH,
8622 -1, -1);
8623
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008624 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008625
8626 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008627 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 -08008628 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008629 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 -08008630 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008631 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008632 if (mSettingsFilename.exists()) {
8633 if (!mSettingsFilename.delete()) {
8634 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8635 }
8636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008637 //Debug.stopMethodTracing();
8638 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008639
8640 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008641 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008642 serializer.startTag(null, "updated-package");
8643 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008644 if (pkg.realName != null) {
8645 serializer.attribute(null, "realName", pkg.realName);
8646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008647 serializer.attribute(null, "codePath", pkg.codePathString);
8648 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008649 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008650 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8651 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8652 }
8653 if (pkg.sharedUser == null) {
8654 serializer.attribute(null, "userId",
8655 Integer.toString(pkg.userId));
8656 } else {
8657 serializer.attribute(null, "sharedUserId",
8658 Integer.toString(pkg.userId));
8659 }
8660 serializer.startTag(null, "perms");
8661 if (pkg.sharedUser == null) {
8662 // If this is a shared user, the permissions will
8663 // be written there. We still need to write an
8664 // empty permissions list so permissionsFixed will
8665 // be set.
8666 for (final String name : pkg.grantedPermissions) {
8667 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008668 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008669 // We only need to write signature or system permissions but this wont
8670 // match the semantics of grantedPermissions. So write all permissions.
8671 serializer.startTag(null, "item");
8672 serializer.attribute(null, "name", name);
8673 serializer.endTag(null, "item");
8674 }
8675 }
8676 }
8677 serializer.endTag(null, "perms");
8678 serializer.endTag(null, "updated-package");
8679 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008680
8681 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008682 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008683 serializer.startTag(null, "package");
8684 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008685 if (pkg.realName != null) {
8686 serializer.attribute(null, "realName", pkg.realName);
8687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008688 serializer.attribute(null, "codePath", pkg.codePathString);
8689 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8690 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8691 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008692 serializer.attribute(null, "flags",
8693 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008694 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008695 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008696 if (pkg.sharedUser == null) {
8697 serializer.attribute(null, "userId",
8698 Integer.toString(pkg.userId));
8699 } else {
8700 serializer.attribute(null, "sharedUserId",
8701 Integer.toString(pkg.userId));
8702 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008703 if (pkg.uidError) {
8704 serializer.attribute(null, "uidError", "true");
8705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008706 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8707 serializer.attribute(null, "enabled",
8708 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8709 ? "true" : "false");
8710 }
8711 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8712 serializer.attribute(null, "installStatus", "false");
8713 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008714 if (pkg.installerPackageName != null) {
8715 serializer.attribute(null, "installer", pkg.installerPackageName);
8716 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008717 if (pkg.obbPathString != null) {
8718 serializer.attribute(null, "obbPath", pkg.obbPathString);
8719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008720 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8721 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8722 serializer.startTag(null, "perms");
8723 if (pkg.sharedUser == null) {
8724 // If this is a shared user, the permissions will
8725 // be written there. We still need to write an
8726 // empty permissions list so permissionsFixed will
8727 // be set.
8728 for (final String name : pkg.grantedPermissions) {
8729 serializer.startTag(null, "item");
8730 serializer.attribute(null, "name", name);
8731 serializer.endTag(null, "item");
8732 }
8733 }
8734 serializer.endTag(null, "perms");
8735 }
8736 if (pkg.disabledComponents.size() > 0) {
8737 serializer.startTag(null, "disabled-components");
8738 for (final String name : pkg.disabledComponents) {
8739 serializer.startTag(null, "item");
8740 serializer.attribute(null, "name", name);
8741 serializer.endTag(null, "item");
8742 }
8743 serializer.endTag(null, "disabled-components");
8744 }
8745 if (pkg.enabledComponents.size() > 0) {
8746 serializer.startTag(null, "enabled-components");
8747 for (final String name : pkg.enabledComponents) {
8748 serializer.startTag(null, "item");
8749 serializer.attribute(null, "name", name);
8750 serializer.endTag(null, "item");
8751 }
8752 serializer.endTag(null, "enabled-components");
8753 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008755 serializer.endTag(null, "package");
8756 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008758 void writePermission(XmlSerializer serializer, BasePermission bp)
8759 throws XmlPullParserException, java.io.IOException {
8760 if (bp.type != BasePermission.TYPE_BUILTIN
8761 && bp.sourcePackage != null) {
8762 serializer.startTag(null, "item");
8763 serializer.attribute(null, "name", bp.name);
8764 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008765 if (bp.protectionLevel !=
8766 PermissionInfo.PROTECTION_NORMAL) {
8767 serializer.attribute(null, "protection",
8768 Integer.toString(bp.protectionLevel));
8769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008770 if (DEBUG_SETTINGS) Log.v(TAG,
8771 "Writing perm: name=" + bp.name + " type=" + bp.type);
8772 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8773 PermissionInfo pi = bp.perm != null ? bp.perm.info
8774 : bp.pendingInfo;
8775 if (pi != null) {
8776 serializer.attribute(null, "type", "dynamic");
8777 if (pi.icon != 0) {
8778 serializer.attribute(null, "icon",
8779 Integer.toString(pi.icon));
8780 }
8781 if (pi.nonLocalizedLabel != null) {
8782 serializer.attribute(null, "label",
8783 pi.nonLocalizedLabel.toString());
8784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008785 }
8786 }
8787 serializer.endTag(null, "item");
8788 }
8789 }
8790
8791 String getReadMessagesLP() {
8792 return mReadMessages.toString();
8793 }
8794
Oscar Montemayora8529f62009-11-18 10:14:20 -08008795 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008796 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8797 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008798 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008799 while(its.hasNext()) {
8800 String key = its.next();
8801 PackageSetting ps = mPackages.get(key);
8802 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008803 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008804 }
8805 }
8806 return ret;
8807 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008809 boolean readLP() {
8810 FileInputStream str = null;
8811 if (mBackupSettingsFilename.exists()) {
8812 try {
8813 str = new FileInputStream(mBackupSettingsFilename);
8814 mReadMessages.append("Reading from backup settings file\n");
8815 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008816 if (mSettingsFilename.exists()) {
8817 // If both the backup and settings file exist, we
8818 // ignore the settings since it might have been
8819 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008820 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008821 mSettingsFilename.delete();
8822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008823 } catch (java.io.IOException e) {
8824 // We'll try for the normal settings file.
8825 }
8826 }
8827
8828 mPastSignatures.clear();
8829
8830 try {
8831 if (str == null) {
8832 if (!mSettingsFilename.exists()) {
8833 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008834 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008835 return false;
8836 }
8837 str = new FileInputStream(mSettingsFilename);
8838 }
8839 XmlPullParser parser = Xml.newPullParser();
8840 parser.setInput(str, null);
8841
8842 int type;
8843 while ((type=parser.next()) != XmlPullParser.START_TAG
8844 && type != XmlPullParser.END_DOCUMENT) {
8845 ;
8846 }
8847
8848 if (type != XmlPullParser.START_TAG) {
8849 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008850 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008851 return false;
8852 }
8853
8854 int outerDepth = parser.getDepth();
8855 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8856 && (type != XmlPullParser.END_TAG
8857 || parser.getDepth() > outerDepth)) {
8858 if (type == XmlPullParser.END_TAG
8859 || type == XmlPullParser.TEXT) {
8860 continue;
8861 }
8862
8863 String tagName = parser.getName();
8864 if (tagName.equals("package")) {
8865 readPackageLP(parser);
8866 } else if (tagName.equals("permissions")) {
8867 readPermissionsLP(mPermissions, parser);
8868 } else if (tagName.equals("permission-trees")) {
8869 readPermissionsLP(mPermissionTrees, parser);
8870 } else if (tagName.equals("shared-user")) {
8871 readSharedUserLP(parser);
8872 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008873 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008874 } else if (tagName.equals("preferred-activities")) {
8875 readPreferredActivitiesLP(parser);
8876 } else if(tagName.equals("updated-package")) {
8877 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008878 } else if (tagName.equals("cleaning-package")) {
8879 String name = parser.getAttributeValue(null, "name");
8880 if (name != null) {
8881 mPackagesToBeCleaned.add(name);
8882 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008883 } else if (tagName.equals("renamed-package")) {
8884 String nname = parser.getAttributeValue(null, "new");
8885 String oname = parser.getAttributeValue(null, "old");
8886 if (nname != null && oname != null) {
8887 mRenamedPackages.put(nname, oname);
8888 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008889 } else if (tagName.equals("last-platform-version")) {
8890 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8891 try {
8892 String internal = parser.getAttributeValue(null, "internal");
8893 if (internal != null) {
8894 mInternalSdkPlatform = Integer.parseInt(internal);
8895 }
8896 String external = parser.getAttributeValue(null, "external");
8897 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008898 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008899 }
8900 } catch (NumberFormatException e) {
8901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008902 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008903 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008904 + parser.getName());
8905 XmlUtils.skipCurrentTag(parser);
8906 }
8907 }
8908
8909 str.close();
8910
8911 } catch(XmlPullParserException e) {
8912 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008913 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008914
8915 } catch(java.io.IOException e) {
8916 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008917 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008918
8919 }
8920
8921 int N = mPendingPackages.size();
8922 for (int i=0; i<N; i++) {
8923 final PendingPackage pp = mPendingPackages.get(i);
8924 Object idObj = getUserIdLP(pp.sharedId);
8925 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008926 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008927 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008928 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008929 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008930 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008931 + pp.name);
8932 continue;
8933 }
8934 p.copyFrom(pp);
8935 } else if (idObj != null) {
8936 String msg = "Bad package setting: package " + pp.name
8937 + " has shared uid " + pp.sharedId
8938 + " that is not a shared uid\n";
8939 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008940 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008941 } else {
8942 String msg = "Bad package setting: package " + pp.name
8943 + " has shared uid " + pp.sharedId
8944 + " that is not defined\n";
8945 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008946 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008947 }
8948 }
8949 mPendingPackages.clear();
8950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008951 mReadMessages.append("Read completed successfully: "
8952 + mPackages.size() + " packages, "
8953 + mSharedUsers.size() + " shared uids\n");
8954
8955 return true;
8956 }
8957
8958 private int readInt(XmlPullParser parser, String ns, String name,
8959 int defValue) {
8960 String v = parser.getAttributeValue(ns, name);
8961 try {
8962 if (v == null) {
8963 return defValue;
8964 }
8965 return Integer.parseInt(v);
8966 } catch (NumberFormatException e) {
8967 reportSettingsProblem(Log.WARN,
8968 "Error in package manager settings: attribute " +
8969 name + " has bad integer value " + v + " at "
8970 + parser.getPositionDescription());
8971 }
8972 return defValue;
8973 }
8974
8975 private void readPermissionsLP(HashMap<String, BasePermission> out,
8976 XmlPullParser parser)
8977 throws IOException, XmlPullParserException {
8978 int outerDepth = parser.getDepth();
8979 int type;
8980 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8981 && (type != XmlPullParser.END_TAG
8982 || parser.getDepth() > outerDepth)) {
8983 if (type == XmlPullParser.END_TAG
8984 || type == XmlPullParser.TEXT) {
8985 continue;
8986 }
8987
8988 String tagName = parser.getName();
8989 if (tagName.equals("item")) {
8990 String name = parser.getAttributeValue(null, "name");
8991 String sourcePackage = parser.getAttributeValue(null, "package");
8992 String ptype = parser.getAttributeValue(null, "type");
8993 if (name != null && sourcePackage != null) {
8994 boolean dynamic = "dynamic".equals(ptype);
8995 BasePermission bp = new BasePermission(name, sourcePackage,
8996 dynamic
8997 ? BasePermission.TYPE_DYNAMIC
8998 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008999 bp.protectionLevel = readInt(parser, null, "protection",
9000 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009001 if (dynamic) {
9002 PermissionInfo pi = new PermissionInfo();
9003 pi.packageName = sourcePackage.intern();
9004 pi.name = name.intern();
9005 pi.icon = readInt(parser, null, "icon", 0);
9006 pi.nonLocalizedLabel = parser.getAttributeValue(
9007 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009008 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009009 bp.pendingInfo = pi;
9010 }
9011 out.put(bp.name, bp);
9012 } else {
9013 reportSettingsProblem(Log.WARN,
9014 "Error in package manager settings: permissions has"
9015 + " no name at " + parser.getPositionDescription());
9016 }
9017 } else {
9018 reportSettingsProblem(Log.WARN,
9019 "Unknown element reading permissions: "
9020 + parser.getName() + " at "
9021 + parser.getPositionDescription());
9022 }
9023 XmlUtils.skipCurrentTag(parser);
9024 }
9025 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009027 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009028 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009029 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009030 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009031 String codePathStr = parser.getAttributeValue(null, "codePath");
9032 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009033 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009034 resourcePathStr = codePathStr;
9035 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009036 String version = parser.getAttributeValue(null, "version");
9037 int versionCode = 0;
9038 if (version != null) {
9039 try {
9040 versionCode = Integer.parseInt(version);
9041 } catch (NumberFormatException e) {
9042 }
9043 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009045 int pkgFlags = 0;
9046 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009047 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009048 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009049 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009050 String timeStampStr = parser.getAttributeValue(null, "ts");
9051 if (timeStampStr != null) {
9052 try {
9053 long timeStamp = Long.parseLong(timeStampStr);
9054 ps.setTimeStamp(timeStamp, timeStampStr);
9055 } catch (NumberFormatException e) {
9056 }
9057 }
9058 String idStr = parser.getAttributeValue(null, "userId");
9059 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
9060 if(ps.userId <= 0) {
9061 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9062 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
9063 }
9064 int outerDepth = parser.getDepth();
9065 int type;
9066 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9067 && (type != XmlPullParser.END_TAG
9068 || parser.getDepth() > outerDepth)) {
9069 if (type == XmlPullParser.END_TAG
9070 || type == XmlPullParser.TEXT) {
9071 continue;
9072 }
9073
9074 String tagName = parser.getName();
9075 if (tagName.equals("perms")) {
9076 readGrantedPermissionsLP(parser,
9077 ps.grantedPermissions);
9078 } else {
9079 reportSettingsProblem(Log.WARN,
9080 "Unknown element under <updated-package>: "
9081 + parser.getName());
9082 XmlUtils.skipCurrentTag(parser);
9083 }
9084 }
9085 mDisabledSysPackages.put(name, ps);
9086 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009088 private void readPackageLP(XmlPullParser parser)
9089 throws XmlPullParserException, IOException {
9090 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009091 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009092 String idStr = null;
9093 String sharedIdStr = null;
9094 String codePathStr = null;
9095 String resourcePathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07009096 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009097 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009098 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009099 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009100 int pkgFlags = 0;
9101 String timeStampStr;
9102 long timeStamp = 0;
9103 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009104 String version = null;
9105 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009106 try {
9107 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009108 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009109 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009110 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009111 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9112 codePathStr = parser.getAttributeValue(null, "codePath");
9113 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root93565c4b2010-06-18 15:46:06 -07009114 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009115 version = parser.getAttributeValue(null, "version");
9116 if (version != null) {
9117 try {
9118 versionCode = Integer.parseInt(version);
9119 } catch (NumberFormatException e) {
9120 }
9121 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009122 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009123
9124 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009125 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009126 try {
9127 pkgFlags = Integer.parseInt(systemStr);
9128 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009129 }
9130 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009131 // For backward compatibility
9132 systemStr = parser.getAttributeValue(null, "system");
9133 if (systemStr != null) {
9134 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9135 } else {
9136 // Old settings that don't specify system... just treat
9137 // them as system, good enough.
9138 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009140 }
9141 timeStampStr = parser.getAttributeValue(null, "ts");
9142 if (timeStampStr != null) {
9143 try {
9144 timeStamp = Long.parseLong(timeStampStr);
9145 } catch (NumberFormatException e) {
9146 }
9147 }
9148 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9149 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9150 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9151 if (resourcePathStr == null) {
9152 resourcePathStr = codePathStr;
9153 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009154 if (realName != null) {
9155 realName = realName.intern();
9156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009157 if (name == null) {
9158 reportSettingsProblem(Log.WARN,
9159 "Error in package manager settings: <package> has no name at "
9160 + parser.getPositionDescription());
9161 } else if (codePathStr == null) {
9162 reportSettingsProblem(Log.WARN,
9163 "Error in package manager settings: <package> has no codePath at "
9164 + parser.getPositionDescription());
9165 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009166 packageSetting = addPackageLP(name.intern(), realName,
9167 new File(codePathStr), new File(resourcePathStr),
9168 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009169 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9170 + ": userId=" + userId + " pkg=" + packageSetting);
9171 if (packageSetting == null) {
9172 reportSettingsProblem(Log.ERROR,
9173 "Failure adding uid " + userId
9174 + " while parsing settings at "
9175 + parser.getPositionDescription());
9176 } else {
9177 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9178 }
9179 } else if (sharedIdStr != null) {
9180 userId = sharedIdStr != null
9181 ? Integer.parseInt(sharedIdStr) : 0;
9182 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009183 packageSetting = new PendingPackage(name.intern(), realName,
9184 new File(codePathStr), new File(resourcePathStr),
9185 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009186 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9187 mPendingPackages.add((PendingPackage) packageSetting);
9188 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9189 + ": sharedUserId=" + userId + " pkg="
9190 + packageSetting);
9191 } else {
9192 reportSettingsProblem(Log.WARN,
9193 "Error in package manager settings: package "
9194 + name + " has bad sharedId " + sharedIdStr
9195 + " at " + parser.getPositionDescription());
9196 }
9197 } else {
9198 reportSettingsProblem(Log.WARN,
9199 "Error in package manager settings: package "
9200 + name + " has bad userId " + idStr + " at "
9201 + parser.getPositionDescription());
9202 }
9203 } catch (NumberFormatException e) {
9204 reportSettingsProblem(Log.WARN,
9205 "Error in package manager settings: package "
9206 + name + " has bad userId " + idStr + " at "
9207 + parser.getPositionDescription());
9208 }
9209 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009210 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009211 packageSetting.installerPackageName = installerPackageName;
Kenny Root93565c4b2010-06-18 15:46:06 -07009212 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009213 final String enabledStr = parser.getAttributeValue(null, "enabled");
9214 if (enabledStr != null) {
9215 if (enabledStr.equalsIgnoreCase("true")) {
9216 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9217 } else if (enabledStr.equalsIgnoreCase("false")) {
9218 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9219 } else if (enabledStr.equalsIgnoreCase("default")) {
9220 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9221 } else {
9222 reportSettingsProblem(Log.WARN,
9223 "Error in package manager settings: package "
9224 + name + " has bad enabled value: " + idStr
9225 + " at " + parser.getPositionDescription());
9226 }
9227 } else {
9228 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9229 }
9230 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9231 if (installStatusStr != null) {
9232 if (installStatusStr.equalsIgnoreCase("false")) {
9233 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9234 } else {
9235 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9236 }
9237 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009239 int outerDepth = parser.getDepth();
9240 int type;
9241 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9242 && (type != XmlPullParser.END_TAG
9243 || parser.getDepth() > outerDepth)) {
9244 if (type == XmlPullParser.END_TAG
9245 || type == XmlPullParser.TEXT) {
9246 continue;
9247 }
9248
9249 String tagName = parser.getName();
9250 if (tagName.equals("disabled-components")) {
9251 readDisabledComponentsLP(packageSetting, parser);
9252 } else if (tagName.equals("enabled-components")) {
9253 readEnabledComponentsLP(packageSetting, parser);
9254 } else if (tagName.equals("sigs")) {
9255 packageSetting.signatures.readXml(parser, mPastSignatures);
9256 } else if (tagName.equals("perms")) {
9257 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009258 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009259 packageSetting.permissionsFixed = true;
9260 } else {
9261 reportSettingsProblem(Log.WARN,
9262 "Unknown element under <package>: "
9263 + parser.getName());
9264 XmlUtils.skipCurrentTag(parser);
9265 }
9266 }
9267 } else {
9268 XmlUtils.skipCurrentTag(parser);
9269 }
9270 }
9271
9272 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9273 XmlPullParser parser)
9274 throws IOException, XmlPullParserException {
9275 int outerDepth = parser.getDepth();
9276 int type;
9277 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9278 && (type != XmlPullParser.END_TAG
9279 || parser.getDepth() > outerDepth)) {
9280 if (type == XmlPullParser.END_TAG
9281 || type == XmlPullParser.TEXT) {
9282 continue;
9283 }
9284
9285 String tagName = parser.getName();
9286 if (tagName.equals("item")) {
9287 String name = parser.getAttributeValue(null, "name");
9288 if (name != null) {
9289 packageSetting.disabledComponents.add(name.intern());
9290 } else {
9291 reportSettingsProblem(Log.WARN,
9292 "Error in package manager settings: <disabled-components> has"
9293 + " no name at " + parser.getPositionDescription());
9294 }
9295 } else {
9296 reportSettingsProblem(Log.WARN,
9297 "Unknown element under <disabled-components>: "
9298 + parser.getName());
9299 }
9300 XmlUtils.skipCurrentTag(parser);
9301 }
9302 }
9303
9304 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9305 XmlPullParser parser)
9306 throws IOException, XmlPullParserException {
9307 int outerDepth = parser.getDepth();
9308 int type;
9309 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9310 && (type != XmlPullParser.END_TAG
9311 || parser.getDepth() > outerDepth)) {
9312 if (type == XmlPullParser.END_TAG
9313 || type == XmlPullParser.TEXT) {
9314 continue;
9315 }
9316
9317 String tagName = parser.getName();
9318 if (tagName.equals("item")) {
9319 String name = parser.getAttributeValue(null, "name");
9320 if (name != null) {
9321 packageSetting.enabledComponents.add(name.intern());
9322 } else {
9323 reportSettingsProblem(Log.WARN,
9324 "Error in package manager settings: <enabled-components> has"
9325 + " no name at " + parser.getPositionDescription());
9326 }
9327 } else {
9328 reportSettingsProblem(Log.WARN,
9329 "Unknown element under <enabled-components>: "
9330 + parser.getName());
9331 }
9332 XmlUtils.skipCurrentTag(parser);
9333 }
9334 }
9335
9336 private void readSharedUserLP(XmlPullParser parser)
9337 throws XmlPullParserException, IOException {
9338 String name = null;
9339 String idStr = null;
9340 int pkgFlags = 0;
9341 SharedUserSetting su = null;
9342 try {
9343 name = parser.getAttributeValue(null, "name");
9344 idStr = parser.getAttributeValue(null, "userId");
9345 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9346 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9347 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9348 }
9349 if (name == null) {
9350 reportSettingsProblem(Log.WARN,
9351 "Error in package manager settings: <shared-user> has no name at "
9352 + parser.getPositionDescription());
9353 } else if (userId == 0) {
9354 reportSettingsProblem(Log.WARN,
9355 "Error in package manager settings: shared-user "
9356 + name + " has bad userId " + idStr + " at "
9357 + parser.getPositionDescription());
9358 } else {
9359 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9360 reportSettingsProblem(Log.ERROR,
9361 "Occurred while parsing settings at "
9362 + parser.getPositionDescription());
9363 }
9364 }
9365 } catch (NumberFormatException e) {
9366 reportSettingsProblem(Log.WARN,
9367 "Error in package manager settings: package "
9368 + name + " has bad userId " + idStr + " at "
9369 + parser.getPositionDescription());
9370 };
9371
9372 if (su != null) {
9373 int outerDepth = parser.getDepth();
9374 int type;
9375 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9376 && (type != XmlPullParser.END_TAG
9377 || parser.getDepth() > outerDepth)) {
9378 if (type == XmlPullParser.END_TAG
9379 || type == XmlPullParser.TEXT) {
9380 continue;
9381 }
9382
9383 String tagName = parser.getName();
9384 if (tagName.equals("sigs")) {
9385 su.signatures.readXml(parser, mPastSignatures);
9386 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009387 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009388 } else {
9389 reportSettingsProblem(Log.WARN,
9390 "Unknown element under <shared-user>: "
9391 + parser.getName());
9392 XmlUtils.skipCurrentTag(parser);
9393 }
9394 }
9395
9396 } else {
9397 XmlUtils.skipCurrentTag(parser);
9398 }
9399 }
9400
9401 private void readGrantedPermissionsLP(XmlPullParser parser,
9402 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9403 int outerDepth = parser.getDepth();
9404 int type;
9405 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9406 && (type != XmlPullParser.END_TAG
9407 || parser.getDepth() > outerDepth)) {
9408 if (type == XmlPullParser.END_TAG
9409 || type == XmlPullParser.TEXT) {
9410 continue;
9411 }
9412
9413 String tagName = parser.getName();
9414 if (tagName.equals("item")) {
9415 String name = parser.getAttributeValue(null, "name");
9416 if (name != null) {
9417 outPerms.add(name.intern());
9418 } else {
9419 reportSettingsProblem(Log.WARN,
9420 "Error in package manager settings: <perms> has"
9421 + " no name at " + parser.getPositionDescription());
9422 }
9423 } else {
9424 reportSettingsProblem(Log.WARN,
9425 "Unknown element under <perms>: "
9426 + parser.getName());
9427 }
9428 XmlUtils.skipCurrentTag(parser);
9429 }
9430 }
9431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009432 private void readPreferredActivitiesLP(XmlPullParser parser)
9433 throws XmlPullParserException, IOException {
9434 int outerDepth = parser.getDepth();
9435 int type;
9436 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9437 && (type != XmlPullParser.END_TAG
9438 || parser.getDepth() > outerDepth)) {
9439 if (type == XmlPullParser.END_TAG
9440 || type == XmlPullParser.TEXT) {
9441 continue;
9442 }
9443
9444 String tagName = parser.getName();
9445 if (tagName.equals("item")) {
9446 PreferredActivity pa = new PreferredActivity(parser);
9447 if (pa.mParseError == null) {
9448 mPreferredActivities.addFilter(pa);
9449 } else {
9450 reportSettingsProblem(Log.WARN,
9451 "Error in package manager settings: <preferred-activity> "
9452 + pa.mParseError + " at "
9453 + parser.getPositionDescription());
9454 }
9455 } else {
9456 reportSettingsProblem(Log.WARN,
9457 "Unknown element under <preferred-activities>: "
9458 + parser.getName());
9459 XmlUtils.skipCurrentTag(parser);
9460 }
9461 }
9462 }
9463
9464 // Returns -1 if we could not find an available UserId to assign
9465 private int newUserIdLP(Object obj) {
9466 // Let's be stupidly inefficient for now...
9467 final int N = mUserIds.size();
9468 for (int i=0; i<N; i++) {
9469 if (mUserIds.get(i) == null) {
9470 mUserIds.set(i, obj);
9471 return FIRST_APPLICATION_UID + i;
9472 }
9473 }
9474
9475 // None left?
9476 if (N >= MAX_APPLICATION_UIDS) {
9477 return -1;
9478 }
9479
9480 mUserIds.add(obj);
9481 return FIRST_APPLICATION_UID + N;
9482 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009484 public PackageSetting getDisabledSystemPkg(String name) {
9485 synchronized(mPackages) {
9486 PackageSetting ps = mDisabledSysPackages.get(name);
9487 return ps;
9488 }
9489 }
9490
9491 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009492 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9493 return true;
9494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009495 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9496 if (Config.LOGV) {
9497 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9498 + " componentName = " + componentInfo.name);
9499 Log.v(TAG, "enabledComponents: "
9500 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9501 Log.v(TAG, "disabledComponents: "
9502 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9503 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009504 if (packageSettings == null) {
9505 if (false) {
9506 Log.w(TAG, "WAITING FOR DEBUGGER");
9507 Debug.waitForDebugger();
9508 Log.i(TAG, "We will crash!");
9509 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009510 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009511 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009512 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9513 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9514 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9515 return false;
9516 }
9517 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9518 return true;
9519 }
9520 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9521 return false;
9522 }
9523 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009524 }
9525 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009526
9527 // ------- apps on sdcard specific code -------
9528 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009529 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009530 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009531 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009532 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009533
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009534 private String getEncryptKey() {
9535 try {
9536 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9537 if (sdEncKey == null) {
9538 sdEncKey = SystemKeyStore.getInstance().
9539 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9540 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009541 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009542 return null;
9543 }
9544 }
9545 return sdEncKey;
9546 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009547 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009548 return null;
9549 }
9550 }
9551
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009552 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009553 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009554 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009555 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009556 if (list != null) {
9557 int idx = 0;
9558 int idList[] = new int[MAX_CONTAINERS];
9559 boolean neverFound = true;
9560 for (String name : list) {
9561 // Ignore null entries
9562 if (name == null) {
9563 continue;
9564 }
9565 int sidx = name.indexOf(prefix);
9566 if (sidx == -1) {
9567 // Not a temp file. just ignore
9568 continue;
9569 }
9570 String subStr = name.substring(sidx + prefix.length());
9571 idList[idx] = -1;
9572 if (subStr != null) {
9573 try {
9574 int cid = Integer.parseInt(subStr);
9575 idList[idx++] = cid;
9576 neverFound = false;
9577 } catch (NumberFormatException e) {
9578 }
9579 }
9580 }
9581 if (!neverFound) {
9582 // Sort idList
9583 Arrays.sort(idList);
9584 for (int j = 1; j <= idList.length; j++) {
9585 if (idList[j-1] != j) {
9586 tmpIdx = j;
9587 break;
9588 }
9589 }
9590 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009591 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009592 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009593 }
9594
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009595 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009596 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009597 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009598 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9599 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9600 throw new SecurityException("Media status can only be updated by the system");
9601 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009602 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009603 Log.i(TAG, "Updating external media status from " +
9604 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9605 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009606 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9607 mediaStatus+", mMediaMounted=" + mMediaMounted);
9608 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009609 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9610 reportStatus ? 1 : 0, -1);
9611 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009612 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009613 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009614 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009615 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009616 // Queue up an async operation since the package installation may take a little while.
9617 mHandler.post(new Runnable() {
9618 public void run() {
9619 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009620 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009621 }
9622 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009623 }
9624
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009625 /*
9626 * Collect information of applications on external media, map them
9627 * against existing containers and update information based on current
9628 * mount status. Please note that we always have to report status
9629 * if reportStatus has been set to true especially when unloading packages.
9630 */
9631 private void updateExternalMediaStatusInner(boolean mediaStatus,
9632 boolean reportStatus) {
9633 // Collection of uids
9634 int uidArr[] = null;
9635 // Collection of stale containers
9636 HashSet<String> removeCids = new HashSet<String>();
9637 // Collection of packages on external media with valid containers.
9638 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9639 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009640 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009641 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009642 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009643 } else {
9644 // Process list of secure containers and categorize them
9645 // as active or stale based on their package internal state.
9646 int uidList[] = new int[list.length];
9647 int num = 0;
9648 synchronized (mPackages) {
9649 for (String cid : list) {
9650 SdInstallArgs args = new SdInstallArgs(cid);
9651 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009652 String pkgName = args.getPackageName();
9653 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009654 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9655 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009656 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009657 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009658 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9659 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009660 // The package status is changed only if the code path
9661 // matches between settings and the container id.
9662 if (ps != null && ps.codePathString != null &&
9663 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009664 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9665 " corresponds to pkg : " + pkgName +
9666 " at code path: " + ps.codePathString);
9667 // We do have a valid package installed on sdcard
9668 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009669 int uid = ps.userId;
9670 if (uid != -1) {
9671 uidList[num++] = uid;
9672 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009673 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009674 // Stale container on sdcard. Just delete
9675 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9676 removeCids.add(cid);
9677 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009678 }
9679 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009680
9681 if (num > 0) {
9682 // Sort uid list
9683 Arrays.sort(uidList, 0, num);
9684 // Throw away duplicates
9685 uidArr = new int[num];
9686 uidArr[0] = uidList[0];
9687 int di = 0;
9688 for (int i = 1; i < num; i++) {
9689 if (uidList[i-1] != uidList[i]) {
9690 uidArr[di++] = uidList[i];
9691 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009692 }
9693 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009694 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009695 // Process packages with valid entries.
9696 if (mediaStatus) {
9697 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009698 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009699 startCleaningPackages();
9700 } else {
9701 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009702 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009703 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009704 }
9705
9706 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009707 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009708 int size = pkgList.size();
9709 if (size > 0) {
9710 // Send broadcasts here
9711 Bundle extras = new Bundle();
9712 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9713 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009714 if (uidArr != null) {
9715 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9716 }
9717 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9718 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009719 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009720 }
9721 }
9722
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009723 /*
9724 * Look at potentially valid container ids from processCids
9725 * If package information doesn't match the one on record
9726 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009727 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009728 */
9729 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009730 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009731 ArrayList<String> pkgList = new ArrayList<String>();
9732 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009733 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009734 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009735 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009736 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9737 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009738 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009739 try {
9740 // Make sure there are no container errors first.
9741 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9742 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009743 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009744 " when installing from sdcard");
9745 continue;
9746 }
9747 // Check code path here.
9748 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009749 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009750 " does not match one in settings " + codePath);
9751 continue;
9752 }
9753 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009754 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009755 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009756 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009757 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9758 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009759 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009760 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009761 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009762 retCode = PackageManager.INSTALL_SUCCEEDED;
9763 pkgList.add(pkg.packageName);
9764 // Post process args
9765 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9766 }
9767 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009768 Slog.i(TAG, "Failed to install pkg from " +
9769 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009770 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009771 }
9772
9773 } finally {
9774 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9775 // Don't destroy container here. Wait till gc clears things up.
9776 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009777 }
9778 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009779 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009780 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009781 // If the platform SDK has changed since the last time we booted,
9782 // we need to re-grant app permission to catch any new ones that
9783 // appear. This is really a hack, and means that apps can in some
9784 // cases get permissions that the user didn't initially explicitly
9785 // allow... it would be nice to have some better way to handle
9786 // this situation.
9787 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9788 != mSdkVersion;
9789 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9790 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9791 + "; regranting permissions for external storage");
9792 mSettings.mExternalSdkPlatform = mSdkVersion;
9793
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009794 // Make sure group IDs have been assigned, and any permission
9795 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009796 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009797 // Persist settings
9798 mSettings.writeLP();
9799 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009800 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009801 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009802 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009803 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009804 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009805 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009806 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009807 }
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009808 // List stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009809 if (removeCids != null) {
9810 for (String cid : removeCids) {
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009811 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009812 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009813 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009814 }
9815
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009816 /*
9817 * Utility method to unload a list of specified containers
9818 */
9819 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9820 // Just unmount all valid containers.
9821 for (SdInstallArgs arg : cidArgs) {
9822 synchronized (mInstallLock) {
9823 arg.doPostDeleteLI(false);
9824 }
9825 }
9826 }
9827
9828 /*
9829 * Unload packages mounted on external media. This involves deleting
9830 * package data from internal structures, sending broadcasts about
9831 * diabled packages, gc'ing to free up references, unmounting all
9832 * secure containers corresponding to packages on external media, and
9833 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9834 * Please note that we always have to post this message if status has
9835 * been requested no matter what.
9836 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009837 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009838 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009839 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009840 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009841 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009842 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009843 for (SdInstallArgs args : keys) {
9844 String cid = args.cid;
9845 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009846 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009847 // Delete package internally
9848 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9849 synchronized (mInstallLock) {
9850 boolean res = deletePackageLI(pkgName, false,
9851 PackageManager.DONT_DELETE_DATA, outInfo);
9852 if (res) {
9853 pkgList.add(pkgName);
9854 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009855 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009856 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009857 }
9858 }
9859 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009860 // We have to absolutely send UPDATED_MEDIA_STATUS only
9861 // after confirming that all the receivers processed the ordered
9862 // broadcast when packages get disabled, force a gc to clean things up.
9863 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009864 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009865 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9866 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9867 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009868 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9869 reportStatus ? 1 : 0, 1, keys);
9870 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009871 }
9872 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009873 } else {
9874 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9875 reportStatus ? 1 : 0, -1, keys);
9876 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009877 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009878 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009879
9880 public void movePackage(final String packageName,
9881 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009882 mContext.enforceCallingOrSelfPermission(
9883 android.Manifest.permission.MOVE_PACKAGE, null);
9884 int returnCode = PackageManager.MOVE_SUCCEEDED;
9885 int currFlags = 0;
9886 int newFlags = 0;
9887 synchronized (mPackages) {
9888 PackageParser.Package pkg = mPackages.get(packageName);
9889 if (pkg == null) {
9890 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009891 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009892 // Disable moving fwd locked apps and system packages
9893 if (pkg.applicationInfo != null &&
9894 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9895 Slog.w(TAG, "Cannot move system application");
9896 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9897 } else if (pkg.applicationInfo != null &&
9898 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9899 Slog.w(TAG, "Cannot move forward locked app.");
9900 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009901 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009902 // Find install location first
9903 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9904 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9905 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009906 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009907 } else {
9908 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9909 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9910 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
9911 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9912 if (newFlags == currFlags) {
9913 Slog.w(TAG, "No move required. Trying to move to same location");
9914 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9915 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009916 }
9917 }
9918 }
9919 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07009920 processPendingMove(new MoveParams(null, observer, 0, packageName), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009921 } else {
9922 Message msg = mHandler.obtainMessage(INIT_COPY);
9923 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9924 pkg.applicationInfo.publicSourceDir);
9925 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9926 packageName);
9927 msg.obj = mp;
9928 mHandler.sendMessage(msg);
9929 }
9930 }
9931 }
9932
9933 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9934 // Queue up an async operation since the package deletion may take a little while.
9935 mHandler.post(new Runnable() {
9936 public void run() {
9937 mHandler.removeCallbacks(this);
9938 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009939 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9940 int uidArr[] = null;
9941 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009942 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009943 PackageParser.Package pkg = mPackages.get(mp.packageName);
9944 if (pkg == null ) {
9945 Slog.w(TAG, " Package " + mp.packageName +
9946 " doesn't exist. Aborting move");
9947 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9948 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9949 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9950 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9951 " Aborting move and returning error");
9952 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9953 } else {
9954 uidArr = new int[] { pkg.applicationInfo.uid };
9955 pkgList = new ArrayList<String>();
9956 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009957 }
9958 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009959 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9960 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009961 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009962 // Update package code and resource paths
9963 synchronized (mInstallLock) {
9964 synchronized (mPackages) {
9965 PackageParser.Package pkg = mPackages.get(mp.packageName);
9966 // Recheck for package again.
9967 if (pkg == null ) {
9968 Slog.w(TAG, " Package " + mp.packageName +
9969 " doesn't exist. Aborting move");
9970 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9971 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9972 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9973 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9974 " Aborting move and returning error");
9975 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9976 } else {
9977 String oldCodePath = pkg.mPath;
9978 String newCodePath = mp.targetArgs.getCodePath();
9979 String newResPath = mp.targetArgs.getResourcePath();
9980 pkg.mPath = newCodePath;
9981 // Move dex files around
9982 if (moveDexFilesLI(pkg)
9983 != PackageManager.INSTALL_SUCCEEDED) {
9984 // Moving of dex files failed. Set
9985 // error code and abort move.
9986 pkg.mPath = pkg.mScanPath;
9987 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9988 } else {
9989 pkg.mScanPath = newCodePath;
9990 pkg.applicationInfo.sourceDir = newCodePath;
9991 pkg.applicationInfo.publicSourceDir = newResPath;
9992 PackageSetting ps = (PackageSetting) pkg.mExtras;
9993 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9994 ps.codePathString = ps.codePath.getPath();
9995 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9996 ps.resourcePathString = ps.resourcePath.getPath();
9997 // Set the application info flag correctly.
9998 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9999 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10000 } else {
10001 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10002 }
10003 ps.setFlags(pkg.applicationInfo.flags);
10004 mAppDirs.remove(oldCodePath);
10005 mAppDirs.put(newCodePath, pkg);
10006 // Persist settings
10007 mSettings.writeLP();
10008 }
10009 }
10010 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010011 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -070010012 // Send resources available broadcast
10013 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010014 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010015 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010016 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010017 // Clean up failed installation
10018 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010019 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010020 }
10021 } else {
10022 // Force a gc to clear things up.
10023 Runtime.getRuntime().gc();
10024 // Delete older code
10025 synchronized (mInstallLock) {
10026 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010027 }
10028 }
10029 IPackageMoveObserver observer = mp.observer;
10030 if (observer != null) {
10031 try {
10032 observer.packageMoved(mp.packageName, returnCode);
10033 } catch (RemoteException e) {
10034 Log.i(TAG, "Observer no longer exists.");
10035 }
10036 }
10037 }
10038 });
10039 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070010040
10041 public boolean setInstallLocation(int loc) {
10042 mContext.enforceCallingOrSelfPermission(
10043 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
10044 if (getInstallLocation() == loc) {
10045 return true;
10046 }
10047 if (loc == PackageHelper.APP_INSTALL_AUTO ||
10048 loc == PackageHelper.APP_INSTALL_INTERNAL ||
10049 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
10050 android.provider.Settings.System.putInt(mContext.getContentResolver(),
10051 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
10052 return true;
10053 }
10054 return false;
10055 }
10056
10057 public int getInstallLocation() {
10058 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
10059 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
10060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010061}