blob: 7827d2698df208a05697a035caf20787fc15091f [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");
Kenny Rootc78a8072010-07-27 15:18:38 -0700190
191 static final String mTempContainerPrefix = "smdl2tmp";
192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
194 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700195 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196
Dianne Hackborn851a5412009-05-08 12:06:44 -0700197 final int mSdkVersion = Build.VERSION.SDK_INT;
198 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
199 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 final Context mContext;
202 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700203 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 final DisplayMetrics mMetrics;
205 final int mDefParseFlags;
206 final String[] mSeparateProcesses;
207
208 // This is where all application persistent data goes.
209 final File mAppDataDir;
210
Oscar Montemayora8529f62009-11-18 10:14:20 -0800211 // If Encrypted File System feature is enabled, all application persistent data
212 // should go here instead.
213 final File mSecureAppDataDir;
214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 // This is the object monitoring the framework dir.
216 final FileObserver mFrameworkInstallObserver;
217
218 // This is the object monitoring the system app dir.
219 final FileObserver mSystemInstallObserver;
220
221 // This is the object monitoring mAppInstallDir.
222 final FileObserver mAppInstallObserver;
223
224 // This is the object monitoring mDrmAppPrivateInstallDir.
225 final FileObserver mDrmAppInstallObserver;
226
227 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
228 // LOCK HELD. Can be called with mInstallLock held.
229 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 final File mFrameworkDir;
232 final File mSystemAppDir;
233 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700234 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235
236 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
237 // apps.
238 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 // Lock for state used when installing and doing other long running
243 // operations. Methods that must be called with this lock held have
244 // the prefix "LI".
245 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 // These are the directories in the 3rd party applications installed dir
248 // that we have currently loaded packages from. Keys are the application's
249 // installed zip file (absolute codePath), and values are Package.
250 final HashMap<String, PackageParser.Package> mAppDirs =
251 new HashMap<String, PackageParser.Package>();
252
253 // Information for the parser to write more useful error messages.
254 File mScanningPath;
255 int mLastScanError;
256
257 final int[] mOutPermissions = new int[3];
258
259 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261 // Keys are String (package name), values are Package. This also serves
262 // as the lock for the global state. Methods that must be called with
263 // this lock held have the prefix "LP".
264 final HashMap<String, PackageParser.Package> mPackages =
265 new HashMap<String, PackageParser.Package>();
266
267 final Settings mSettings;
268 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269
270 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
271 int[] mGlobalGids;
272
273 // These are the built-in uid -> permission mappings that were read from the
274 // etc/permissions.xml file.
275 final SparseArray<HashSet<String>> mSystemPermissions =
276 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 // These are the built-in shared libraries that were read from the
279 // etc/permissions.xml file.
280 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800281
Dianne Hackborn49237342009-08-27 20:08:01 -0700282 // Temporary for building the final shared libraries for an .apk.
283 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800284
Dianne Hackborn49237342009-08-27 20:08:01 -0700285 // These are the features this devices supports that were read from the
286 // etc/permissions.xml file.
287 final HashMap<String, FeatureInfo> mAvailableFeatures =
288 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290 // All available activities, for your resolving pleasure.
291 final ActivityIntentResolver mActivities =
292 new ActivityIntentResolver();
293
294 // All available receivers, for your resolving pleasure.
295 final ActivityIntentResolver mReceivers =
296 new ActivityIntentResolver();
297
298 // All available services, for your resolving pleasure.
299 final ServiceIntentResolver mServices = new ServiceIntentResolver();
300
301 // Keys are String (provider class name), values are Provider.
302 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
303 new HashMap<ComponentName, PackageParser.Provider>();
304
305 // Mapping from provider base names (first directory in content URI codePath)
306 // to the provider information.
307 final HashMap<String, PackageParser.Provider> mProviders =
308 new HashMap<String, PackageParser.Provider>();
309
310 // Mapping from instrumentation class names to info about them.
311 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
312 new HashMap<ComponentName, PackageParser.Instrumentation>();
313
314 // Mapping from permission names to info about them.
315 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
316 new HashMap<String, PackageParser.PermissionGroup>();
317
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800318 // Packages whose data we have transfered into another package, thus
319 // should no longer exist.
320 final HashSet<String> mTransferedPackages = new HashSet<String>();
321
Dianne Hackborn854060af2009-07-09 18:14:31 -0700322 // Broadcast actions that are only available to the system.
323 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 boolean mSystemReady;
326 boolean mSafeMode;
327 boolean mHasSystemUidErrors;
328
329 ApplicationInfo mAndroidApplication;
330 final ActivityInfo mResolveActivity = new ActivityInfo();
331 final ResolveInfo mResolveInfo = new ResolveInfo();
332 ComponentName mResolveComponentName;
333 PackageParser.Package mPlatformPackage;
334
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700335 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800336 final HashMap<String, ArrayList<String>> mPendingBroadcasts
337 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800338 // Service Connection to remote media container service to copy
339 // package uri's from external media onto secure containers
340 // or internal storage.
341 private IMediaContainerService mContainerService = null;
342
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700343 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800344 static final int MCS_BOUND = 3;
345 static final int END_COPY = 4;
346 static final int INIT_COPY = 5;
347 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800348 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800349 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800350 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800351 static final int MCS_RECONNECT = 10;
352 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700353 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700354 static final int WRITE_SETTINGS = 13;
355
356 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800357
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700358 // Delay time in millisecs
359 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800360 final private DefaultContainerConnection mDefContainerConn =
361 new DefaultContainerConnection();
362 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800363 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800364 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800365 IMediaContainerService imcs =
366 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800367 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800368 }
369
370 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800371 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800372 }
373 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700374
Christopher Tate1bb69062010-02-19 17:02:12 -0800375 // Recordkeeping of restore-after-install operations that are currently in flight
376 // between the Package Manager and the Backup Manager
377 class PostInstallData {
378 public InstallArgs args;
379 public PackageInstalledInfo res;
380
381 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
382 args = _a;
383 res = _r;
384 }
385 };
386 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
387 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
388
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700389 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800390 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800391 final ArrayList<HandlerParams> mPendingInstalls =
392 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800393
394 private boolean connectToService() {
395 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
396 " DefaultContainerService");
397 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700398 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800399 if (mContext.bindService(service, mDefContainerConn,
400 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700401 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800402 mBound = true;
403 return true;
404 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700405 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800406 return false;
407 }
408
409 private void disconnectService() {
410 mContainerService = null;
411 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700412 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800413 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700414 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800415 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800416
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700417 PackageHandler(Looper looper) {
418 super(looper);
419 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700420
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700421 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700422 try {
423 doHandleMessage(msg);
424 } finally {
425 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
426 }
427 }
428
429 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700430 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800431 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800432 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800433 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800434 int idx = mPendingInstalls.size();
435 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
436 // If a bind was already initiated we dont really
437 // need to do anything. The pending install
438 // will be processed later on.
439 if (!mBound) {
440 // If this is the only one pending we might
441 // have to bind to the service again.
442 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800443 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800444 params.serviceError();
445 return;
446 } else {
447 // Once we bind to the service, the first
448 // pending request will be processed.
449 mPendingInstalls.add(idx, params);
450 }
451 } else {
452 mPendingInstalls.add(idx, params);
453 // Already bound to the service. Just make
454 // sure we trigger off processing the first request.
455 if (idx == 0) {
456 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800457 }
458 }
459 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800460 }
461 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800462 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800463 if (msg.obj != null) {
464 mContainerService = (IMediaContainerService) msg.obj;
465 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800466 if (mContainerService == null) {
467 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800468 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800469 for (HandlerParams params : mPendingInstalls) {
470 mPendingInstalls.remove(0);
471 // Indicate service bind error
472 params.serviceError();
473 }
474 mPendingInstalls.clear();
475 } else if (mPendingInstalls.size() > 0) {
476 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800477 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800478 params.startCopy();
479 }
480 } else {
481 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800482 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800483 }
484 break;
485 }
486 case MCS_RECONNECT : {
487 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
488 if (mPendingInstalls.size() > 0) {
489 if (mBound) {
490 disconnectService();
491 }
492 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800493 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800494 for (HandlerParams params : mPendingInstalls) {
495 mPendingInstalls.remove(0);
496 // Indicate service bind error
497 params.serviceError();
498 }
499 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800500 }
501 }
502 break;
503 }
504 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800505 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
506 // Delete pending install
507 if (mPendingInstalls.size() > 0) {
508 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800509 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800510 if (mPendingInstalls.size() == 0) {
511 if (mBound) {
512 disconnectService();
513 }
514 } else {
515 // There are more pending requests in queue.
516 // Just post MCS_BOUND message to trigger processing
517 // of next pending install.
518 mHandler.sendEmptyMessage(MCS_BOUND);
519 }
520 break;
521 }
522 case MCS_GIVE_UP: {
523 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
524 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800525 break;
526 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700527 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800528 String packages[];
529 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700530 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700531 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700532 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700533 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800534 if (mPendingBroadcasts == null) {
535 return;
536 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700537 size = mPendingBroadcasts.size();
538 if (size <= 0) {
539 // Nothing to be done. Just return
540 return;
541 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800542 packages = new String[size];
543 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700544 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800545 Iterator<HashMap.Entry<String, ArrayList<String>>>
546 it = mPendingBroadcasts.entrySet().iterator();
547 int i = 0;
548 while (it.hasNext() && i < size) {
549 HashMap.Entry<String, ArrayList<String>> ent = it.next();
550 packages[i] = ent.getKey();
551 components[i] = ent.getValue();
552 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700553 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800554 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700555 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800556 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700557 mPendingBroadcasts.clear();
558 }
559 // Send broadcasts
560 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800561 sendPackageChangedBroadcast(packages[i], true,
562 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700563 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700564 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700565 break;
566 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800567 case START_CLEANING_PACKAGE: {
568 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700569 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800570 synchronized (mPackages) {
571 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
572 mSettings.mPackagesToBeCleaned.add(packageName);
573 }
574 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700575 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800576 startCleaningPackages();
577 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800578 case POST_INSTALL: {
579 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
580 PostInstallData data = mRunningInstalls.get(msg.arg1);
581 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700582 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800583
584 if (data != null) {
585 InstallArgs args = data.args;
586 PackageInstalledInfo res = data.res;
587
588 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700589 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800590 Bundle extras = new Bundle(1);
591 extras.putInt(Intent.EXTRA_UID, res.uid);
592 final boolean update = res.removedInfo.removedPackage != null;
593 if (update) {
594 extras.putBoolean(Intent.EXTRA_REPLACING, true);
595 }
596 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
597 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700598 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800599 if (update) {
600 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
601 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700602 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800603 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700604 if (res.removedInfo.args != null) {
605 // Remove the replaced package's older resources safely now
606 deleteOld = true;
607 }
608 }
609 // Force a gc to clear up things
610 Runtime.getRuntime().gc();
611 // We delete after a gc for applications on sdcard.
612 if (deleteOld) {
613 synchronized (mInstallLock) {
614 res.removedInfo.args.doPostDeleteLI(true);
615 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800616 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800617 if (args.observer != null) {
618 try {
619 args.observer.packageInstalled(res.name, res.returnCode);
620 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800621 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800622 }
623 }
624 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800625 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800626 }
627 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700628 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700629 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
630 boolean reportStatus = msg.arg1 == 1;
631 boolean doGc = msg.arg2 == 1;
632 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
633 if (doGc) {
634 // Force a gc to clear up stale containers.
635 Runtime.getRuntime().gc();
636 }
637 if (msg.obj != null) {
638 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
639 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
640 // Unload containers
641 unloadAllContainers(args);
642 }
643 if (reportStatus) {
644 try {
645 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
646 PackageHelper.getMountService().finishMediaUpdate();
647 } catch (RemoteException e) {
648 Log.e(TAG, "MountService not running?");
649 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700650 }
651 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700652 case WRITE_SETTINGS: {
653 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
654 synchronized (mPackages) {
655 removeMessages(WRITE_SETTINGS);
656 mSettings.writeLP();
657 }
658 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
659 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700660 }
661 }
662 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800663
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700664 void scheduleWriteSettingsLocked() {
665 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
666 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
667 }
668 }
669
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800670 static boolean installOnSd(int flags) {
671 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700672 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800673 return false;
674 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700675 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
676 return true;
677 }
678 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800679 }
680
681 static boolean isFwdLocked(int flags) {
682 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
683 return true;
684 }
685 return false;
686 }
687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 public static final IPackageManager main(Context context, boolean factoryTest) {
689 PackageManagerService m = new PackageManagerService(context, factoryTest);
690 ServiceManager.addService("package", m);
691 return m;
692 }
693
694 static String[] splitString(String str, char sep) {
695 int count = 1;
696 int i = 0;
697 while ((i=str.indexOf(sep, i)) >= 0) {
698 count++;
699 i++;
700 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 String[] res = new String[count];
703 i=0;
704 count = 0;
705 int lastI=0;
706 while ((i=str.indexOf(sep, i)) >= 0) {
707 res[count] = str.substring(lastI, i);
708 count++;
709 i++;
710 lastI = i;
711 }
712 res[count] = str.substring(lastI, str.length());
713 return res;
714 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800717 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800721 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 mContext = context;
725 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700726 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 mMetrics = new DisplayMetrics();
728 mSettings = new Settings();
729 mSettings.addSharedUserLP("android.uid.system",
730 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
731 mSettings.addSharedUserLP("android.uid.phone",
732 MULTIPLE_APPLICATION_UIDS
733 ? RADIO_UID : FIRST_APPLICATION_UID,
734 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400735 mSettings.addSharedUserLP("android.uid.log",
736 MULTIPLE_APPLICATION_UIDS
737 ? LOG_UID : FIRST_APPLICATION_UID,
738 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739
740 String separateProcesses = SystemProperties.get("debug.separate_processes");
741 if (separateProcesses != null && separateProcesses.length() > 0) {
742 if ("*".equals(separateProcesses)) {
743 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
744 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800745 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 } else {
747 mDefParseFlags = 0;
748 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800749 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 + separateProcesses);
751 }
752 } else {
753 mDefParseFlags = 0;
754 mSeparateProcesses = null;
755 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 Installer installer = new Installer();
758 // Little hacky thing to check if installd is here, to determine
759 // whether we are running on the simulator and thus need to take
760 // care of building the /data file structure ourself.
761 // (apparently the sim now has a working installer)
762 if (installer.ping() && Process.supportsProcesses()) {
763 mInstaller = installer;
764 } else {
765 mInstaller = null;
766 }
767
768 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
769 Display d = wm.getDefaultDisplay();
770 d.getMetrics(mMetrics);
771
772 synchronized (mInstallLock) {
773 synchronized (mPackages) {
774 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700775 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 File dataDir = Environment.getDataDirectory();
778 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800779 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
781
782 if (mInstaller == null) {
783 // Make sure these dirs exist, when we are running in
784 // the simulator.
785 // Make a wide-open directory for random misc stuff.
786 File miscDir = new File(dataDir, "misc");
787 miscDir.mkdirs();
788 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800789 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 mDrmAppPrivateInstallDir.mkdirs();
791 }
792
793 readPermissions();
794
795 mRestoredSettings = mSettings.readLP();
796 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800797
798 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800800
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800801 // Set flag to monitor and not change apk file paths when
802 // scanning install directories.
803 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700804 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800805 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800806 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700807 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700812 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700815 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 /**
818 * Out of paranoia, ensure that everything in the boot class
819 * path has been dexed.
820 */
821 String bootClassPath = System.getProperty("java.boot.class.path");
822 if (bootClassPath != null) {
823 String[] paths = splitString(bootClassPath, ':');
824 for (int i=0; i<paths.length; i++) {
825 try {
826 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
827 libFiles.add(paths[i]);
828 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700829 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 }
831 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800832 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800834 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 }
836 }
837 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800838 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 /**
842 * Also ensure all external libraries have had dexopt run on them.
843 */
844 if (mSharedLibraries.size() > 0) {
845 Iterator<String> libs = mSharedLibraries.values().iterator();
846 while (libs.hasNext()) {
847 String lib = libs.next();
848 try {
849 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
850 libFiles.add(lib);
851 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700852 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 }
854 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800855 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800857 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 }
859 }
860 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 // Gross hack for now: we know this file doesn't contain any
863 // code, so don't dexopt it to avoid the resulting log spew.
864 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 /**
867 * And there are a number of commands implemented in Java, which
868 * we currently need to do the dexopt on so that they can be
869 * run from a non-root shell.
870 */
871 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700872 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 for (int i=0; i<frameworkFiles.length; i++) {
874 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
875 String path = libPath.getPath();
876 // Skip the file if we alrady did it.
877 if (libFiles.contains(path)) {
878 continue;
879 }
880 // Skip the file if it is not a type we want to dexopt.
881 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
882 continue;
883 }
884 try {
885 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
886 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700887 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 }
889 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800890 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800892 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 }
894 }
895 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800896
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700897 if (didDexOpt) {
898 // If we had to do a dexopt of one of the previous
899 // things, then something on the system has changed.
900 // Consider this significant, and wipe away all other
901 // existing dexopt files to ensure we don't leave any
902 // dangling around.
903 String[] files = mDalvikCacheDir.list();
904 if (files != null) {
905 for (int i=0; i<files.length; i++) {
906 String fn = files[i];
907 if (fn.startsWith("data@app@")
908 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800909 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700910 (new File(mDalvikCacheDir, fn)).delete();
911 }
912 }
913 }
914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800916
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800917 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 mFrameworkInstallObserver = new AppDirObserver(
919 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
920 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700921 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
922 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800923 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800924
925 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
927 mSystemInstallObserver = new AppDirObserver(
928 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
929 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700930 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
931 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800932
933 if (mInstaller != null) {
934 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
935 mInstaller.moveFiles();
936 }
937
938 // Prune any system packages that no longer exist.
939 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
940 while (psit.hasNext()) {
941 PackageSetting ps = psit.next();
942 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800943 && !mPackages.containsKey(ps.name)
944 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800945 psit.remove();
946 String msg = "System package " + ps.name
947 + " no longer exists; wiping its data";
948 reportSettingsProblem(Log.WARN, msg);
949 if (mInstaller != null) {
950 // XXX how to set useEncryptedFSDir for packages that
951 // are not encrypted?
952 mInstaller.remove(ps.name, true);
953 }
954 }
955 }
956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 mAppInstallDir = new File(dataDir, "app");
958 if (mInstaller == null) {
959 // Make sure these dirs exist, when we are running in
960 // the simulator.
961 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
962 }
963 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800964 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 //clean up list
966 for(int i = 0; i < deletePkgsList.size(); i++) {
967 //clean up here
968 cleanupInstallFailedPackage(deletePkgsList.get(i));
969 }
970 //delete tmp files
971 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800972
973 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 SystemClock.uptimeMillis());
975 mAppInstallObserver = new AppDirObserver(
976 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
977 mAppInstallObserver.startWatching();
978 scanDirLI(mAppInstallDir, 0, scanMode);
979
980 mDrmAppInstallObserver = new AppDirObserver(
981 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
982 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800983 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800985 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800987 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 + ((SystemClock.uptimeMillis()-startTime)/1000f)
989 + " seconds");
990
Dianne Hackbornf22221f2010-04-05 18:35:42 -0700991 // If the platform SDK has changed since the last time we booted,
992 // we need to re-grant app permission to catch any new ones that
993 // appear. This is really a hack, and means that apps can in some
994 // cases get permissions that the user didn't initially explicitly
995 // allow... it would be nice to have some better way to handle
996 // this situation.
997 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
998 != mSdkVersion;
999 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1000 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1001 + "; regranting permissions for internal storage");
1002 mSettings.mInternalSdkPlatform = mSdkVersion;
1003
Dianne Hackborn92cfa102010-04-28 11:00:44 -07001004 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005
1006 mSettings.writeLP();
1007
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001008 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 // Now after opening every single application zip, make sure they
1012 // are all flushed. Not really needed, but keeps things nice and
1013 // tidy.
1014 Runtime.getRuntime().gc();
1015 } // synchronized (mPackages)
1016 } // synchronized (mInstallLock)
1017 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 @Override
1020 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1021 throws RemoteException {
1022 try {
1023 return super.onTransact(code, data, reply, flags);
1024 } catch (RuntimeException e) {
1025 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001026 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 }
1028 throw e;
1029 }
1030 }
1031
Dianne Hackborne6620b22010-01-22 14:46:21 -08001032 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001033 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001035 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1036 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001038 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001039 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 }
1041 } else {
1042 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001043 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 File dataDir = new File(pkg.applicationInfo.dataDir);
1045 dataDir.delete();
1046 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001047 if (ps.codePath != null) {
1048 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001049 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001050 }
1051 }
1052 if (ps.resourcePath != null) {
1053 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001054 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001055 }
1056 }
1057 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 }
1059
1060 void readPermissions() {
1061 // Read permissions from .../etc/permission directory.
1062 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1063 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001064 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 return;
1066 }
1067 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001068 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 return;
1070 }
1071
1072 // Iterate over the files in the directory and scan .xml files
1073 for (File f : libraryDir.listFiles()) {
1074 // We'll read platform.xml last
1075 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1076 continue;
1077 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001080 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 continue;
1082 }
1083 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001084 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 continue;
1086 }
1087
1088 readPermissionsFromXml(f);
1089 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1092 final File permFile = new File(Environment.getRootDirectory(),
1093 "etc/permissions/platform.xml");
1094 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001095
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001096 StringBuilder sb = new StringBuilder(128);
1097 sb.append("Libs:");
1098 Iterator<String> it = mSharedLibraries.keySet().iterator();
1099 while (it.hasNext()) {
1100 sb.append(' ');
1101 String name = it.next();
1102 sb.append(name);
1103 sb.append(':');
1104 sb.append(mSharedLibraries.get(name));
1105 }
1106 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001107
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001108 sb.setLength(0);
1109 sb.append("Features:");
1110 it = mAvailableFeatures.keySet().iterator();
1111 while (it.hasNext()) {
1112 sb.append(' ');
1113 sb.append(it.next());
1114 }
1115 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001117
1118 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 FileReader permReader = null;
1120 try {
1121 permReader = new FileReader(permFile);
1122 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001123 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 return;
1125 }
1126
1127 try {
1128 XmlPullParser parser = Xml.newPullParser();
1129 parser.setInput(permReader);
1130
1131 XmlUtils.beginDocument(parser, "permissions");
1132
1133 while (true) {
1134 XmlUtils.nextElement(parser);
1135 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1136 break;
1137 }
1138
1139 String name = parser.getName();
1140 if ("group".equals(name)) {
1141 String gidStr = parser.getAttributeValue(null, "gid");
1142 if (gidStr != null) {
1143 int gid = Integer.parseInt(gidStr);
1144 mGlobalGids = appendInt(mGlobalGids, gid);
1145 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001146 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 + parser.getPositionDescription());
1148 }
1149
1150 XmlUtils.skipCurrentTag(parser);
1151 continue;
1152 } else if ("permission".equals(name)) {
1153 String perm = parser.getAttributeValue(null, "name");
1154 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001155 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 + parser.getPositionDescription());
1157 XmlUtils.skipCurrentTag(parser);
1158 continue;
1159 }
1160 perm = perm.intern();
1161 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 } else if ("assign-permission".equals(name)) {
1164 String perm = parser.getAttributeValue(null, "name");
1165 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001166 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 + parser.getPositionDescription());
1168 XmlUtils.skipCurrentTag(parser);
1169 continue;
1170 }
1171 String uidStr = parser.getAttributeValue(null, "uid");
1172 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001173 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 + parser.getPositionDescription());
1175 XmlUtils.skipCurrentTag(parser);
1176 continue;
1177 }
1178 int uid = Process.getUidForName(uidStr);
1179 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001180 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 + uidStr + "\" at "
1182 + parser.getPositionDescription());
1183 XmlUtils.skipCurrentTag(parser);
1184 continue;
1185 }
1186 perm = perm.intern();
1187 HashSet<String> perms = mSystemPermissions.get(uid);
1188 if (perms == null) {
1189 perms = new HashSet<String>();
1190 mSystemPermissions.put(uid, perms);
1191 }
1192 perms.add(perm);
1193 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 } else if ("library".equals(name)) {
1196 String lname = parser.getAttributeValue(null, "name");
1197 String lfile = parser.getAttributeValue(null, "file");
1198 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001199 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 + parser.getPositionDescription());
1201 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001202 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 + parser.getPositionDescription());
1204 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001205 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001206 mSharedLibraries.put(lname, lfile);
1207 }
1208 XmlUtils.skipCurrentTag(parser);
1209 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001210
Dianne Hackborn49237342009-08-27 20:08:01 -07001211 } else if ("feature".equals(name)) {
1212 String fname = parser.getAttributeValue(null, "name");
1213 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001214 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001215 + parser.getPositionDescription());
1216 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001217 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001218 FeatureInfo fi = new FeatureInfo();
1219 fi.name = fname;
1220 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 }
1222 XmlUtils.skipCurrentTag(parser);
1223 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 } else {
1226 XmlUtils.skipCurrentTag(parser);
1227 continue;
1228 }
1229
1230 }
1231 } catch (XmlPullParserException 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 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001234 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 }
1236 }
1237
1238 void readPermission(XmlPullParser parser, String name)
1239 throws IOException, XmlPullParserException {
1240
1241 name = name.intern();
1242
1243 BasePermission bp = mSettings.mPermissions.get(name);
1244 if (bp == null) {
1245 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1246 mSettings.mPermissions.put(name, bp);
1247 }
1248 int outerDepth = parser.getDepth();
1249 int type;
1250 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1251 && (type != XmlPullParser.END_TAG
1252 || parser.getDepth() > outerDepth)) {
1253 if (type == XmlPullParser.END_TAG
1254 || type == XmlPullParser.TEXT) {
1255 continue;
1256 }
1257
1258 String tagName = parser.getName();
1259 if ("group".equals(tagName)) {
1260 String gidStr = parser.getAttributeValue(null, "gid");
1261 if (gidStr != null) {
1262 int gid = Process.getGidForName(gidStr);
1263 bp.gids = appendInt(bp.gids, gid);
1264 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001265 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 + parser.getPositionDescription());
1267 }
1268 }
1269 XmlUtils.skipCurrentTag(parser);
1270 }
1271 }
1272
1273 static int[] appendInt(int[] cur, int val) {
1274 if (cur == null) {
1275 return new int[] { val };
1276 }
1277 final int N = cur.length;
1278 for (int i=0; i<N; i++) {
1279 if (cur[i] == val) {
1280 return cur;
1281 }
1282 }
1283 int[] ret = new int[N+1];
1284 System.arraycopy(cur, 0, ret, 0, N);
1285 ret[N] = val;
1286 return ret;
1287 }
1288
1289 static int[] appendInts(int[] cur, int[] add) {
1290 if (add == null) return cur;
1291 if (cur == null) return add;
1292 final int N = add.length;
1293 for (int i=0; i<N; i++) {
1294 cur = appendInt(cur, add[i]);
1295 }
1296 return cur;
1297 }
1298
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001299 static int[] removeInt(int[] cur, int val) {
1300 if (cur == null) {
1301 return null;
1302 }
1303 final int N = cur.length;
1304 for (int i=0; i<N; i++) {
1305 if (cur[i] == val) {
1306 int[] ret = new int[N-1];
1307 if (i > 0) {
1308 System.arraycopy(cur, 0, ret, 0, i);
1309 }
1310 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001311 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001312 }
1313 return ret;
1314 }
1315 }
1316 return cur;
1317 }
1318
1319 static int[] removeInts(int[] cur, int[] rem) {
1320 if (rem == null) return cur;
1321 if (cur == null) return cur;
1322 final int N = rem.length;
1323 for (int i=0; i<N; i++) {
1324 cur = removeInt(cur, rem[i]);
1325 }
1326 return cur;
1327 }
1328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001330 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1331 // The package has been uninstalled but has retained data and resources.
1332 return PackageParser.generatePackageInfo(p, null, flags);
1333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 final PackageSetting ps = (PackageSetting)p.mExtras;
1335 if (ps == null) {
1336 return null;
1337 }
1338 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1339 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1340 }
1341
1342 public PackageInfo getPackageInfo(String packageName, int flags) {
1343 synchronized (mPackages) {
1344 PackageParser.Package p = mPackages.get(packageName);
1345 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001346 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 + ": " + p);
1348 if (p != null) {
1349 return generatePackageInfo(p, flags);
1350 }
1351 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1352 return generatePackageInfoFromSettingsLP(packageName, flags);
1353 }
1354 }
1355 return null;
1356 }
1357
Dianne Hackborn47096932010-02-11 15:57:09 -08001358 public String[] currentToCanonicalPackageNames(String[] names) {
1359 String[] out = new String[names.length];
1360 synchronized (mPackages) {
1361 for (int i=names.length-1; i>=0; i--) {
1362 PackageSetting ps = mSettings.mPackages.get(names[i]);
1363 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1364 }
1365 }
1366 return out;
1367 }
1368
1369 public String[] canonicalToCurrentPackageNames(String[] names) {
1370 String[] out = new String[names.length];
1371 synchronized (mPackages) {
1372 for (int i=names.length-1; i>=0; i--) {
1373 String cur = mSettings.mRenamedPackages.get(names[i]);
1374 out[i] = cur != null ? cur : names[i];
1375 }
1376 }
1377 return out;
1378 }
1379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 public int getPackageUid(String packageName) {
1381 synchronized (mPackages) {
1382 PackageParser.Package p = mPackages.get(packageName);
1383 if(p != null) {
1384 return p.applicationInfo.uid;
1385 }
1386 PackageSetting ps = mSettings.mPackages.get(packageName);
1387 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1388 return -1;
1389 }
1390 p = ps.pkg;
1391 return p != null ? p.applicationInfo.uid : -1;
1392 }
1393 }
1394
1395 public int[] getPackageGids(String packageName) {
1396 synchronized (mPackages) {
1397 PackageParser.Package p = mPackages.get(packageName);
1398 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001399 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 + ": " + p);
1401 if (p != null) {
1402 final PackageSetting ps = (PackageSetting)p.mExtras;
1403 final SharedUserSetting suid = ps.sharedUser;
1404 return suid != null ? suid.gids : ps.gids;
1405 }
1406 }
1407 // stupid thing to indicate an error.
1408 return new int[0];
1409 }
1410
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001411 static final PermissionInfo generatePermissionInfo(
1412 BasePermission bp, int flags) {
1413 if (bp.perm != null) {
1414 return PackageParser.generatePermissionInfo(bp.perm, flags);
1415 }
1416 PermissionInfo pi = new PermissionInfo();
1417 pi.name = bp.name;
1418 pi.packageName = bp.sourcePackage;
1419 pi.nonLocalizedLabel = bp.name;
1420 pi.protectionLevel = bp.protectionLevel;
1421 return pi;
1422 }
1423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 public PermissionInfo getPermissionInfo(String name, int flags) {
1425 synchronized (mPackages) {
1426 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001427 if (p != null) {
1428 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 }
1430 return null;
1431 }
1432 }
1433
1434 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1435 synchronized (mPackages) {
1436 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1437 for (BasePermission p : mSettings.mPermissions.values()) {
1438 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001439 if (p.perm == null || p.perm.info.group == null) {
1440 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 }
1442 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001443 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1445 }
1446 }
1447 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 if (out.size() > 0) {
1450 return out;
1451 }
1452 return mPermissionGroups.containsKey(group) ? out : null;
1453 }
1454 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1457 synchronized (mPackages) {
1458 return PackageParser.generatePermissionGroupInfo(
1459 mPermissionGroups.get(name), flags);
1460 }
1461 }
1462
1463 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1464 synchronized (mPackages) {
1465 final int N = mPermissionGroups.size();
1466 ArrayList<PermissionGroupInfo> out
1467 = new ArrayList<PermissionGroupInfo>(N);
1468 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1469 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1470 }
1471 return out;
1472 }
1473 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1476 PackageSetting ps = mSettings.mPackages.get(packageName);
1477 if(ps != null) {
1478 if(ps.pkg == null) {
1479 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1480 if(pInfo != null) {
1481 return pInfo.applicationInfo;
1482 }
1483 return null;
1484 }
1485 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1486 }
1487 return null;
1488 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1491 PackageSetting ps = mSettings.mPackages.get(packageName);
1492 if(ps != null) {
1493 if(ps.pkg == null) {
1494 ps.pkg = new PackageParser.Package(packageName);
1495 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001496 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1497 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1498 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1499 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001500 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 }
1502 return generatePackageInfo(ps.pkg, flags);
1503 }
1504 return null;
1505 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1508 synchronized (mPackages) {
1509 PackageParser.Package p = mPackages.get(packageName);
1510 if (Config.LOGV) Log.v(
1511 TAG, "getApplicationInfo " + packageName
1512 + ": " + p);
1513 if (p != null) {
1514 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001515 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 }
1517 if ("android".equals(packageName)||"system".equals(packageName)) {
1518 return mAndroidApplication;
1519 }
1520 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1521 return generateApplicationInfoFromSettingsLP(packageName, flags);
1522 }
1523 }
1524 return null;
1525 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001526
1527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1529 mContext.enforceCallingOrSelfPermission(
1530 android.Manifest.permission.CLEAR_APP_CACHE, null);
1531 // Queue up an async operation since clearing cache may take a little while.
1532 mHandler.post(new Runnable() {
1533 public void run() {
1534 mHandler.removeCallbacks(this);
1535 int retCode = -1;
1536 if (mInstaller != null) {
1537 retCode = mInstaller.freeCache(freeStorageSize);
1538 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001539 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 }
1541 } //end if mInstaller
1542 if (observer != null) {
1543 try {
1544 observer.onRemoveCompleted(null, (retCode >= 0));
1545 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001546 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 }
1548 }
1549 }
1550 });
1551 }
1552
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001553 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001554 mContext.enforceCallingOrSelfPermission(
1555 android.Manifest.permission.CLEAR_APP_CACHE, null);
1556 // Queue up an async operation since clearing cache may take a little while.
1557 mHandler.post(new Runnable() {
1558 public void run() {
1559 mHandler.removeCallbacks(this);
1560 int retCode = -1;
1561 if (mInstaller != null) {
1562 retCode = mInstaller.freeCache(freeStorageSize);
1563 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001564 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001565 }
1566 }
1567 if(pi != null) {
1568 try {
1569 // Callback via pending intent
1570 int code = (retCode >= 0) ? 1 : 0;
1571 pi.sendIntent(null, code, null,
1572 null, null);
1573 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001574 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001575 }
1576 }
1577 }
1578 });
1579 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1582 synchronized (mPackages) {
1583 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001584
1585 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001587 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 }
1589 if (mResolveComponentName.equals(component)) {
1590 return mResolveActivity;
1591 }
1592 }
1593 return null;
1594 }
1595
1596 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1597 synchronized (mPackages) {
1598 PackageParser.Activity a = mReceivers.mActivities.get(component);
1599 if (Config.LOGV) Log.v(
1600 TAG, "getReceiverInfo " + component + ": " + a);
1601 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1602 return PackageParser.generateActivityInfo(a, flags);
1603 }
1604 }
1605 return null;
1606 }
1607
1608 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1609 synchronized (mPackages) {
1610 PackageParser.Service s = mServices.mServices.get(component);
1611 if (Config.LOGV) Log.v(
1612 TAG, "getServiceInfo " + component + ": " + s);
1613 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1614 return PackageParser.generateServiceInfo(s, flags);
1615 }
1616 }
1617 return null;
1618 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 public String[] getSystemSharedLibraryNames() {
1621 Set<String> libSet;
1622 synchronized (mPackages) {
1623 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001624 int size = libSet.size();
1625 if (size > 0) {
1626 String[] libs = new String[size];
1627 libSet.toArray(libs);
1628 return libs;
1629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001631 return null;
1632 }
1633
1634 public FeatureInfo[] getSystemAvailableFeatures() {
1635 Collection<FeatureInfo> featSet;
1636 synchronized (mPackages) {
1637 featSet = mAvailableFeatures.values();
1638 int size = featSet.size();
1639 if (size > 0) {
1640 FeatureInfo[] features = new FeatureInfo[size+1];
1641 featSet.toArray(features);
1642 FeatureInfo fi = new FeatureInfo();
1643 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1644 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1645 features[size] = fi;
1646 return features;
1647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 }
1649 return null;
1650 }
1651
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001652 public boolean hasSystemFeature(String name) {
1653 synchronized (mPackages) {
1654 return mAvailableFeatures.containsKey(name);
1655 }
1656 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 public int checkPermission(String permName, String pkgName) {
1659 synchronized (mPackages) {
1660 PackageParser.Package p = mPackages.get(pkgName);
1661 if (p != null && p.mExtras != null) {
1662 PackageSetting ps = (PackageSetting)p.mExtras;
1663 if (ps.sharedUser != null) {
1664 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1665 return PackageManager.PERMISSION_GRANTED;
1666 }
1667 } else if (ps.grantedPermissions.contains(permName)) {
1668 return PackageManager.PERMISSION_GRANTED;
1669 }
1670 }
1671 }
1672 return PackageManager.PERMISSION_DENIED;
1673 }
1674
1675 public int checkUidPermission(String permName, int uid) {
1676 synchronized (mPackages) {
1677 Object obj = mSettings.getUserIdLP(uid);
1678 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001679 GrantedPermissions gp = (GrantedPermissions)obj;
1680 if (gp.grantedPermissions.contains(permName)) {
1681 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 }
1683 } else {
1684 HashSet<String> perms = mSystemPermissions.get(uid);
1685 if (perms != null && perms.contains(permName)) {
1686 return PackageManager.PERMISSION_GRANTED;
1687 }
1688 }
1689 }
1690 return PackageManager.PERMISSION_DENIED;
1691 }
1692
1693 private BasePermission findPermissionTreeLP(String permName) {
1694 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1695 if (permName.startsWith(bp.name) &&
1696 permName.length() > bp.name.length() &&
1697 permName.charAt(bp.name.length()) == '.') {
1698 return bp;
1699 }
1700 }
1701 return null;
1702 }
1703
1704 private BasePermission checkPermissionTreeLP(String permName) {
1705 if (permName != null) {
1706 BasePermission bp = findPermissionTreeLP(permName);
1707 if (bp != null) {
1708 if (bp.uid == Binder.getCallingUid()) {
1709 return bp;
1710 }
1711 throw new SecurityException("Calling uid "
1712 + Binder.getCallingUid()
1713 + " is not allowed to add to permission tree "
1714 + bp.name + " owned by uid " + bp.uid);
1715 }
1716 }
1717 throw new SecurityException("No permission tree found for " + permName);
1718 }
1719
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001720 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1721 if (s1 == null) {
1722 return s2 == null;
1723 }
1724 if (s2 == null) {
1725 return false;
1726 }
1727 if (s1.getClass() != s2.getClass()) {
1728 return false;
1729 }
1730 return s1.equals(s2);
1731 }
1732
1733 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1734 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001735 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001736 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1737 if (!compareStrings(pi1.name, pi2.name)) return false;
1738 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1739 // We'll take care of setting this one.
1740 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1741 // These are not currently stored in settings.
1742 //if (!compareStrings(pi1.group, pi2.group)) return false;
1743 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1744 //if (pi1.labelRes != pi2.labelRes) return false;
1745 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1746 return true;
1747 }
1748
1749 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1750 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1751 throw new SecurityException("Label must be specified in permission");
1752 }
1753 BasePermission tree = checkPermissionTreeLP(info.name);
1754 BasePermission bp = mSettings.mPermissions.get(info.name);
1755 boolean added = bp == null;
1756 boolean changed = true;
1757 if (added) {
1758 bp = new BasePermission(info.name, tree.sourcePackage,
1759 BasePermission.TYPE_DYNAMIC);
1760 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1761 throw new SecurityException(
1762 "Not allowed to modify non-dynamic permission "
1763 + info.name);
1764 } else {
1765 if (bp.protectionLevel == info.protectionLevel
1766 && bp.perm.owner.equals(tree.perm.owner)
1767 && bp.uid == tree.uid
1768 && comparePermissionInfos(bp.perm.info, info)) {
1769 changed = false;
1770 }
1771 }
1772 bp.protectionLevel = info.protectionLevel;
1773 bp.perm = new PackageParser.Permission(tree.perm.owner,
1774 new PermissionInfo(info));
1775 bp.perm.info.packageName = tree.perm.info.packageName;
1776 bp.uid = tree.uid;
1777 if (added) {
1778 mSettings.mPermissions.put(info.name, bp);
1779 }
1780 if (changed) {
1781 if (!async) {
1782 mSettings.writeLP();
1783 } else {
1784 scheduleWriteSettingsLocked();
1785 }
1786 }
1787 return added;
1788 }
1789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 public boolean addPermission(PermissionInfo info) {
1791 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001792 return addPermissionLocked(info, false);
1793 }
1794 }
1795
1796 public boolean addPermissionAsync(PermissionInfo info) {
1797 synchronized (mPackages) {
1798 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 }
1800 }
1801
1802 public void removePermission(String name) {
1803 synchronized (mPackages) {
1804 checkPermissionTreeLP(name);
1805 BasePermission bp = mSettings.mPermissions.get(name);
1806 if (bp != null) {
1807 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1808 throw new SecurityException(
1809 "Not allowed to modify non-dynamic permission "
1810 + name);
1811 }
1812 mSettings.mPermissions.remove(name);
1813 mSettings.writeLP();
1814 }
1815 }
1816 }
1817
Dianne Hackborn854060af2009-07-09 18:14:31 -07001818 public boolean isProtectedBroadcast(String actionName) {
1819 synchronized (mPackages) {
1820 return mProtectedBroadcasts.contains(actionName);
1821 }
1822 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 public int checkSignatures(String pkg1, String pkg2) {
1825 synchronized (mPackages) {
1826 PackageParser.Package p1 = mPackages.get(pkg1);
1827 PackageParser.Package p2 = mPackages.get(pkg2);
1828 if (p1 == null || p1.mExtras == null
1829 || p2 == null || p2.mExtras == null) {
1830 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1831 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001832 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 }
1834 }
1835
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001836 public int checkUidSignatures(int uid1, int uid2) {
1837 synchronized (mPackages) {
1838 Signature[] s1;
1839 Signature[] s2;
1840 Object obj = mSettings.getUserIdLP(uid1);
1841 if (obj != null) {
1842 if (obj instanceof SharedUserSetting) {
1843 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1844 } else if (obj instanceof PackageSetting) {
1845 s1 = ((PackageSetting)obj).signatures.mSignatures;
1846 } else {
1847 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1848 }
1849 } else {
1850 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1851 }
1852 obj = mSettings.getUserIdLP(uid2);
1853 if (obj != null) {
1854 if (obj instanceof SharedUserSetting) {
1855 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1856 } else if (obj instanceof PackageSetting) {
1857 s2 = ((PackageSetting)obj).signatures.mSignatures;
1858 } else {
1859 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1860 }
1861 } else {
1862 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1863 }
1864 return checkSignaturesLP(s1, s2);
1865 }
1866 }
1867
1868 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1869 if (s1 == null) {
1870 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1872 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1873 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001874 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1876 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001877 HashSet<Signature> set1 = new HashSet<Signature>();
1878 for (Signature sig : s1) {
1879 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001881 HashSet<Signature> set2 = new HashSet<Signature>();
1882 for (Signature sig : s2) {
1883 set2.add(sig);
1884 }
1885 // Make sure s2 contains all signatures in s1.
1886 if (set1.equals(set2)) {
1887 return PackageManager.SIGNATURE_MATCH;
1888 }
1889 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 }
1891
1892 public String[] getPackagesForUid(int uid) {
1893 synchronized (mPackages) {
1894 Object obj = mSettings.getUserIdLP(uid);
1895 if (obj instanceof SharedUserSetting) {
1896 SharedUserSetting sus = (SharedUserSetting)obj;
1897 final int N = sus.packages.size();
1898 String[] res = new String[N];
1899 Iterator<PackageSetting> it = sus.packages.iterator();
1900 int i=0;
1901 while (it.hasNext()) {
1902 res[i++] = it.next().name;
1903 }
1904 return res;
1905 } else if (obj instanceof PackageSetting) {
1906 PackageSetting ps = (PackageSetting)obj;
1907 return new String[] { ps.name };
1908 }
1909 }
1910 return null;
1911 }
1912
1913 public String getNameForUid(int uid) {
1914 synchronized (mPackages) {
1915 Object obj = mSettings.getUserIdLP(uid);
1916 if (obj instanceof SharedUserSetting) {
1917 SharedUserSetting sus = (SharedUserSetting)obj;
1918 return sus.name + ":" + sus.userId;
1919 } else if (obj instanceof PackageSetting) {
1920 PackageSetting ps = (PackageSetting)obj;
1921 return ps.name;
1922 }
1923 }
1924 return null;
1925 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 public int getUidForSharedUser(String sharedUserName) {
1928 if(sharedUserName == null) {
1929 return -1;
1930 }
1931 synchronized (mPackages) {
1932 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1933 if(suid == null) {
1934 return -1;
1935 }
1936 return suid.userId;
1937 }
1938 }
1939
1940 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1941 int flags) {
1942 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001943 return chooseBestActivity(intent, resolvedType, flags, query);
1944 }
1945
Mihai Predaeae850c2009-05-13 10:13:48 +02001946 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1947 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 if (query != null) {
1949 final int N = query.size();
1950 if (N == 1) {
1951 return query.get(0);
1952 } else if (N > 1) {
1953 // If there is more than one activity with the same priority,
1954 // then let the user decide between them.
1955 ResolveInfo r0 = query.get(0);
1956 ResolveInfo r1 = query.get(1);
1957 if (false) {
1958 System.out.println(r0.activityInfo.name +
1959 "=" + r0.priority + " vs " +
1960 r1.activityInfo.name +
1961 "=" + r1.priority);
1962 }
1963 // If the first activity has a higher priority, or a different
1964 // default, then it is always desireable to pick it.
1965 if (r0.priority != r1.priority
1966 || r0.preferredOrder != r1.preferredOrder
1967 || r0.isDefault != r1.isDefault) {
1968 return query.get(0);
1969 }
1970 // If we have saved a preference for a preferred activity for
1971 // this Intent, use that.
1972 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1973 flags, query, r0.priority);
1974 if (ri != null) {
1975 return ri;
1976 }
1977 return mResolveInfo;
1978 }
1979 }
1980 return null;
1981 }
1982
1983 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1984 int flags, List<ResolveInfo> query, int priority) {
1985 synchronized (mPackages) {
1986 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1987 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001988 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1990 if (prefs != null && prefs.size() > 0) {
1991 // First figure out how good the original match set is.
1992 // We will only allow preferred activities that came
1993 // from the same match quality.
1994 int match = 0;
1995 final int N = query.size();
1996 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1997 for (int j=0; j<N; j++) {
1998 ResolveInfo ri = query.get(j);
1999 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2000 + ": 0x" + Integer.toHexString(match));
2001 if (ri.match > match) match = ri.match;
2002 }
2003 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2004 + Integer.toHexString(match));
2005 match &= IntentFilter.MATCH_CATEGORY_MASK;
2006 final int M = prefs.size();
2007 for (int i=0; i<M; i++) {
2008 PreferredActivity pa = prefs.get(i);
2009 if (pa.mMatch != match) {
2010 continue;
2011 }
2012 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2013 if (DEBUG_PREFERRED) {
2014 Log.v(TAG, "Got preferred activity:");
2015 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
2016 }
2017 if (ai != null) {
2018 for (int j=0; j<N; j++) {
2019 ResolveInfo ri = query.get(j);
2020 if (!ri.activityInfo.applicationInfo.packageName
2021 .equals(ai.applicationInfo.packageName)) {
2022 continue;
2023 }
2024 if (!ri.activityInfo.name.equals(ai.name)) {
2025 continue;
2026 }
2027
2028 // Okay we found a previously set preferred app.
2029 // If the result set is different from when this
2030 // was created, we need to clear it and re-ask the
2031 // user their preference.
2032 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002033 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 + intent + " type " + resolvedType);
2035 mSettings.mPreferredActivities.removeFilter(pa);
2036 return null;
2037 }
2038
2039 // Yay!
2040 return ri;
2041 }
2042 }
2043 }
2044 }
2045 }
2046 return null;
2047 }
2048
2049 public List<ResolveInfo> queryIntentActivities(Intent intent,
2050 String resolvedType, int flags) {
2051 ComponentName comp = intent.getComponent();
2052 if (comp != null) {
2053 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2054 ActivityInfo ai = getActivityInfo(comp, flags);
2055 if (ai != null) {
2056 ResolveInfo ri = new ResolveInfo();
2057 ri.activityInfo = ai;
2058 list.add(ri);
2059 }
2060 return list;
2061 }
2062
2063 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002064 String pkgName = intent.getPackage();
2065 if (pkgName == null) {
2066 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2067 resolvedType, flags);
2068 }
2069 PackageParser.Package pkg = mPackages.get(pkgName);
2070 if (pkg != null) {
2071 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2072 resolvedType, flags, pkg.activities);
2073 }
2074 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 }
2076 }
2077
2078 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2079 Intent[] specifics, String[] specificTypes, Intent intent,
2080 String resolvedType, int flags) {
2081 final String resultsAction = intent.getAction();
2082
2083 List<ResolveInfo> results = queryIntentActivities(
2084 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2085 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2086
2087 int specificsPos = 0;
2088 int N;
2089
2090 // todo: note that the algorithm used here is O(N^2). This
2091 // isn't a problem in our current environment, but if we start running
2092 // into situations where we have more than 5 or 10 matches then this
2093 // should probably be changed to something smarter...
2094
2095 // First we go through and resolve each of the specific items
2096 // that were supplied, taking care of removing any corresponding
2097 // duplicate items in the generic resolve list.
2098 if (specifics != null) {
2099 for (int i=0; i<specifics.length; i++) {
2100 final Intent sintent = specifics[i];
2101 if (sintent == null) {
2102 continue;
2103 }
2104
2105 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2106 String action = sintent.getAction();
2107 if (resultsAction != null && resultsAction.equals(action)) {
2108 // If this action was explicitly requested, then don't
2109 // remove things that have it.
2110 action = null;
2111 }
2112 ComponentName comp = sintent.getComponent();
2113 ResolveInfo ri = null;
2114 ActivityInfo ai = null;
2115 if (comp == null) {
2116 ri = resolveIntent(
2117 sintent,
2118 specificTypes != null ? specificTypes[i] : null,
2119 flags);
2120 if (ri == null) {
2121 continue;
2122 }
2123 if (ri == mResolveInfo) {
2124 // ACK! Must do something better with this.
2125 }
2126 ai = ri.activityInfo;
2127 comp = new ComponentName(ai.applicationInfo.packageName,
2128 ai.name);
2129 } else {
2130 ai = getActivityInfo(comp, flags);
2131 if (ai == null) {
2132 continue;
2133 }
2134 }
2135
2136 // Look for any generic query activities that are duplicates
2137 // of this specific one, and remove them from the results.
2138 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2139 N = results.size();
2140 int j;
2141 for (j=specificsPos; j<N; j++) {
2142 ResolveInfo sri = results.get(j);
2143 if ((sri.activityInfo.name.equals(comp.getClassName())
2144 && sri.activityInfo.applicationInfo.packageName.equals(
2145 comp.getPackageName()))
2146 || (action != null && sri.filter.matchAction(action))) {
2147 results.remove(j);
2148 if (Config.LOGV) Log.v(
2149 TAG, "Removing duplicate item from " + j
2150 + " due to specific " + specificsPos);
2151 if (ri == null) {
2152 ri = sri;
2153 }
2154 j--;
2155 N--;
2156 }
2157 }
2158
2159 // Add this specific item to its proper place.
2160 if (ri == null) {
2161 ri = new ResolveInfo();
2162 ri.activityInfo = ai;
2163 }
2164 results.add(specificsPos, ri);
2165 ri.specificIndex = i;
2166 specificsPos++;
2167 }
2168 }
2169
2170 // Now we go through the remaining generic results and remove any
2171 // duplicate actions that are found here.
2172 N = results.size();
2173 for (int i=specificsPos; i<N-1; i++) {
2174 final ResolveInfo rii = results.get(i);
2175 if (rii.filter == null) {
2176 continue;
2177 }
2178
2179 // Iterate over all of the actions of this result's intent
2180 // filter... typically this should be just one.
2181 final Iterator<String> it = rii.filter.actionsIterator();
2182 if (it == null) {
2183 continue;
2184 }
2185 while (it.hasNext()) {
2186 final String action = it.next();
2187 if (resultsAction != null && resultsAction.equals(action)) {
2188 // If this action was explicitly requested, then don't
2189 // remove things that have it.
2190 continue;
2191 }
2192 for (int j=i+1; j<N; j++) {
2193 final ResolveInfo rij = results.get(j);
2194 if (rij.filter != null && rij.filter.hasAction(action)) {
2195 results.remove(j);
2196 if (Config.LOGV) Log.v(
2197 TAG, "Removing duplicate item from " + j
2198 + " due to action " + action + " at " + i);
2199 j--;
2200 N--;
2201 }
2202 }
2203 }
2204
2205 // If the caller didn't request filter information, drop it now
2206 // so we don't have to marshall/unmarshall it.
2207 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2208 rii.filter = null;
2209 }
2210 }
2211
2212 // Filter out the caller activity if so requested.
2213 if (caller != null) {
2214 N = results.size();
2215 for (int i=0; i<N; i++) {
2216 ActivityInfo ainfo = results.get(i).activityInfo;
2217 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2218 && caller.getClassName().equals(ainfo.name)) {
2219 results.remove(i);
2220 break;
2221 }
2222 }
2223 }
2224
2225 // If the caller didn't request filter information,
2226 // drop them now so we don't have to
2227 // marshall/unmarshall it.
2228 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2229 N = results.size();
2230 for (int i=0; i<N; i++) {
2231 results.get(i).filter = null;
2232 }
2233 }
2234
2235 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2236 return results;
2237 }
2238
2239 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2240 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002241 ComponentName comp = intent.getComponent();
2242 if (comp != null) {
2243 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2244 ActivityInfo ai = getReceiverInfo(comp, flags);
2245 if (ai != null) {
2246 ResolveInfo ri = new ResolveInfo();
2247 ri.activityInfo = ai;
2248 list.add(ri);
2249 }
2250 return list;
2251 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002253 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002254 String pkgName = intent.getPackage();
2255 if (pkgName == null) {
2256 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2257 resolvedType, flags);
2258 }
2259 PackageParser.Package pkg = mPackages.get(pkgName);
2260 if (pkg != null) {
2261 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2262 resolvedType, flags, pkg.receivers);
2263 }
2264 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002265 }
2266 }
2267
2268 public ResolveInfo resolveService(Intent intent, String resolvedType,
2269 int flags) {
2270 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2271 flags);
2272 if (query != null) {
2273 if (query.size() >= 1) {
2274 // If there is more than one service with the same priority,
2275 // just arbitrarily pick the first one.
2276 return query.get(0);
2277 }
2278 }
2279 return null;
2280 }
2281
2282 public List<ResolveInfo> queryIntentServices(Intent intent,
2283 String resolvedType, int flags) {
2284 ComponentName comp = intent.getComponent();
2285 if (comp != null) {
2286 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2287 ServiceInfo si = getServiceInfo(comp, flags);
2288 if (si != null) {
2289 ResolveInfo ri = new ResolveInfo();
2290 ri.serviceInfo = si;
2291 list.add(ri);
2292 }
2293 return list;
2294 }
2295
2296 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002297 String pkgName = intent.getPackage();
2298 if (pkgName == null) {
2299 return (List<ResolveInfo>)mServices.queryIntent(intent,
2300 resolvedType, flags);
2301 }
2302 PackageParser.Package pkg = mPackages.get(pkgName);
2303 if (pkg != null) {
2304 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2305 resolvedType, flags, pkg.services);
2306 }
2307 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 }
2309 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 public List<PackageInfo> getInstalledPackages(int flags) {
2312 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2313
2314 synchronized (mPackages) {
2315 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2316 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2317 while (i.hasNext()) {
2318 final PackageSetting ps = i.next();
2319 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2320 if(psPkg != null) {
2321 finalList.add(psPkg);
2322 }
2323 }
2324 }
2325 else {
2326 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2327 while (i.hasNext()) {
2328 final PackageParser.Package p = i.next();
2329 if (p.applicationInfo != null) {
2330 PackageInfo pi = generatePackageInfo(p, flags);
2331 if(pi != null) {
2332 finalList.add(pi);
2333 }
2334 }
2335 }
2336 }
2337 }
2338 return finalList;
2339 }
2340
2341 public List<ApplicationInfo> getInstalledApplications(int flags) {
2342 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2343 synchronized(mPackages) {
2344 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2345 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2346 while (i.hasNext()) {
2347 final PackageSetting ps = i.next();
2348 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2349 if(ai != null) {
2350 finalList.add(ai);
2351 }
2352 }
2353 }
2354 else {
2355 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2356 while (i.hasNext()) {
2357 final PackageParser.Package p = i.next();
2358 if (p.applicationInfo != null) {
2359 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2360 if(ai != null) {
2361 finalList.add(ai);
2362 }
2363 }
2364 }
2365 }
2366 }
2367 return finalList;
2368 }
2369
2370 public List<ApplicationInfo> getPersistentApplications(int flags) {
2371 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2372
2373 synchronized (mPackages) {
2374 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2375 while (i.hasNext()) {
2376 PackageParser.Package p = i.next();
2377 if (p.applicationInfo != null
2378 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2379 && (!mSafeMode || (p.applicationInfo.flags
2380 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
Jey2eebf5c2009-11-18 18:37:31 -08002381 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002382 }
2383 }
2384 }
2385
2386 return finalList;
2387 }
2388
2389 public ProviderInfo resolveContentProvider(String name, int flags) {
2390 synchronized (mPackages) {
2391 final PackageParser.Provider provider = mProviders.get(name);
2392 return provider != null
2393 && mSettings.isEnabledLP(provider.info, flags)
2394 && (!mSafeMode || (provider.info.applicationInfo.flags
2395 &ApplicationInfo.FLAG_SYSTEM) != 0)
2396 ? PackageParser.generateProviderInfo(provider, flags)
2397 : null;
2398 }
2399 }
2400
Fred Quintana718d8a22009-04-29 17:53:20 -07002401 /**
2402 * @deprecated
2403 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002404 public void querySyncProviders(List outNames, List outInfo) {
2405 synchronized (mPackages) {
2406 Iterator<Map.Entry<String, PackageParser.Provider>> i
2407 = mProviders.entrySet().iterator();
2408
2409 while (i.hasNext()) {
2410 Map.Entry<String, PackageParser.Provider> entry = i.next();
2411 PackageParser.Provider p = entry.getValue();
2412
2413 if (p.syncable
2414 && (!mSafeMode || (p.info.applicationInfo.flags
2415 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2416 outNames.add(entry.getKey());
2417 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2418 }
2419 }
2420 }
2421 }
2422
2423 public List<ProviderInfo> queryContentProviders(String processName,
2424 int uid, int flags) {
2425 ArrayList<ProviderInfo> finalList = null;
2426
2427 synchronized (mPackages) {
2428 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2429 while (i.hasNext()) {
2430 PackageParser.Provider p = i.next();
2431 if (p.info.authority != null
2432 && (processName == null ||
2433 (p.info.processName.equals(processName)
2434 && p.info.applicationInfo.uid == uid))
2435 && mSettings.isEnabledLP(p.info, flags)
2436 && (!mSafeMode || (p.info.applicationInfo.flags
2437 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2438 if (finalList == null) {
2439 finalList = new ArrayList<ProviderInfo>(3);
2440 }
2441 finalList.add(PackageParser.generateProviderInfo(p,
2442 flags));
2443 }
2444 }
2445 }
2446
2447 if (finalList != null) {
2448 Collections.sort(finalList, mProviderInitOrderSorter);
2449 }
2450
2451 return finalList;
2452 }
2453
2454 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2455 int flags) {
2456 synchronized (mPackages) {
2457 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2458 return PackageParser.generateInstrumentationInfo(i, flags);
2459 }
2460 }
2461
2462 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2463 int flags) {
2464 ArrayList<InstrumentationInfo> finalList =
2465 new ArrayList<InstrumentationInfo>();
2466
2467 synchronized (mPackages) {
2468 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2469 while (i.hasNext()) {
2470 PackageParser.Instrumentation p = i.next();
2471 if (targetPackage == null
2472 || targetPackage.equals(p.info.targetPackage)) {
2473 finalList.add(PackageParser.generateInstrumentationInfo(p,
2474 flags));
2475 }
2476 }
2477 }
2478
2479 return finalList;
2480 }
2481
2482 private void scanDirLI(File dir, int flags, int scanMode) {
2483 Log.d(TAG, "Scanning app dir " + dir);
2484
2485 String[] files = dir.list();
2486
2487 int i;
2488 for (i=0; i<files.length; i++) {
2489 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002490 if (!isPackageFilename(files[i])) {
2491 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002492 continue;
2493 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002494 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002496 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002497 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2498 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002499 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002500 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002501 file.delete();
2502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 }
2504 }
2505
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002506 private static File getSettingsProblemFile() {
2507 File dataDir = Environment.getDataDirectory();
2508 File systemDir = new File(dataDir, "system");
2509 File fname = new File(systemDir, "uiderrors.txt");
2510 return fname;
2511 }
2512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 private static void reportSettingsProblem(int priority, String msg) {
2514 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002515 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 FileOutputStream out = new FileOutputStream(fname, true);
2517 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002518 SimpleDateFormat formatter = new SimpleDateFormat();
2519 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2520 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 pw.close();
2522 FileUtils.setPermissions(
2523 fname.toString(),
2524 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2525 -1, -1);
2526 } catch (java.io.IOException e) {
2527 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002528 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 }
2530
2531 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2532 PackageParser.Package pkg, File srcFile, int parseFlags) {
2533 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002534 if (ps != null
2535 && ps.codePath.equals(srcFile)
2536 && ps.getTimeStamp() == srcFile.lastModified()) {
2537 if (ps.signatures.mSignatures != null
2538 && ps.signatures.mSignatures.length != 0) {
2539 // Optimization: reuse the existing cached certificates
2540 // if the package appears to be unchanged.
2541 pkg.mSignatures = ps.signatures.mSignatures;
2542 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 }
Jeff Browne7600722010-04-07 18:28:23 -07002544
2545 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002546 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002547 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2548 }
2549
2550 if (!pp.collectCertificates(pkg, parseFlags)) {
2551 mLastScanError = pp.getParseError();
2552 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553 }
2554 }
2555 return true;
2556 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 /*
2559 * Scan a package and return the newly parsed package.
2560 * Returns null in case of errors and the error code is stored in mLastScanError
2561 */
2562 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002563 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002565 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002567 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002570 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 if (pkg == null) {
2572 mLastScanError = pp.getParseError();
2573 return null;
2574 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002575 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 PackageSetting updatedPkg;
2577 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002578 // Look to see if we already know about this package.
2579 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002580 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002581 // This package has been renamed to its original name. Let's
2582 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002583 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002584 }
2585 // If there was no original package, see one for the real package name.
2586 if (ps == null) {
2587 ps = mSettings.peekPackageLP(pkg.packageName);
2588 }
2589 // Check to see if this package could be hiding/updating a system
2590 // package. Must look for it either under the original or real
2591 // package name depending on our state.
2592 updatedPkg = mSettings.mDisabledSysPackages.get(
2593 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002595 // First check if this is a system package that may involve an update
2596 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2597 if (!ps.codePath.equals(scanFile)) {
2598 // The path has changed from what was last scanned... check the
2599 // version of the new path against what we have stored to determine
2600 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002601 if (pkg.mVersionCode < ps.versionCode) {
2602 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002603 // Ignore entry. Skip it.
2604 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2605 + "ignored: updated version " + ps.versionCode
2606 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002607 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2608 return null;
2609 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002610 // The current app on the system partion is better than
2611 // what we have updated to on the data partition; switch
2612 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002613 // At this point, its safely assumed that package installation for
2614 // apps in system partition will go through. If not there won't be a working
2615 // version of the app
2616 synchronized (mPackages) {
2617 // Just remove the loaded entries from package lists.
2618 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002619 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002620 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002621 + "reverting from " + ps.codePathString
2622 + ": new version " + pkg.mVersionCode
2623 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002624 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2625 args.cleanUpResourcesLI();
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07002626 removeNativeBinariesLI(pkg);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002627 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 }
2630 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002631 if (updatedPkg != null) {
2632 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2633 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2634 }
2635 // Verify certificates against what was last scanned
2636 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002637 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002638 return null;
2639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 // The apk is forward locked (not public) if its code and resources
2641 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002642 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002643 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002644 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002645 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002646
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002647 String codePath = null;
2648 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002649 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2650 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002651 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002652 } else {
2653 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002654 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002655 }
2656 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002657 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002658 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002659 codePath = pkg.mScanPath;
2660 // Set application objects path explicitly.
2661 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002663 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 }
2665
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002666 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2667 String destCodePath, String destResPath) {
2668 pkg.mPath = pkg.mScanPath = destCodePath;
2669 pkg.applicationInfo.sourceDir = destCodePath;
2670 pkg.applicationInfo.publicSourceDir = destResPath;
2671 }
2672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 private static String fixProcessName(String defProcessName,
2674 String processName, int uid) {
2675 if (processName == null) {
2676 return defProcessName;
2677 }
2678 return processName;
2679 }
2680
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002681 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002682 PackageParser.Package pkg) {
2683 if (pkgSetting.signatures.mSignatures != null) {
2684 // Already existing package. Make sure signatures match
2685 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2686 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002687 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002688 + " signatures do not match the previously installed version; ignoring!");
2689 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 return false;
2691 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002692 }
2693 // Check for shared user signatures
2694 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2695 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2696 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2697 Slog.e(TAG, "Package " + pkg.packageName
2698 + " has no signatures that match those in shared user "
2699 + pkgSetting.sharedUser.name + "; ignoring!");
2700 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2701 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 }
2704 return true;
2705 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002706
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002707 public boolean performDexOpt(String packageName) {
2708 if (!mNoDexOpt) {
2709 return false;
2710 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002711
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002712 PackageParser.Package p;
2713 synchronized (mPackages) {
2714 p = mPackages.get(packageName);
2715 if (p == null || p.mDidDexOpt) {
2716 return false;
2717 }
2718 }
2719 synchronized (mInstallLock) {
2720 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2721 }
2722 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002723
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002724 static final int DEX_OPT_SKIPPED = 0;
2725 static final int DEX_OPT_PERFORMED = 1;
2726 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002727
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002728 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2729 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002730 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002731 String path = pkg.mScanPath;
2732 int ret = 0;
2733 try {
2734 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002735 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002736 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002737 pkg.mDidDexOpt = true;
2738 performed = true;
2739 }
2740 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002741 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002742 ret = -1;
2743 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002744 Slog.w(TAG, "IOException reading apk: " + path, e);
2745 ret = -1;
2746 } catch (dalvik.system.StaleDexCacheError e) {
2747 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2748 ret = -1;
2749 } catch (Exception e) {
2750 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002751 ret = -1;
2752 }
2753 if (ret < 0) {
2754 //error from installer
2755 return DEX_OPT_FAILED;
2756 }
2757 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002758
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002759 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2760 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002761
2762 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2763 return Environment.isEncryptedFilesystemEnabled() &&
2764 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2765 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002766
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002767 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2768 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002769 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002770 + " to " + newPkg.packageName
2771 + ": old package not in system partition");
2772 return false;
2773 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002774 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002775 + " to " + newPkg.packageName
2776 + ": old package still exists");
2777 return false;
2778 }
2779 return true;
2780 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002781
2782 private File getDataPathForPackage(PackageParser.Package pkg) {
2783 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2784 File dataPath;
2785 if (useEncryptedFSDir) {
2786 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2787 } else {
2788 dataPath = new File(mAppDataDir, pkg.packageName);
2789 }
2790 return dataPath;
2791 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002792
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002793 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2794 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002795 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002796 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2797 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002798 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002799 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002800 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2801 return null;
2802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 mScanningPath = scanFile;
2804 if (pkg == null) {
2805 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2806 return null;
2807 }
2808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002809 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2810 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2811 }
2812
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002813 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 synchronized (mPackages) {
2815 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002816 Slog.w(TAG, "*************************************************");
2817 Slog.w(TAG, "Core android package being redefined. Skipping.");
2818 Slog.w(TAG, " file=" + mScanningPath);
2819 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2821 return null;
2822 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 // Set up information for our fall-back user intent resolution
2825 // activity.
2826 mPlatformPackage = pkg;
2827 pkg.mVersionCode = mSdkVersion;
2828 mAndroidApplication = pkg.applicationInfo;
2829 mResolveActivity.applicationInfo = mAndroidApplication;
2830 mResolveActivity.name = ResolverActivity.class.getName();
2831 mResolveActivity.packageName = mAndroidApplication.packageName;
2832 mResolveActivity.processName = mAndroidApplication.processName;
2833 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2834 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2835 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2836 mResolveActivity.exported = true;
2837 mResolveActivity.enabled = true;
2838 mResolveInfo.activityInfo = mResolveActivity;
2839 mResolveInfo.priority = 0;
2840 mResolveInfo.preferredOrder = 0;
2841 mResolveInfo.match = 0;
2842 mResolveComponentName = new ComponentName(
2843 mAndroidApplication.packageName, mResolveActivity.name);
2844 }
2845 }
2846
2847 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002848 TAG, "Scanning package " + pkg.packageName);
2849 if (mPackages.containsKey(pkg.packageName)
2850 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002851 Slog.w(TAG, "*************************************************");
2852 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002854 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2856 return null;
2857 }
2858
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002859 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002860 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2861 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 SharedUserSetting suid = null;
2864 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002865
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002866 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2867 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002868 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002869 pkg.mRealPackage = null;
2870 pkg.mAdoptPermissions = null;
2871 }
2872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 synchronized (mPackages) {
2874 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002875 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2876 if (mTmpSharedLibraries == null ||
2877 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2878 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2879 }
2880 int num = 0;
2881 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2882 for (int i=0; i<N; i++) {
2883 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002885 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002887 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2889 return null;
2890 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002891 mTmpSharedLibraries[num] = file;
2892 num++;
2893 }
2894 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2895 for (int i=0; i<N; i++) {
2896 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2897 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002898 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002899 + " desires unavailable shared library "
2900 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2901 } else {
2902 mTmpSharedLibraries[num] = file;
2903 num++;
2904 }
2905 }
2906 if (num > 0) {
2907 pkg.usesLibraryFiles = new String[num];
2908 System.arraycopy(mTmpSharedLibraries, 0,
2909 pkg.usesLibraryFiles, 0, num);
2910 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002911
Dianne Hackborn49237342009-08-27 20:08:01 -07002912 if (pkg.reqFeatures != null) {
2913 N = pkg.reqFeatures.size();
2914 for (int i=0; i<N; i++) {
2915 FeatureInfo fi = pkg.reqFeatures.get(i);
2916 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2917 // Don't care.
2918 continue;
2919 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002920
Dianne Hackborn49237342009-08-27 20:08:01 -07002921 if (fi.name != null) {
2922 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002923 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002924 + " requires unavailable feature "
2925 + fi.name + "; failing!");
2926 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2927 return null;
2928 }
2929 }
2930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 }
2932 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 if (pkg.mSharedUserId != null) {
2935 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2936 pkg.applicationInfo.flags, true);
2937 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002938 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939 + " for shared user failed");
2940 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2941 return null;
2942 }
2943 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2944 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2945 + suid.userId + "): packages=" + suid.packages);
2946 }
2947 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002948
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002949 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002950 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002951 Log.w(TAG, "WAITING FOR DEBUGGER");
2952 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002953 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2954 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002955 }
2956 }
2957
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002958 // Check if we are renaming from an original package name.
2959 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002960 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002961 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002962 // This package may need to be renamed to a previously
2963 // installed name. Let's check on that...
2964 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002965 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002966 // This package had originally been installed as the
2967 // original name, and we have already taken care of
2968 // transitioning to the new one. Just update the new
2969 // one to continue using the old name.
2970 realName = pkg.mRealPackage;
2971 if (!pkg.packageName.equals(renamed)) {
2972 // Callers into this function may have already taken
2973 // care of renaming the package; only do it here if
2974 // it is not already done.
2975 pkg.setPackageName(renamed);
2976 }
2977
Dianne Hackbornc1552392010-03-03 16:19:01 -08002978 } else {
2979 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2980 if ((origPackage=mSettings.peekPackageLP(
2981 pkg.mOriginalPackages.get(i))) != null) {
2982 // We do have the package already installed under its
2983 // original name... should we use it?
2984 if (!verifyPackageUpdate(origPackage, pkg)) {
2985 // New package is not compatible with original.
2986 origPackage = null;
2987 continue;
2988 } else if (origPackage.sharedUser != null) {
2989 // Make sure uid is compatible between packages.
2990 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002991 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002992 + " to " + pkg.packageName + ": old uid "
2993 + origPackage.sharedUser.name
2994 + " differs from " + pkg.mSharedUserId);
2995 origPackage = null;
2996 continue;
2997 }
2998 } else {
2999 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3000 + pkg.packageName + " to old name " + origPackage.name);
3001 }
3002 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003003 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003004 }
3005 }
3006 }
3007
3008 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003009 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003010 + " was transferred to another, but its .apk remains");
3011 }
3012
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003013 // Just create the setting, don't add it yet. For already existing packages
3014 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003015 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016 destResourceFile, pkg.applicationInfo.flags, true, false);
3017 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003018 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003019 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3020 return null;
3021 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003022
3023 if (pkgSetting.origPackage != null) {
3024 // If we are first transitioning from an original package,
3025 // fix up the new package's name now. We need to do this after
3026 // looking up the package under its new name, so getPackageLP
3027 // can take care of fiddling things correctly.
3028 pkg.setPackageName(origPackage.name);
3029
3030 // File a report about this.
3031 String msg = "New package " + pkgSetting.realName
3032 + " renamed to replace old package " + pkgSetting.name;
3033 reportSettingsProblem(Log.WARN, msg);
3034
3035 // Make a note of it.
3036 mTransferedPackages.add(origPackage.name);
3037
3038 // No longer need to retain this.
3039 pkgSetting.origPackage = null;
3040 }
3041
3042 if (realName != null) {
3043 // Make a note of it.
3044 mTransferedPackages.add(pkg.packageName);
3045 }
3046
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003047 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3049 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003051 pkg.applicationInfo.uid = pkgSetting.userId;
3052 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003053
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003054 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003055 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056 return null;
3057 }
3058 // The signature has changed, but this package is in the system
3059 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003060 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003061 // However... if this package is part of a shared user, but it
3062 // doesn't match the signature of the shared user, let's fail.
3063 // What this means is that you can't change the signatures
3064 // associated with an overall shared user, which doesn't seem all
3065 // that unreasonable.
3066 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003067 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3068 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3069 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3071 return null;
3072 }
3073 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003074 // File a report about this.
3075 String msg = "System package " + pkg.packageName
3076 + " signature changed; retaining data.";
3077 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003078 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003079
The Android Open Source Project10592532009-03-18 17:39:46 -07003080 // Verify that this new package doesn't have any content providers
3081 // that conflict with existing packages. Only do this if the
3082 // package isn't already installed, since we don't want to break
3083 // things that are installed.
3084 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3085 int N = pkg.providers.size();
3086 int i;
3087 for (i=0; i<N; i++) {
3088 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003089 if (p.info.authority != null) {
3090 String names[] = p.info.authority.split(";");
3091 for (int j = 0; j < names.length; j++) {
3092 if (mProviders.containsKey(names[j])) {
3093 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003094 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003095 " (in package " + pkg.applicationInfo.packageName +
3096 ") is already used by "
3097 + ((other != null && other.getComponentName() != null)
3098 ? other.getComponentName().getPackageName() : "?"));
3099 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3100 return null;
3101 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003102 }
3103 }
3104 }
3105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003106 }
3107
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003108 final String pkgName = pkg.packageName;
3109
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003110 if (pkg.mAdoptPermissions != null) {
3111 // This package wants to adopt ownership of permissions from
3112 // another package.
3113 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3114 String origName = pkg.mAdoptPermissions.get(i);
3115 PackageSetting orig = mSettings.peekPackageLP(origName);
3116 if (orig != null) {
3117 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003118 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003119 + origName + " to " + pkg.packageName);
3120 mSettings.transferPermissions(origName, pkg.packageName);
3121 }
3122 }
3123 }
3124 }
3125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 long scanFileTime = scanFile.lastModified();
3127 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3128 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3129 pkg.applicationInfo.processName = fixProcessName(
3130 pkg.applicationInfo.packageName,
3131 pkg.applicationInfo.processName,
3132 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003133
3134 File dataPath;
3135 if (mPlatformPackage == pkg) {
3136 // The system package is special.
3137 dataPath = new File (Environment.getDataDirectory(), "system");
3138 pkg.applicationInfo.dataDir = dataPath.getPath();
3139 } else {
3140 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003141 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003142 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003143
3144 boolean uidError = false;
3145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146 if (dataPath.exists()) {
3147 mOutPermissions[1] = 0;
3148 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3149 if (mOutPermissions[1] == pkg.applicationInfo.uid
3150 || !Process.supportsProcesses()) {
3151 pkg.applicationInfo.dataDir = dataPath.getPath();
3152 } else {
3153 boolean recovered = false;
3154 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3155 // If this is a system app, we can at least delete its
3156 // current data so the application will still work.
3157 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003158 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003159 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003160 // Old data gone!
3161 String msg = "System package " + pkg.packageName
3162 + " has changed from uid: "
3163 + mOutPermissions[1] + " to "
3164 + pkg.applicationInfo.uid + "; old data erased";
3165 reportSettingsProblem(Log.WARN, msg);
3166 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003167
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003168 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003169 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003170 pkg.applicationInfo.uid);
3171 if (ret == -1) {
3172 // Ack should not happen!
3173 msg = "System package " + pkg.packageName
3174 + " could not have data directory re-created after delete.";
3175 reportSettingsProblem(Log.WARN, msg);
3176 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3177 return null;
3178 }
3179 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003181 if (!recovered) {
3182 mHasSystemUidErrors = true;
3183 }
3184 }
3185 if (!recovered) {
3186 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3187 + pkg.applicationInfo.uid + "/fs_"
3188 + mOutPermissions[1];
3189 String msg = "Package " + pkg.packageName
3190 + " has mismatched uid: "
3191 + mOutPermissions[1] + " on disk, "
3192 + pkg.applicationInfo.uid + " in settings";
3193 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003194 mSettings.mReadMessages.append(msg);
3195 mSettings.mReadMessages.append('\n');
3196 uidError = true;
3197 if (!pkgSetting.uidError) {
3198 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003200 }
3201 }
3202 }
3203 pkg.applicationInfo.dataDir = dataPath.getPath();
3204 } else {
3205 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3206 Log.v(TAG, "Want this data dir: " + dataPath);
3207 //invoke installer to do the actual installation
3208 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003209 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 pkg.applicationInfo.uid);
3211 if(ret < 0) {
3212 // Error from installer
3213 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3214 return null;
3215 }
3216 } else {
3217 dataPath.mkdirs();
3218 if (dataPath.exists()) {
3219 FileUtils.setPermissions(
3220 dataPath.toString(),
3221 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3222 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3223 }
3224 }
3225 if (dataPath.exists()) {
3226 pkg.applicationInfo.dataDir = dataPath.getPath();
3227 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003228 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 pkg.applicationInfo.dataDir = null;
3230 }
3231 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003232
3233 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003234 }
3235
3236 // Perform shared library installation and dex validation and
3237 // optimization, if this is not a system app.
3238 if (mInstaller != null) {
3239 String path = scanFile.getPath();
3240 if (scanFileNewer) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003241 // Note: We don't want to unpack the native binaries for
3242 // system applications, unless they have been updated
3243 // (the binaries are already under /system/lib).
3244 //
3245 // In other words, we're going to unpack the binaries
3246 // only for non-system apps and system app upgrades.
3247 //
3248 int flags = pkg.applicationInfo.flags;
3249 if ((flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
3250 (flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3251 Log.i(TAG, path + " changed; unpacking");
3252 int err = cachePackageSharedLibsLI(pkg, scanFile);
3253 if (err != PackageManager.INSTALL_SUCCEEDED) {
3254 mLastScanError = err;
3255 return null;
3256 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 }
3258 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003259 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003260
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003261 if ((scanMode&SCAN_NO_DEX) == 0) {
3262 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3264 return null;
3265 }
3266 }
3267 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 if (mFactoryTest && pkg.requestedPermissions.contains(
3270 android.Manifest.permission.FACTORY_TEST)) {
3271 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3272 }
3273
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003274 // Request the ActivityManager to kill the process(only for existing packages)
3275 // so that we do not end up in a confused state while the user is still using the older
3276 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003277 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003278 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003279 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003280 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003282 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003283 // We don't expect installation to fail beyond this point,
3284 if ((scanMode&SCAN_MONITOR) != 0) {
3285 mAppDirs.put(pkg.mPath, pkg);
3286 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003288 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003290 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003291 // Make sure we don't accidentally delete its data.
3292 mSettings.mPackagesToBeCleaned.remove(pkgName);
3293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294 int N = pkg.providers.size();
3295 StringBuilder r = null;
3296 int i;
3297 for (i=0; i<N; i++) {
3298 PackageParser.Provider p = pkg.providers.get(i);
3299 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3300 p.info.processName, pkg.applicationInfo.uid);
3301 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3302 p.info.name), p);
3303 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003304 if (p.info.authority != null) {
3305 String names[] = p.info.authority.split(";");
3306 p.info.authority = null;
3307 for (int j = 0; j < names.length; j++) {
3308 if (j == 1 && p.syncable) {
3309 // We only want the first authority for a provider to possibly be
3310 // syncable, so if we already added this provider using a different
3311 // authority clear the syncable flag. We copy the provider before
3312 // changing it because the mProviders object contains a reference
3313 // to a provider that we don't want to change.
3314 // Only do this for the second authority since the resulting provider
3315 // object can be the same for all future authorities for this provider.
3316 p = new PackageParser.Provider(p);
3317 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003318 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003319 if (!mProviders.containsKey(names[j])) {
3320 mProviders.put(names[j], p);
3321 if (p.info.authority == null) {
3322 p.info.authority = names[j];
3323 } else {
3324 p.info.authority = p.info.authority + ";" + names[j];
3325 }
3326 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3327 Log.d(TAG, "Registered content provider: " + names[j] +
3328 ", className = " + p.info.name +
3329 ", isSyncable = " + p.info.isSyncable);
3330 } else {
3331 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003332 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003333 " (in package " + pkg.applicationInfo.packageName +
3334 "): name already used by "
3335 + ((other != null && other.getComponentName() != null)
3336 ? other.getComponentName().getPackageName() : "?"));
3337 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 }
3339 }
3340 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3341 if (r == null) {
3342 r = new StringBuilder(256);
3343 } else {
3344 r.append(' ');
3345 }
3346 r.append(p.info.name);
3347 }
3348 }
3349 if (r != null) {
3350 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3351 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 N = pkg.services.size();
3354 r = null;
3355 for (i=0; i<N; i++) {
3356 PackageParser.Service s = pkg.services.get(i);
3357 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3358 s.info.processName, pkg.applicationInfo.uid);
3359 mServices.addService(s);
3360 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3361 if (r == null) {
3362 r = new StringBuilder(256);
3363 } else {
3364 r.append(' ');
3365 }
3366 r.append(s.info.name);
3367 }
3368 }
3369 if (r != null) {
3370 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3371 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003373 N = pkg.receivers.size();
3374 r = null;
3375 for (i=0; i<N; i++) {
3376 PackageParser.Activity a = pkg.receivers.get(i);
3377 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3378 a.info.processName, pkg.applicationInfo.uid);
3379 mReceivers.addActivity(a, "receiver");
3380 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3381 if (r == null) {
3382 r = new StringBuilder(256);
3383 } else {
3384 r.append(' ');
3385 }
3386 r.append(a.info.name);
3387 }
3388 }
3389 if (r != null) {
3390 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3391 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 N = pkg.activities.size();
3394 r = null;
3395 for (i=0; i<N; i++) {
3396 PackageParser.Activity a = pkg.activities.get(i);
3397 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3398 a.info.processName, pkg.applicationInfo.uid);
3399 mActivities.addActivity(a, "activity");
3400 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3401 if (r == null) {
3402 r = new StringBuilder(256);
3403 } else {
3404 r.append(' ');
3405 }
3406 r.append(a.info.name);
3407 }
3408 }
3409 if (r != null) {
3410 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3411 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 N = pkg.permissionGroups.size();
3414 r = null;
3415 for (i=0; i<N; i++) {
3416 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3417 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3418 if (cur == null) {
3419 mPermissionGroups.put(pg.info.name, pg);
3420 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3421 if (r == null) {
3422 r = new StringBuilder(256);
3423 } else {
3424 r.append(' ');
3425 }
3426 r.append(pg.info.name);
3427 }
3428 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003429 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 + pg.info.packageName + " ignored: original from "
3431 + cur.info.packageName);
3432 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3433 if (r == null) {
3434 r = new StringBuilder(256);
3435 } else {
3436 r.append(' ');
3437 }
3438 r.append("DUP:");
3439 r.append(pg.info.name);
3440 }
3441 }
3442 }
3443 if (r != null) {
3444 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3445 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003447 N = pkg.permissions.size();
3448 r = null;
3449 for (i=0; i<N; i++) {
3450 PackageParser.Permission p = pkg.permissions.get(i);
3451 HashMap<String, BasePermission> permissionMap =
3452 p.tree ? mSettings.mPermissionTrees
3453 : mSettings.mPermissions;
3454 p.group = mPermissionGroups.get(p.info.group);
3455 if (p.info.group == null || p.group != null) {
3456 BasePermission bp = permissionMap.get(p.info.name);
3457 if (bp == null) {
3458 bp = new BasePermission(p.info.name, p.info.packageName,
3459 BasePermission.TYPE_NORMAL);
3460 permissionMap.put(p.info.name, bp);
3461 }
3462 if (bp.perm == null) {
3463 if (bp.sourcePackage == null
3464 || bp.sourcePackage.equals(p.info.packageName)) {
3465 BasePermission tree = findPermissionTreeLP(p.info.name);
3466 if (tree == null
3467 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003468 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003469 bp.perm = p;
3470 bp.uid = pkg.applicationInfo.uid;
3471 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3472 if (r == null) {
3473 r = new StringBuilder(256);
3474 } else {
3475 r.append(' ');
3476 }
3477 r.append(p.info.name);
3478 }
3479 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003480 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481 + p.info.packageName + " ignored: base tree "
3482 + tree.name + " is from package "
3483 + tree.sourcePackage);
3484 }
3485 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003486 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003487 + p.info.packageName + " ignored: original from "
3488 + bp.sourcePackage);
3489 }
3490 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3491 if (r == null) {
3492 r = new StringBuilder(256);
3493 } else {
3494 r.append(' ');
3495 }
3496 r.append("DUP:");
3497 r.append(p.info.name);
3498 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003499 if (bp.perm == p) {
3500 bp.protectionLevel = p.info.protectionLevel;
3501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003502 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003503 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003504 + p.info.packageName + " ignored: no group "
3505 + p.group);
3506 }
3507 }
3508 if (r != null) {
3509 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3510 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003512 N = pkg.instrumentation.size();
3513 r = null;
3514 for (i=0; i<N; i++) {
3515 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3516 a.info.packageName = pkg.applicationInfo.packageName;
3517 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3518 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3519 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003520 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003521 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3522 if (r == null) {
3523 r = new StringBuilder(256);
3524 } else {
3525 r.append(' ');
3526 }
3527 r.append(a.info.name);
3528 }
3529 }
3530 if (r != null) {
3531 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3532 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003533
Dianne Hackborn854060af2009-07-09 18:14:31 -07003534 if (pkg.protectedBroadcasts != null) {
3535 N = pkg.protectedBroadcasts.size();
3536 for (i=0; i<N; i++) {
3537 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3538 }
3539 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 pkgSetting.setTimeStamp(scanFileTime);
3542 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003544 return pkg;
3545 }
3546
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003547 private void killApplication(String pkgName, int uid) {
3548 // Request the ActivityManager to kill the process(only for existing packages)
3549 // so that we do not end up in a confused state while the user is still using the older
3550 // version of the application while the new one gets installed.
3551 IActivityManager am = ActivityManagerNative.getDefault();
3552 if (am != null) {
3553 try {
3554 am.killApplicationWithUid(pkgName, uid);
3555 } catch (RemoteException e) {
3556 }
3557 }
3558 }
3559
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003560 // The following constants are returned by cachePackageSharedLibsForAbiLI
3561 // to indicate if native shared libraries were found in the package.
3562 // Values are:
3563 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3564 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3565 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3566 // in package (and not installed)
3567 //
3568 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3569 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3570 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003572 // Return the path of the directory that will contain the native binaries
3573 // of a given installed package. This is relative to the data path.
3574 //
3575 private static File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3576 return new File(pkg.applicationInfo.dataDir + "/lib");
3577 }
3578
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003579 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3580 // and automatically copy them to /data/data/<appname>/lib if present.
3581 //
3582 // NOTE: this method may throw an IOException if the library cannot
3583 // be copied to its final destination, e.g. if there isn't enough
3584 // room left on the data partition, or a ZipException if the package
3585 // file is malformed.
3586 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003587 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003588 File scanFile, String cpuAbi) throws IOException, ZipException {
3589 File sharedLibraryDir = getNativeBinaryDirForPackage(pkg);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003590 final String apkLib = "lib/";
3591 final int apkLibLen = apkLib.length();
3592 final int cpuAbiLen = cpuAbi.length();
3593 final String libPrefix = "lib";
3594 final int libPrefixLen = libPrefix.length();
3595 final String libSuffix = ".so";
3596 final int libSuffixLen = libSuffix.length();
3597 boolean hasNativeLibraries = false;
3598 boolean installedNativeLibraries = false;
3599
3600 // the minimum length of a valid native shared library of the form
3601 // lib/<something>/lib<name>.so.
3602 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3603
3604 ZipFile zipFile = new ZipFile(scanFile);
3605 Enumeration<ZipEntry> entries =
3606 (Enumeration<ZipEntry>) zipFile.entries();
3607
3608 while (entries.hasMoreElements()) {
3609 ZipEntry entry = entries.nextElement();
3610 // skip directories
3611 if (entry.isDirectory()) {
3612 continue;
3613 }
3614 String entryName = entry.getName();
3615
3616 // check that the entry looks like lib/<something>/lib<name>.so
3617 // here, but don't check the ABI just yet.
3618 //
3619 // - must be sufficiently long
3620 // - must end with libSuffix, i.e. ".so"
3621 // - must start with apkLib, i.e. "lib/"
3622 if (entryName.length() < minEntryLen ||
3623 !entryName.endsWith(libSuffix) ||
3624 !entryName.startsWith(apkLib) ) {
3625 continue;
3626 }
3627
3628 // file name must start with libPrefix, i.e. "lib"
3629 int lastSlash = entryName.lastIndexOf('/');
3630
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003631 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003632 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3633 continue;
3634 }
3635
3636 hasNativeLibraries = true;
3637
3638 // check the cpuAbi now, between lib/ and /lib<name>.so
3639 //
3640 if (lastSlash != apkLibLen + cpuAbiLen ||
3641 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3642 continue;
3643
3644 // extract the library file name, ensure it doesn't contain
3645 // weird characters. we're guaranteed here that it doesn't contain
3646 // a directory separator though.
3647 String libFileName = entryName.substring(lastSlash+1);
3648 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3649 continue;
3650 }
3651
3652 installedNativeLibraries = true;
3653
David 'Digit' Turner63909292010-06-03 14:37:42 -07003654 // Always extract the shared library
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003655 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3656 File.separator + libFileName;
3657 File sharedLibraryFile = new File(sharedLibraryFilePath);
David 'Digit' Turner63909292010-06-03 14:37:42 -07003658
3659 if (Config.LOGD) {
3660 Log.d(TAG, "Caching shared lib " + entry.getName());
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003661 }
David 'Digit' Turner63909292010-06-03 14:37:42 -07003662 if (mInstaller == null) {
3663 sharedLibraryDir.mkdir();
3664 }
3665 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
3666 sharedLibraryFile);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003667 }
3668 if (!hasNativeLibraries)
3669 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3670
3671 if (!installedNativeLibraries)
3672 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3673
3674 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3675 }
3676
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003677 // Find the gdbserver executable program in a package at
3678 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3679 //
3680 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3681 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3682 //
3683 private int cachePackageGdbServerLI(PackageParser.Package pkg,
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003684 File scanFile, String cpuAbi) throws IOException, ZipException {
3685 File installGdbServerDir = getNativeBinaryDirForPackage(pkg);
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003686 final String GDBSERVER = "gdbserver";
3687 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3688
3689 ZipFile zipFile = new ZipFile(scanFile);
3690 Enumeration<ZipEntry> entries =
3691 (Enumeration<ZipEntry>) zipFile.entries();
3692
3693 while (entries.hasMoreElements()) {
3694 ZipEntry entry = entries.nextElement();
3695 // skip directories
3696 if (entry.isDirectory()) {
3697 continue;
3698 }
3699 String entryName = entry.getName();
3700
3701 if (!entryName.equals(apkGdbServerPath)) {
3702 continue;
3703 }
3704
3705 String installGdbServerPath = installGdbServerDir.getPath() +
3706 "/" + GDBSERVER;
3707 File installGdbServerFile = new File(installGdbServerPath);
David 'Digit' Turner63909292010-06-03 14:37:42 -07003708
3709 if (Config.LOGD) {
3710 Log.d(TAG, "Caching gdbserver " + entry.getName());
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003711 }
David 'Digit' Turner63909292010-06-03 14:37:42 -07003712 if (mInstaller == null) {
3713 installGdbServerDir.mkdir();
3714 }
3715 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3716 installGdbServerFile);
3717
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003718 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3719 }
3720 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3721 }
3722
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003723 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3724 // and copy them to /data/data/<appname>/lib.
3725 //
3726 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3727 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3728 // one if ro.product.cpu.abi2 is defined.
3729 //
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003730 private int cachePackageSharedLibsLI(PackageParser.Package pkg, File scanFile) {
David 'Digit' Turner63909292010-06-03 14:37:42 -07003731 // Remove all native binaries from a directory. This is used when upgrading
3732 // a package: in case the new .apk doesn't contain a native binary that was
3733 // in the old one (and thus installed), we need to remove it from
3734 // /data/data/<appname>/lib
3735 //
3736 // The simplest way to do that is to remove all files in this directory,
3737 // since it is owned by "system", applications are not supposed to write
3738 // anything there.
3739 removeNativeBinariesLI(pkg);
3740
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003741 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003742 try {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003743 int result = cachePackageSharedLibsForAbiLI(pkg, scanFile, cpuAbi);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003744
3745 // some architectures are capable of supporting several CPU ABIs
3746 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3747 // this is indicated by the definition of the ro.product.cpu.abi2
3748 // system property.
3749 //
3750 // only scan the package twice in case of ABI mismatch
3751 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003752 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003753 if (cpuAbi2 != null) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003754 result = cachePackageSharedLibsForAbiLI(pkg, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003756
3757 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003758 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003759 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003760 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003761
3762 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3763 cpuAbi = cpuAbi2;
3764 }
3765 }
3766
3767 // for debuggable packages, also extract gdbserver from lib/<abi>
3768 // into /data/data/<appname>/lib too.
3769 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3770 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003771 int result2 = cachePackageGdbServerLI(pkg, scanFile, cpuAbi);
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003772 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3773 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003775 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003776 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003777 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003778 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003779 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003780 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003781 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003782 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003783 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003784 }
3785
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003786 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003787 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003788 File binaryDir,
3789 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790 InputStream inputStream = zipFile.getInputStream(entry);
3791 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003792 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003794 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795 // now need to be left as world readable and owned by the system.
3796 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3797 ! tempFile.setLastModified(entry.getTime()) ||
3798 FileUtils.setPermissions(tempFilePath,
3799 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003800 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003802 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003803 // Failed to properly write file.
3804 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003805 throw new IOException("Couldn't create cached binary "
3806 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003807 }
3808 } finally {
3809 inputStream.close();
3810 }
3811 }
3812
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003813 // Remove the native binaries of a given package. This simply
3814 // gets rid of the files in the 'lib' sub-directory.
3815 private void removeNativeBinariesLI(PackageParser.Package pkg) {
3816 File binaryDir = getNativeBinaryDirForPackage(pkg);
3817
3818 if (DEBUG_NATIVE) {
3819 Slog.w(TAG,"Deleting native binaries from: " + binaryDir.getPath());
3820 }
3821
3822 // Just remove any file in the directory. Since the directory
3823 // is owned by the 'system' UID, the application is not supposed
3824 // to have written anything there.
3825 //
3826 if (binaryDir.exists()) {
3827 File[] binaries = binaryDir.listFiles();
3828 if (binaries != null) {
3829 for (int nn=0; nn < binaries.length; nn++) {
3830 if (DEBUG_NATIVE) {
3831 Slog.d(TAG," Deleting " + binaries[nn].getName());
3832 }
3833 if (!binaries[nn].delete()) {
3834 Slog.w(TAG,"Could not delete native binary: " +
3835 binaries[nn].getPath());
3836 }
3837 }
3838 }
3839 // Do not delete 'lib' directory itself, or this will prevent
3840 // installation of future updates.
3841 }
3842 }
3843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003844 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3845 if (chatty && Config.LOGD) Log.d(
3846 TAG, "Removing package " + pkg.applicationInfo.packageName );
3847
3848 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 mPackages.remove(pkg.applicationInfo.packageName);
3852 if (pkg.mPath != null) {
3853 mAppDirs.remove(pkg.mPath);
3854 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003856 PackageSetting ps = (PackageSetting)pkg.mExtras;
3857 if (ps != null && ps.sharedUser != null) {
3858 // XXX don't do this until the data is removed.
3859 if (false) {
3860 ps.sharedUser.packages.remove(ps);
3861 if (ps.sharedUser.packages.size() == 0) {
3862 // Remove.
3863 }
3864 }
3865 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 int N = pkg.providers.size();
3868 StringBuilder r = null;
3869 int i;
3870 for (i=0; i<N; i++) {
3871 PackageParser.Provider p = pkg.providers.get(i);
3872 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3873 p.info.name));
3874 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003875
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876 /* The is another ContentProvider with this authority when
3877 * this app was installed so this authority is null,
3878 * Ignore it as we don't have to unregister the provider.
3879 */
3880 continue;
3881 }
3882 String names[] = p.info.authority.split(";");
3883 for (int j = 0; j < names.length; j++) {
3884 if (mProviders.get(names[j]) == p) {
3885 mProviders.remove(names[j]);
3886 if (chatty && Config.LOGD) Log.d(
3887 TAG, "Unregistered content provider: " + names[j] +
3888 ", className = " + p.info.name +
3889 ", isSyncable = " + p.info.isSyncable);
3890 }
3891 }
3892 if (chatty) {
3893 if (r == null) {
3894 r = new StringBuilder(256);
3895 } else {
3896 r.append(' ');
3897 }
3898 r.append(p.info.name);
3899 }
3900 }
3901 if (r != null) {
3902 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3903 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 N = pkg.services.size();
3906 r = null;
3907 for (i=0; i<N; i++) {
3908 PackageParser.Service s = pkg.services.get(i);
3909 mServices.removeService(s);
3910 if (chatty) {
3911 if (r == null) {
3912 r = new StringBuilder(256);
3913 } else {
3914 r.append(' ');
3915 }
3916 r.append(s.info.name);
3917 }
3918 }
3919 if (r != null) {
3920 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3921 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003923 N = pkg.receivers.size();
3924 r = null;
3925 for (i=0; i<N; i++) {
3926 PackageParser.Activity a = pkg.receivers.get(i);
3927 mReceivers.removeActivity(a, "receiver");
3928 if (chatty) {
3929 if (r == null) {
3930 r = new StringBuilder(256);
3931 } else {
3932 r.append(' ');
3933 }
3934 r.append(a.info.name);
3935 }
3936 }
3937 if (r != null) {
3938 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3939 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 N = pkg.activities.size();
3942 r = null;
3943 for (i=0; i<N; i++) {
3944 PackageParser.Activity a = pkg.activities.get(i);
3945 mActivities.removeActivity(a, "activity");
3946 if (chatty) {
3947 if (r == null) {
3948 r = new StringBuilder(256);
3949 } else {
3950 r.append(' ');
3951 }
3952 r.append(a.info.name);
3953 }
3954 }
3955 if (r != null) {
3956 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3957 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 N = pkg.permissions.size();
3960 r = null;
3961 for (i=0; i<N; i++) {
3962 PackageParser.Permission p = pkg.permissions.get(i);
3963 boolean tree = false;
3964 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3965 if (bp == null) {
3966 tree = true;
3967 bp = mSettings.mPermissionTrees.get(p.info.name);
3968 }
3969 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003970 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003971 if (chatty) {
3972 if (r == null) {
3973 r = new StringBuilder(256);
3974 } else {
3975 r.append(' ');
3976 }
3977 r.append(p.info.name);
3978 }
3979 }
3980 }
3981 if (r != null) {
3982 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3983 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003985 N = pkg.instrumentation.size();
3986 r = null;
3987 for (i=0; i<N; i++) {
3988 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003989 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003990 if (chatty) {
3991 if (r == null) {
3992 r = new StringBuilder(256);
3993 } else {
3994 r.append(' ');
3995 }
3996 r.append(a.info.name);
3997 }
3998 }
3999 if (r != null) {
4000 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
4001 }
4002 }
4003 }
4004
4005 private static final boolean isPackageFilename(String name) {
4006 return name != null && name.endsWith(".apk");
4007 }
4008
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004009 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
4010 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
4011 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
4012 return true;
4013 }
4014 }
4015 return false;
4016 }
4017
4018 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004019 PackageParser.Package pkgInfo, boolean grantPermissions,
4020 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 // Make sure there are no dangling permission trees.
4022 Iterator<BasePermission> it = mSettings.mPermissionTrees
4023 .values().iterator();
4024 while (it.hasNext()) {
4025 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004026 if (bp.packageSetting == null) {
4027 // We may not yet have parsed the package, so just see if
4028 // we still know about its settings.
4029 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4030 }
4031 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004032 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 + " from package " + bp.sourcePackage);
4034 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004035 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4036 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4037 Slog.i(TAG, "Removing old permission tree: " + bp.name
4038 + " from package " + bp.sourcePackage);
4039 grantPermissions = true;
4040 it.remove();
4041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004042 }
4043 }
4044
4045 // Make sure all dynamic permissions have been assigned to a package,
4046 // and make sure there are no dangling permissions.
4047 it = mSettings.mPermissions.values().iterator();
4048 while (it.hasNext()) {
4049 BasePermission bp = it.next();
4050 if (bp.type == BasePermission.TYPE_DYNAMIC) {
4051 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
4052 + bp.name + " pkg=" + bp.sourcePackage
4053 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004054 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004055 BasePermission tree = findPermissionTreeLP(bp.name);
4056 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004057 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004058 bp.perm = new PackageParser.Permission(tree.perm.owner,
4059 new PermissionInfo(bp.pendingInfo));
4060 bp.perm.info.packageName = tree.perm.info.packageName;
4061 bp.perm.info.name = bp.name;
4062 bp.uid = tree.uid;
4063 }
4064 }
4065 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004066 if (bp.packageSetting == null) {
4067 // We may not yet have parsed the package, so just see if
4068 // we still know about its settings.
4069 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4070 }
4071 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004072 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004073 + " from package " + bp.sourcePackage);
4074 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004075 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4076 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4077 Slog.i(TAG, "Removing old permission: " + bp.name
4078 + " from package " + bp.sourcePackage);
4079 grantPermissions = true;
4080 it.remove();
4081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004082 }
4083 }
4084
4085 // Now update the permissions for all packages, in particular
4086 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004087 if (grantPermissions) {
4088 for (PackageParser.Package pkg : mPackages.values()) {
4089 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004090 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004091 }
4092 }
4093 }
4094
4095 if (pkgInfo != null) {
4096 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 }
4098 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004100 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
4101 final PackageSetting ps = (PackageSetting)pkg.mExtras;
4102 if (ps == null) {
4103 return;
4104 }
4105 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004106 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004108 if (replace) {
4109 ps.permissionsFixed = false;
4110 if (gp == ps) {
4111 gp.grantedPermissions.clear();
4112 gp.gids = mGlobalGids;
4113 }
4114 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004116 if (gp.gids == null) {
4117 gp.gids = mGlobalGids;
4118 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004120 final int N = pkg.requestedPermissions.size();
4121 for (int i=0; i<N; i++) {
4122 String name = pkg.requestedPermissions.get(i);
4123 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004124 if (false) {
4125 if (gp != ps) {
4126 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004127 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004128 }
4129 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004130 if (bp != null && bp.packageSetting != null) {
4131 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004133 boolean allowedSig = false;
4134 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
4135 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004136 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07004137 } else if (bp.packageSetting == null) {
4138 // This permission is invalid; skip it.
4139 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004140 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
4141 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
4142 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004144 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004146 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004147 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4148 // For updated system applications, the signatureOrSystem permission
4149 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004150 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004151 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
4152 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
4153 if(sysPs.grantedPermissions.contains(perm)) {
4154 allowed = true;
4155 } else {
4156 allowed = false;
4157 }
4158 } else {
4159 allowed = true;
4160 }
4161 }
4162 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004163 if (allowed) {
4164 allowedSig = true;
4165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166 } else {
4167 allowed = false;
4168 }
4169 if (false) {
4170 if (gp != ps) {
4171 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4172 }
4173 }
4174 if (allowed) {
4175 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4176 && ps.permissionsFixed) {
4177 // If this is an existing, non-system package, then
4178 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004179 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004181 // Except... if this is a permission that was added
4182 // to the platform (note: need to only do this when
4183 // updating the platform).
4184 final int NP = PackageParser.NEW_PERMISSIONS.length;
4185 for (int ip=0; ip<NP; ip++) {
4186 final PackageParser.NewPermissionInfo npi
4187 = PackageParser.NEW_PERMISSIONS[ip];
4188 if (npi.name.equals(perm)
4189 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4190 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004191 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004192 + pkg.packageName);
4193 break;
4194 }
4195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004196 }
4197 }
4198 if (allowed) {
4199 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004200 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004201 gp.grantedPermissions.add(perm);
4202 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004203 } else if (!ps.haveGids) {
4204 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205 }
4206 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004207 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004208 + " to package " + pkg.packageName
4209 + " because it was previously installed without");
4210 }
4211 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004212 if (gp.grantedPermissions.remove(perm)) {
4213 changedPermission = true;
4214 gp.gids = removeInts(gp.gids, bp.gids);
4215 Slog.i(TAG, "Un-granting permission " + perm
4216 + " from package " + pkg.packageName
4217 + " (protectionLevel=" + bp.protectionLevel
4218 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4219 + ")");
4220 } else {
4221 Slog.w(TAG, "Not granting permission " + perm
4222 + " to package " + pkg.packageName
4223 + " (protectionLevel=" + bp.protectionLevel
4224 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4225 + ")");
4226 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004227 }
4228 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004229 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004230 + " in package " + pkg.packageName);
4231 }
4232 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004233
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004234 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004235 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4236 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004237 // This is the first that we have heard about this package, so the
4238 // permissions we have now selected are fixed until explicitly
4239 // changed.
4240 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004242 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004243 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004245 private final class ActivityIntentResolver
4246 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004247 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004249 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004250 }
4251
Mihai Preda074edef2009-05-18 17:13:31 +02004252 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004253 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004254 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004255 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4256 }
4257
Mihai Predaeae850c2009-05-13 10:13:48 +02004258 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4259 ArrayList<PackageParser.Activity> packageActivities) {
4260 if (packageActivities == null) {
4261 return null;
4262 }
4263 mFlags = flags;
4264 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4265 int N = packageActivities.size();
4266 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4267 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004268
4269 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004270 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004271 intentFilters = packageActivities.get(i).intents;
4272 if (intentFilters != null && intentFilters.size() > 0) {
4273 listCut.add(intentFilters);
4274 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004275 }
4276 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4277 }
4278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004279 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004280 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004281 if (SHOW_INFO || Config.LOGV) Log.v(
4282 TAG, " " + type + " " +
4283 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4284 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4285 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004286 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004287 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4288 if (SHOW_INFO || Config.LOGV) {
4289 Log.v(TAG, " IntentFilter:");
4290 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4291 }
4292 if (!intent.debugCheck()) {
4293 Log.w(TAG, "==> For Activity " + a.info.name);
4294 }
4295 addFilter(intent);
4296 }
4297 }
4298
4299 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004300 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 if (SHOW_INFO || Config.LOGV) Log.v(
4302 TAG, " " + type + " " +
4303 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4304 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4305 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004306 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4308 if (SHOW_INFO || Config.LOGV) {
4309 Log.v(TAG, " IntentFilter:");
4310 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4311 }
4312 removeFilter(intent);
4313 }
4314 }
4315
4316 @Override
4317 protected boolean allowFilterResult(
4318 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4319 ActivityInfo filterAi = filter.activity.info;
4320 for (int i=dest.size()-1; i>=0; i--) {
4321 ActivityInfo destAi = dest.get(i).activityInfo;
4322 if (destAi.name == filterAi.name
4323 && destAi.packageName == filterAi.packageName) {
4324 return false;
4325 }
4326 }
4327 return true;
4328 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004330 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004331 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4332 return info.activity.owner.packageName;
4333 }
4334
4335 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004336 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4337 int match) {
4338 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4339 return null;
4340 }
4341 final PackageParser.Activity activity = info.activity;
4342 if (mSafeMode && (activity.info.applicationInfo.flags
4343 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4344 return null;
4345 }
4346 final ResolveInfo res = new ResolveInfo();
4347 res.activityInfo = PackageParser.generateActivityInfo(activity,
4348 mFlags);
4349 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4350 res.filter = info;
4351 }
4352 res.priority = info.getPriority();
4353 res.preferredOrder = activity.owner.mPreferredOrder;
4354 //System.out.println("Result: " + res.activityInfo.className +
4355 // " = " + res.priority);
4356 res.match = match;
4357 res.isDefault = info.hasDefault;
4358 res.labelRes = info.labelRes;
4359 res.nonLocalizedLabel = info.nonLocalizedLabel;
4360 res.icon = info.icon;
4361 return res;
4362 }
4363
4364 @Override
4365 protected void sortResults(List<ResolveInfo> results) {
4366 Collections.sort(results, mResolvePrioritySorter);
4367 }
4368
4369 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004370 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004371 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004372 out.print(prefix); out.print(
4373 Integer.toHexString(System.identityHashCode(filter.activity)));
4374 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004375 out.print(filter.activity.getComponentShortName());
4376 out.print(" filter ");
4377 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004378 }
4379
4380// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4381// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4382// final List<ResolveInfo> retList = Lists.newArrayList();
4383// while (i.hasNext()) {
4384// final ResolveInfo resolveInfo = i.next();
4385// if (isEnabledLP(resolveInfo.activityInfo)) {
4386// retList.add(resolveInfo);
4387// }
4388// }
4389// return retList;
4390// }
4391
4392 // Keys are String (activity class name), values are Activity.
4393 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4394 = new HashMap<ComponentName, PackageParser.Activity>();
4395 private int mFlags;
4396 }
4397
4398 private final class ServiceIntentResolver
4399 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004400 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004401 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004402 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004403 }
4404
Mihai Preda074edef2009-05-18 17:13:31 +02004405 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004406 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004407 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004408 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4409 }
4410
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004411 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4412 ArrayList<PackageParser.Service> packageServices) {
4413 if (packageServices == null) {
4414 return null;
4415 }
4416 mFlags = flags;
4417 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4418 int N = packageServices.size();
4419 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4420 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4421
4422 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4423 for (int i = 0; i < N; ++i) {
4424 intentFilters = packageServices.get(i).intents;
4425 if (intentFilters != null && intentFilters.size() > 0) {
4426 listCut.add(intentFilters);
4427 }
4428 }
4429 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4430 }
4431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004432 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004433 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004434 if (SHOW_INFO || Config.LOGV) Log.v(
4435 TAG, " " + (s.info.nonLocalizedLabel != null
4436 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4437 if (SHOW_INFO || Config.LOGV) Log.v(
4438 TAG, " Class=" + s.info.name);
4439 int NI = s.intents.size();
4440 int j;
4441 for (j=0; j<NI; j++) {
4442 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4443 if (SHOW_INFO || Config.LOGV) {
4444 Log.v(TAG, " IntentFilter:");
4445 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4446 }
4447 if (!intent.debugCheck()) {
4448 Log.w(TAG, "==> For Service " + s.info.name);
4449 }
4450 addFilter(intent);
4451 }
4452 }
4453
4454 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004455 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004456 if (SHOW_INFO || Config.LOGV) Log.v(
4457 TAG, " " + (s.info.nonLocalizedLabel != null
4458 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4459 if (SHOW_INFO || Config.LOGV) Log.v(
4460 TAG, " Class=" + s.info.name);
4461 int NI = s.intents.size();
4462 int j;
4463 for (j=0; j<NI; j++) {
4464 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4465 if (SHOW_INFO || Config.LOGV) {
4466 Log.v(TAG, " IntentFilter:");
4467 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4468 }
4469 removeFilter(intent);
4470 }
4471 }
4472
4473 @Override
4474 protected boolean allowFilterResult(
4475 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4476 ServiceInfo filterSi = filter.service.info;
4477 for (int i=dest.size()-1; i>=0; i--) {
4478 ServiceInfo destAi = dest.get(i).serviceInfo;
4479 if (destAi.name == filterSi.name
4480 && destAi.packageName == filterSi.packageName) {
4481 return false;
4482 }
4483 }
4484 return true;
4485 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004487 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004488 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4489 return info.service.owner.packageName;
4490 }
4491
4492 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004493 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4494 int match) {
4495 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4496 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4497 return null;
4498 }
4499 final PackageParser.Service service = info.service;
4500 if (mSafeMode && (service.info.applicationInfo.flags
4501 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4502 return null;
4503 }
4504 final ResolveInfo res = new ResolveInfo();
4505 res.serviceInfo = PackageParser.generateServiceInfo(service,
4506 mFlags);
4507 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4508 res.filter = filter;
4509 }
4510 res.priority = info.getPriority();
4511 res.preferredOrder = service.owner.mPreferredOrder;
4512 //System.out.println("Result: " + res.activityInfo.className +
4513 // " = " + res.priority);
4514 res.match = match;
4515 res.isDefault = info.hasDefault;
4516 res.labelRes = info.labelRes;
4517 res.nonLocalizedLabel = info.nonLocalizedLabel;
4518 res.icon = info.icon;
4519 return res;
4520 }
4521
4522 @Override
4523 protected void sortResults(List<ResolveInfo> results) {
4524 Collections.sort(results, mResolvePrioritySorter);
4525 }
4526
4527 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004528 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004529 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004530 out.print(prefix); out.print(
4531 Integer.toHexString(System.identityHashCode(filter.service)));
4532 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004533 out.print(filter.service.getComponentShortName());
4534 out.print(" filter ");
4535 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004536 }
4537
4538// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4539// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4540// final List<ResolveInfo> retList = Lists.newArrayList();
4541// while (i.hasNext()) {
4542// final ResolveInfo resolveInfo = (ResolveInfo) i;
4543// if (isEnabledLP(resolveInfo.serviceInfo)) {
4544// retList.add(resolveInfo);
4545// }
4546// }
4547// return retList;
4548// }
4549
4550 // Keys are String (activity class name), values are Activity.
4551 private final HashMap<ComponentName, PackageParser.Service> mServices
4552 = new HashMap<ComponentName, PackageParser.Service>();
4553 private int mFlags;
4554 };
4555
4556 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4557 new Comparator<ResolveInfo>() {
4558 public int compare(ResolveInfo r1, ResolveInfo r2) {
4559 int v1 = r1.priority;
4560 int v2 = r2.priority;
4561 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4562 if (v1 != v2) {
4563 return (v1 > v2) ? -1 : 1;
4564 }
4565 v1 = r1.preferredOrder;
4566 v2 = r2.preferredOrder;
4567 if (v1 != v2) {
4568 return (v1 > v2) ? -1 : 1;
4569 }
4570 if (r1.isDefault != r2.isDefault) {
4571 return r1.isDefault ? -1 : 1;
4572 }
4573 v1 = r1.match;
4574 v2 = r2.match;
4575 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4576 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4577 }
4578 };
4579
4580 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4581 new Comparator<ProviderInfo>() {
4582 public int compare(ProviderInfo p1, ProviderInfo p2) {
4583 final int v1 = p1.initOrder;
4584 final int v2 = p2.initOrder;
4585 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4586 }
4587 };
4588
Kenny Root93565c4b2010-06-18 15:46:06 -07004589 private static final boolean DEBUG_OBB = false;
4590
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004591 private static final void sendPackageBroadcast(String action, String pkg,
4592 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004593 IActivityManager am = ActivityManagerNative.getDefault();
4594 if (am != null) {
4595 try {
4596 final Intent intent = new Intent(action,
4597 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4598 if (extras != null) {
4599 intent.putExtras(extras);
4600 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004601 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004602 am.broadcastIntent(null, intent, null, finishedReceiver,
4603 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004604 } catch (RemoteException ex) {
4605 }
4606 }
4607 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004608
4609 public String nextPackageToClean(String lastPackage) {
4610 synchronized (mPackages) {
4611 if (!mMediaMounted) {
4612 // If the external storage is no longer mounted at this point,
4613 // the caller may not have been able to delete all of this
4614 // packages files and can not delete any more. Bail.
4615 return null;
4616 }
4617 if (lastPackage != null) {
4618 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4619 }
4620 return mSettings.mPackagesToBeCleaned.size() > 0
4621 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4622 }
4623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004624
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004625 void schedulePackageCleaning(String packageName) {
4626 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4627 }
4628
4629 void startCleaningPackages() {
4630 synchronized (mPackages) {
4631 if (!mMediaMounted) {
4632 return;
4633 }
4634 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4635 return;
4636 }
4637 }
4638 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4639 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4640 IActivityManager am = ActivityManagerNative.getDefault();
4641 if (am != null) {
4642 try {
4643 am.startService(null, intent, null);
4644 } catch (RemoteException e) {
4645 }
4646 }
4647 }
4648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004649 private final class AppDirObserver extends FileObserver {
4650 public AppDirObserver(String path, int mask, boolean isrom) {
4651 super(path, mask);
4652 mRootDir = path;
4653 mIsRom = isrom;
4654 }
4655
4656 public void onEvent(int event, String path) {
4657 String removedPackage = null;
4658 int removedUid = -1;
4659 String addedPackage = null;
4660 int addedUid = -1;
4661
4662 synchronized (mInstallLock) {
4663 String fullPathStr = null;
4664 File fullPath = null;
4665 if (path != null) {
4666 fullPath = new File(mRootDir, path);
4667 fullPathStr = fullPath.getPath();
4668 }
4669
4670 if (Config.LOGV) Log.v(
4671 TAG, "File " + fullPathStr + " changed: "
4672 + Integer.toHexString(event));
4673
4674 if (!isPackageFilename(path)) {
4675 if (Config.LOGV) Log.v(
4676 TAG, "Ignoring change of non-package file: " + fullPathStr);
4677 return;
4678 }
4679
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004680 // Ignore packages that are being installed or
4681 // have just been installed.
4682 if (ignoreCodePath(fullPathStr)) {
4683 return;
4684 }
4685 PackageParser.Package p = null;
4686 synchronized (mPackages) {
4687 p = mAppDirs.get(fullPathStr);
4688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004689 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004690 if (p != null) {
4691 removePackageLI(p, true);
4692 removedPackage = p.applicationInfo.packageName;
4693 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004694 }
4695 }
4696
4697 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004698 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004699 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004700 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4701 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004702 PackageParser.PARSE_CHATTY |
4703 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004704 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004705 if (p != null) {
4706 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004707 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004708 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004709 }
4710 addedPackage = p.applicationInfo.packageName;
4711 addedUid = p.applicationInfo.uid;
4712 }
4713 }
4714 }
4715
4716 synchronized (mPackages) {
4717 mSettings.writeLP();
4718 }
4719 }
4720
4721 if (removedPackage != null) {
4722 Bundle extras = new Bundle(1);
4723 extras.putInt(Intent.EXTRA_UID, removedUid);
4724 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004725 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4726 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004727 }
4728 if (addedPackage != null) {
4729 Bundle extras = new Bundle(1);
4730 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004731 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4732 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004733 }
4734 }
4735
4736 private final String mRootDir;
4737 private final boolean mIsRom;
4738 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004740 /* Called when a downloaded package installation has been confirmed by the user */
4741 public void installPackage(
4742 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004743 installPackage(packageURI, observer, flags, null);
4744 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004745
Jacek Surazski65e13172009-04-28 15:26:38 +02004746 /* Called when a downloaded package installation has been confirmed by the user */
4747 public void installPackage(
4748 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4749 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004750 mContext.enforceCallingOrSelfPermission(
4751 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004752
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004753 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004754 msg.obj = new InstallParams(packageURI, observer, flags,
4755 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004756 mHandler.sendMessage(msg);
4757 }
4758
Christopher Tate1bb69062010-02-19 17:02:12 -08004759 public void finishPackageInstall(int token) {
4760 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4761 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4762 mHandler.sendMessage(msg);
4763 }
4764
Kenny Root93565c4b2010-06-18 15:46:06 -07004765 public void setPackageObbPath(String packageName, String path) {
4766 if (DEBUG_OBB)
4767 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4768 PackageSetting pkgSetting;
4769 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004770 final int permission = mContext.checkCallingPermission(
4771 android.Manifest.permission.INSTALL_PACKAGES);
4772 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004773 synchronized (mPackages) {
4774 pkgSetting = mSettings.mPackages.get(packageName);
4775 if (pkgSetting == null) {
4776 throw new IllegalArgumentException("Unknown package: " + packageName);
4777 }
4778 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4779 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4780 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4781 + pkgSetting.userId);
4782 }
4783 pkgSetting.obbPathString = path;
4784 mSettings.writeLP();
4785 }
4786 }
4787
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004788 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004789 // Queue up an async operation since the package installation may take a little while.
4790 mHandler.post(new Runnable() {
4791 public void run() {
4792 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004793 // Result object to be returned
4794 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004795 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004796 res.uid = -1;
4797 res.pkg = null;
4798 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004799 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004800 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004801 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004802 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004803 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004804 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004805 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004806
4807 // A restore should be performed at this point if (a) the install
4808 // succeeded, (b) the operation is not an update, and (c) the new
4809 // package has a backupAgent defined.
4810 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004811 boolean doRestore = (!update
4812 && res.pkg != null
4813 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004814
4815 // Set up the post-install work request bookkeeping. This will be used
4816 // and cleaned up by the post-install event handling regardless of whether
4817 // there's a restore pass performed. Token values are >= 1.
4818 int token;
4819 if (mNextInstallToken < 0) mNextInstallToken = 1;
4820 token = mNextInstallToken++;
4821
4822 PostInstallData data = new PostInstallData(args, res);
4823 mRunningInstalls.put(token, data);
4824 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4825
4826 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4827 // Pass responsibility to the Backup Manager. It will perform a
4828 // restore if appropriate, then pass responsibility back to the
4829 // Package Manager to run the post-install observer callbacks
4830 // and broadcasts.
4831 IBackupManager bm = IBackupManager.Stub.asInterface(
4832 ServiceManager.getService(Context.BACKUP_SERVICE));
4833 if (bm != null) {
4834 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4835 + " to BM for possible restore");
4836 try {
4837 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4838 } catch (RemoteException e) {
4839 // can't happen; the backup manager is local
4840 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004841 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004842 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004843 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004844 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004845 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004846 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004848 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004849
4850 if (!doRestore) {
4851 // No restore possible, or the Backup Manager was mysteriously not
4852 // available -- just fire the post-install work request directly.
4853 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4854 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4855 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004857 }
4858 });
4859 }
4860
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004861 abstract class HandlerParams {
4862 final static int MAX_RETRIES = 4;
4863 int retry = 0;
4864 final void startCopy() {
4865 try {
4866 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4867 retry++;
4868 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004869 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004870 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4871 handleServiceError();
4872 return;
4873 } else {
4874 handleStartCopy();
4875 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4876 mHandler.sendEmptyMessage(MCS_UNBIND);
4877 }
4878 } catch (RemoteException e) {
4879 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4880 mHandler.sendEmptyMessage(MCS_RECONNECT);
4881 }
4882 handleReturnCode();
4883 }
4884
4885 final void serviceError() {
4886 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4887 handleServiceError();
4888 handleReturnCode();
4889 }
4890 abstract void handleStartCopy() throws RemoteException;
4891 abstract void handleServiceError();
4892 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004893 }
4894
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004895 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004896 final IPackageInstallObserver observer;
4897 int flags;
4898 final Uri packageURI;
4899 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004900 private InstallArgs mArgs;
4901 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004902 InstallParams(Uri packageURI,
4903 IPackageInstallObserver observer, int flags,
4904 String installerPackageName) {
4905 this.packageURI = packageURI;
4906 this.flags = flags;
4907 this.observer = observer;
4908 this.installerPackageName = installerPackageName;
4909 }
4910
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004911 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4912 String packageName = pkgLite.packageName;
4913 int installLocation = pkgLite.installLocation;
4914 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4915 synchronized (mPackages) {
4916 PackageParser.Package pkg = mPackages.get(packageName);
4917 if (pkg != null) {
4918 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4919 // Check for updated system application.
4920 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4921 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004922 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004923 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4924 }
4925 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4926 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004927 if (onSd) {
4928 // Install flag overrides everything.
4929 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4930 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004931 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004932 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4933 // Application explicitly specified internal.
4934 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4935 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4936 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004937 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004938 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004939 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4940 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4941 }
4942 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004943 }
4944 }
4945 } else {
4946 // Invalid install. Return error code
4947 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4948 }
4949 }
4950 }
4951 // All the special cases have been taken care of.
4952 // Return result based on recommended install location.
4953 if (onSd) {
4954 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4955 }
4956 return pkgLite.recommendedInstallLocation;
4957 }
4958
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004959 /*
4960 * Invoke remote method to get package information and install
4961 * location values. Override install location based on default
4962 * policy if needed and then create install arguments based
4963 * on the install location.
4964 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004965 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004966 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004967 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4968 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004969 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4970 if (onInt && onSd) {
4971 // Check if both bits are set.
4972 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4973 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4974 } else if (fwdLocked && onSd) {
4975 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004976 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004977 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004978 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004979 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004980 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004981 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004982 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4983 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4984 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4985 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4986 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004987 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4988 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4989 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004990 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4991 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004992 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004993 // Override with defaults if needed.
4994 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004995 if (!onSd && !onInt) {
4996 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004997 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4998 // Set the flag to install on external media.
4999 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07005000 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005001 } else {
5002 // Make sure the flag for installing on external
5003 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07005004 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005005 flags &= ~PackageManager.INSTALL_EXTERNAL;
5006 }
5007 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005008 }
5009 }
5010 // Create the file args now.
5011 mArgs = createInstallArgs(this);
5012 if (ret == PackageManager.INSTALL_SUCCEEDED) {
5013 // Create copy only if we are not in an erroneous state.
5014 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005015 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005016 }
5017 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005018 }
5019
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005020 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005021 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07005022 // If mArgs is null, then MCS couldn't be reached. When it
5023 // reconnects, it will try again to install. At that point, this
5024 // will succeed.
5025 if (mArgs != null) {
5026 processPendingInstall(mArgs, mRet);
5027 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005028 }
5029
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005030 @Override
5031 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005032 mArgs = createInstallArgs(this);
5033 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005034 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005035 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005036
5037 /*
5038 * Utility class used in movePackage api.
5039 * srcArgs and targetArgs are not set for invalid flags and make
5040 * sure to do null checks when invoking methods on them.
5041 * We probably want to return ErrorPrams for both failed installs
5042 * and moves.
5043 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005044 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005045 final IPackageMoveObserver observer;
5046 final int flags;
5047 final String packageName;
5048 final InstallArgs srcArgs;
5049 final InstallArgs targetArgs;
5050 int mRet;
5051 MoveParams(InstallArgs srcArgs,
5052 IPackageMoveObserver observer,
5053 int flags, String packageName) {
5054 this.srcArgs = srcArgs;
5055 this.observer = observer;
5056 this.flags = flags;
5057 this.packageName = packageName;
5058 if (srcArgs != null) {
5059 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
5060 targetArgs = createInstallArgs(packageUri, flags, packageName);
5061 } else {
5062 targetArgs = null;
5063 }
5064 }
5065
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005066 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005067 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5068 // Check for storage space on target medium
5069 if (!targetArgs.checkFreeStorage(mContainerService)) {
5070 Log.w(TAG, "Insufficient storage to install");
5071 return;
5072 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005073 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005074 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005075 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005076 if (DEBUG_SD_INSTALL) {
5077 StringBuilder builder = new StringBuilder();
5078 if (srcArgs != null) {
5079 builder.append("src: ");
5080 builder.append(srcArgs.getCodePath());
5081 }
5082 if (targetArgs != null) {
5083 builder.append(" target : ");
5084 builder.append(targetArgs.getCodePath());
5085 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005086 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005087 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005088 }
5089
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005090 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005091 void handleReturnCode() {
5092 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005093 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
5094 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
5095 currentStatus = PackageManager.MOVE_SUCCEEDED;
5096 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
5097 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
5098 }
5099 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005100 }
5101
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005102 @Override
5103 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005104 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005105 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005106 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005107
5108 private InstallArgs createInstallArgs(InstallParams params) {
5109 if (installOnSd(params.flags)) {
5110 return new SdInstallArgs(params);
5111 } else {
5112 return new FileInstallArgs(params);
5113 }
5114 }
5115
5116 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
5117 if (installOnSd(flags)) {
5118 return new SdInstallArgs(fullCodePath, fullResourcePath);
5119 } else {
5120 return new FileInstallArgs(fullCodePath, fullResourcePath);
5121 }
5122 }
5123
Suchi Amalapurapu9a212ad2010-05-18 11:06:53 -07005124 private InstallArgs createInstallArgs(Uri packageURI, int flags,
5125 String pkgName) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005126 if (installOnSd(flags)) {
5127 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
5128 return new SdInstallArgs(packageURI, cid);
5129 } else {
5130 return new FileInstallArgs(packageURI, pkgName);
5131 }
5132 }
5133
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005134 static abstract class InstallArgs {
5135 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005136 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005137 final int flags;
5138 final Uri packageURI;
5139 final String installerPackageName;
5140
5141 InstallArgs(Uri packageURI,
5142 IPackageInstallObserver observer, int flags,
5143 String installerPackageName) {
5144 this.packageURI = packageURI;
5145 this.flags = flags;
5146 this.observer = observer;
5147 this.installerPackageName = installerPackageName;
5148 }
5149
5150 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005151 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005152 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005153 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005154 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005155 abstract String getCodePath();
5156 abstract String getResourcePath();
5157 // Need installer lock especially for dex file removal.
5158 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005159 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005160 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005161 }
5162
5163 class FileInstallArgs extends InstallArgs {
5164 File installDir;
5165 String codeFileName;
5166 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005167 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005168
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005169 FileInstallArgs(InstallParams params) {
5170 super(params.packageURI, params.observer,
5171 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005172 }
5173
5174 FileInstallArgs(String fullCodePath, String fullResourcePath) {
5175 super(null, null, 0, null);
5176 File codeFile = new File(fullCodePath);
5177 installDir = codeFile.getParentFile();
5178 codeFileName = fullCodePath;
5179 resourceFileName = fullResourcePath;
5180 }
5181
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005182 FileInstallArgs(Uri packageURI, String pkgName) {
5183 super(packageURI, null, 0, null);
5184 boolean fwdLocked = isFwdLocked(flags);
5185 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5186 String apkName = getNextCodePath(null, pkgName, ".apk");
5187 codeFileName = new File(installDir, apkName + ".apk").getPath();
5188 resourceFileName = getResourcePathFromCodePath();
5189 }
5190
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005191 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5192 return imcs.checkFreeStorage(false, packageURI);
5193 }
5194
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005195 String getCodePath() {
5196 return codeFileName;
5197 }
5198
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005199 void createCopyFile() {
5200 boolean fwdLocked = isFwdLocked(flags);
5201 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5202 codeFileName = createTempPackageFile(installDir).getPath();
5203 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005204 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005205 }
5206
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005207 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005208 if (temp) {
5209 // Generate temp file name
5210 createCopyFile();
5211 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005212 // Get a ParcelFileDescriptor to write to the output file
5213 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005214 if (!created) {
5215 try {
5216 codeFile.createNewFile();
5217 // Set permissions
5218 if (!setPermissions()) {
5219 // Failed setting permissions.
5220 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5221 }
5222 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005223 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005224 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5225 }
5226 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005227 ParcelFileDescriptor out = null;
5228 try {
5229 out = ParcelFileDescriptor.open(codeFile,
5230 ParcelFileDescriptor.MODE_READ_WRITE);
5231 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005232 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005233 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5234 }
5235 // Copy the resource now
5236 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5237 try {
5238 if (imcs.copyResource(packageURI, out)) {
5239 ret = PackageManager.INSTALL_SUCCEEDED;
5240 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005241 } finally {
5242 try { if (out != null) out.close(); } catch (IOException e) {}
5243 }
5244 return ret;
5245 }
5246
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005247 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005248 if (status != PackageManager.INSTALL_SUCCEEDED) {
5249 cleanUp();
5250 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005251 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005252 }
5253
5254 boolean doRename(int status, final String pkgName, String oldCodePath) {
5255 if (status != PackageManager.INSTALL_SUCCEEDED) {
5256 cleanUp();
5257 return false;
5258 } else {
5259 // Rename based on packageName
5260 File codeFile = new File(getCodePath());
5261 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5262 File desFile = new File(installDir, apkName + ".apk");
5263 if (!codeFile.renameTo(desFile)) {
5264 return false;
5265 }
5266 // Reset paths since the file has been renamed.
5267 codeFileName = desFile.getPath();
5268 resourceFileName = getResourcePathFromCodePath();
5269 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005270 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005271 // Failed setting permissions.
5272 return false;
5273 }
5274 return true;
5275 }
5276 }
5277
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005278 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005279 if (status != PackageManager.INSTALL_SUCCEEDED) {
5280 cleanUp();
5281 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005282 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005283 }
5284
5285 String getResourcePath() {
5286 return resourceFileName;
5287 }
5288
5289 String getResourcePathFromCodePath() {
5290 String codePath = getCodePath();
5291 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5292 String apkNameOnly = getApkName(codePath);
5293 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5294 } else {
5295 return codePath;
5296 }
5297 }
5298
5299 private boolean cleanUp() {
5300 boolean ret = true;
5301 String sourceDir = getCodePath();
5302 String publicSourceDir = getResourcePath();
5303 if (sourceDir != null) {
5304 File sourceFile = new File(sourceDir);
5305 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005306 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005307 ret = false;
5308 }
5309 // Delete application's code and resources
5310 sourceFile.delete();
5311 }
5312 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5313 final File publicSourceFile = new File(publicSourceDir);
5314 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005315 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005316 }
5317 if (publicSourceFile.exists()) {
5318 publicSourceFile.delete();
5319 }
5320 }
5321 return ret;
5322 }
5323
5324 void cleanUpResourcesLI() {
5325 String sourceDir = getCodePath();
5326 if (cleanUp() && mInstaller != null) {
5327 int retCode = mInstaller.rmdex(sourceDir);
5328 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005329 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005330 + " at location "
5331 + sourceDir + ", retcode=" + retCode);
5332 // we don't consider this to be a failure of the core package deletion
5333 }
5334 }
5335 }
5336
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005337 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005338 // TODO Do this in a more elegant way later on. for now just a hack
5339 if (!isFwdLocked(flags)) {
5340 final int filePermissions =
5341 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5342 |FileUtils.S_IROTH;
5343 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5344 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005345 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005346 getCodePath()
5347 + ". The return code was: " + retCode);
5348 // TODO Define new internal error
5349 return false;
5350 }
5351 return true;
5352 }
5353 return true;
5354 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005355
5356 boolean doPostDeleteLI(boolean delete) {
5357 cleanUpResourcesLI();
5358 return true;
5359 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005360 }
5361
5362 class SdInstallArgs extends InstallArgs {
5363 String cid;
5364 String cachePath;
5365 static final String RES_FILE_NAME = "pkg.apk";
5366
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005367 SdInstallArgs(InstallParams params) {
5368 super(params.packageURI, params.observer,
5369 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005370 }
5371
5372 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005373 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005374 // Extract cid from fullCodePath
5375 int eidx = fullCodePath.lastIndexOf("/");
5376 String subStr1 = fullCodePath.substring(0, eidx);
5377 int sidx = subStr1.lastIndexOf("/");
5378 cid = subStr1.substring(sidx+1, eidx);
5379 cachePath = subStr1;
5380 }
5381
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005382 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005383 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5384 this.cid = cid;
Suchi Amalapurapu9a212ad2010-05-18 11:06:53 -07005385 cachePath = PackageHelper.getSdDir(cid);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005386 }
5387
5388 SdInstallArgs(Uri packageURI, String cid) {
5389 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005390 this.cid = cid;
5391 }
5392
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005393 void createCopyFile() {
5394 cid = getTempContainerId();
5395 }
5396
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005397 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5398 return imcs.checkFreeStorage(true, packageURI);
5399 }
5400
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005401 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005402 if (temp) {
5403 createCopyFile();
5404 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005405 cachePath = imcs.copyResourceToContainer(
5406 packageURI, cid,
5407 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005408 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5409 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005410 }
5411
5412 @Override
5413 String getCodePath() {
5414 return cachePath + "/" + RES_FILE_NAME;
5415 }
5416
5417 @Override
5418 String getResourcePath() {
5419 return cachePath + "/" + RES_FILE_NAME;
5420 }
5421
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005422 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005423 if (status != PackageManager.INSTALL_SUCCEEDED) {
5424 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005425 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005426 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005427 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005428 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005429 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005430 if (cachePath == null) {
5431 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5432 }
5433 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005434 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005435 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005436 }
5437
5438 boolean doRename(int status, final String pkgName,
5439 String oldCodePath) {
5440 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005441 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005442 if (PackageHelper.isContainerMounted(cid)) {
5443 // Unmount the container
5444 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005445 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005446 return false;
5447 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005448 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005449 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005450 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5451 " which might be stale. Will try to clean up.");
5452 // Clean up the stale container and proceed to recreate.
5453 if (!PackageHelper.destroySdDir(newCacheId)) {
5454 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5455 return false;
5456 }
5457 // Successfully cleaned up stale container. Try to rename again.
5458 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5459 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5460 + " inspite of cleaning it up.");
5461 return false;
5462 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005463 }
5464 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005465 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005466 newCachePath = PackageHelper.mountSdDir(newCacheId,
5467 getEncryptKey(), Process.SYSTEM_UID);
5468 } else {
5469 newCachePath = PackageHelper.getSdDir(newCacheId);
5470 }
5471 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005472 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005473 return false;
5474 }
5475 Log.i(TAG, "Succesfully renamed " + cid +
5476 " at path: " + cachePath + " to " + newCacheId +
5477 " at new path: " + newCachePath);
5478 cid = newCacheId;
5479 cachePath = newCachePath;
5480 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005481 }
5482
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005483 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005484 if (status != PackageManager.INSTALL_SUCCEEDED) {
5485 cleanUp();
5486 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005487 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005488 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005489 PackageHelper.mountSdDir(cid,
5490 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005491 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005492 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005493 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005494 }
5495
5496 private void cleanUp() {
5497 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005498 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005499 }
5500
5501 void cleanUpResourcesLI() {
5502 String sourceFile = getCodePath();
5503 // Remove dex file
5504 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005505 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005506 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005507 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005508 + " at location "
5509 + sourceFile.toString() + ", retcode=" + retCode);
5510 // we don't consider this to be a failure of the core package deletion
5511 }
5512 }
5513 cleanUp();
5514 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005515
5516 boolean matchContainer(String app) {
5517 if (cid.startsWith(app)) {
5518 return true;
5519 }
5520 return false;
5521 }
5522
5523 String getPackageName() {
5524 int idx = cid.lastIndexOf("-");
5525 if (idx == -1) {
5526 return cid;
5527 }
5528 return cid.substring(0, idx);
5529 }
5530
5531 boolean doPostDeleteLI(boolean delete) {
5532 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005533 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005534 if (mounted) {
5535 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005536 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005537 }
5538 if (ret && delete) {
5539 cleanUpResourcesLI();
5540 }
5541 return ret;
5542 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005543 };
5544
5545 // Utility method used to create code paths based on package name and available index.
5546 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5547 String idxStr = "";
5548 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005549 // Fall back to default value of idx=1 if prefix is not
5550 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005551 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005552 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005553 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005554 if (subStr.endsWith(suffix)) {
5555 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005556 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005557 // If oldCodePath already contains prefix find out the
5558 // ending index to either increment or decrement.
5559 int sidx = subStr.lastIndexOf(prefix);
5560 if (sidx != -1) {
5561 subStr = subStr.substring(sidx + prefix.length());
5562 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005563 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5564 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005565 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005566 try {
5567 idx = Integer.parseInt(subStr);
5568 if (idx <= 1) {
5569 idx++;
5570 } else {
5571 idx--;
5572 }
5573 } catch(NumberFormatException e) {
5574 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005575 }
5576 }
5577 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005578 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005579 return prefix + idxStr;
5580 }
5581
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005582 // Utility method used to ignore ADD/REMOVE events
5583 // by directory observer.
5584 private static boolean ignoreCodePath(String fullPathStr) {
5585 String apkName = getApkName(fullPathStr);
5586 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5587 if (idx != -1 && ((idx+1) < apkName.length())) {
5588 // Make sure the package ends with a numeral
5589 String version = apkName.substring(idx+1);
5590 try {
5591 Integer.parseInt(version);
5592 return true;
5593 } catch (NumberFormatException e) {}
5594 }
5595 return false;
5596 }
5597
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005598 // Utility method that returns the relative package path with respect
5599 // to the installation directory. Like say for /data/data/com.test-1.apk
5600 // string com.test-1 is returned.
5601 static String getApkName(String codePath) {
5602 if (codePath == null) {
5603 return null;
5604 }
5605 int sidx = codePath.lastIndexOf("/");
5606 int eidx = codePath.lastIndexOf(".");
5607 if (eidx == -1) {
5608 eidx = codePath.length();
5609 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005610 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005611 return null;
5612 }
5613 return codePath.substring(sidx+1, eidx);
5614 }
5615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005616 class PackageInstalledInfo {
5617 String name;
5618 int uid;
5619 PackageParser.Package pkg;
5620 int returnCode;
5621 PackageRemovedInfo removedInfo;
5622 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005624 /*
5625 * Install a non-existing package.
5626 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005627 private void installNewPackageLI(PackageParser.Package pkg,
5628 int parseFlags,
5629 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005630 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005631 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005632 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005633
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005634 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005635 res.name = pkgName;
5636 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005637 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5638 // A package with the same name is already installed, though
5639 // it has been renamed to an older name. The package we
5640 // are trying to install should be installed as an update to
5641 // the existing one, but that has not been requested, so bail.
5642 Slog.w(TAG, "Attempt to re-install " + pkgName
5643 + " without first uninstalling package running as "
5644 + mSettings.mRenamedPackages.get(pkgName));
5645 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5646 return;
5647 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005648 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005650 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 + " without first uninstalling.");
5652 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5653 return;
5654 }
5655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005656 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005657 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005658 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005659 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005660 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5661 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5662 }
5663 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005664 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005665 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005666 res);
5667 // delete the partially installed application. the data directory will have to be
5668 // restored if it was already existing
5669 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5670 // remove package from internal structures. Note that we want deletePackageX to
5671 // delete the package data and cache directories that it created in
5672 // scanPackageLocked, unless those directories existed before we even tried to
5673 // install.
5674 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005675 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005676 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5677 res.removedInfo);
5678 }
5679 }
5680 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005681
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005682 private void replacePackageLI(PackageParser.Package pkg,
5683 int parseFlags,
5684 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005685 String installerPackageName, PackageInstalledInfo res) {
5686
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005687 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005688 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005689 // First find the old package info and check signatures
5690 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005691 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005692 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005693 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005694 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5695 return;
5696 }
5697 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005698 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005699 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005700 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005702 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005703 }
5704 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005706 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005707 PackageParser.Package pkg,
5708 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005709 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005710 PackageParser.Package newPackage = null;
5711 String pkgName = deletedPackage.packageName;
5712 boolean deletedPkg = true;
5713 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005714
Jacek Surazski65e13172009-04-28 15:26:38 +02005715 String oldInstallerPackageName = null;
5716 synchronized (mPackages) {
5717 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5718 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005721 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005722 res.removedInfo)) {
5723 // If the existing package was'nt successfully deleted
5724 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5725 deletedPkg = false;
5726 } else {
5727 // Successfully deleted the old package. Now proceed with re-installation
5728 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005729 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005730 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005731 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005732 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5733 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005734 }
5735 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005736 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005737 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005738 res);
5739 updatedSettings = true;
5740 }
5741 }
5742
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005743 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 // remove package from internal structures. Note that we want deletePackageX to
5745 // delete the package data and cache directories that it created in
5746 // scanPackageLocked, unless those directories existed before we even tried to
5747 // install.
5748 if(updatedSettings) {
5749 deletePackageLI(
5750 pkgName, true,
5751 PackageManager.DONT_DELETE_DATA,
5752 res.removedInfo);
5753 }
5754 // Since we failed to install the new package we need to restore the old
5755 // package that we deleted.
5756 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005757 File restoreFile = new File(deletedPackage.mPath);
5758 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005759 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005760 return;
5761 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005762 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005763 boolean oldOnSd = isExternal(deletedPackage);
5764 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5765 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5766 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5767 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5768 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5769 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5770 return;
5771 }
5772 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005773 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005774 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005775 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005776 mSettings.writeLP();
5777 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005778 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005779 }
5780 }
5781 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005783 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005784 PackageParser.Package pkg,
5785 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005786 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005787 PackageParser.Package newPackage = null;
5788 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005789 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 PackageParser.PARSE_IS_SYSTEM;
5791 String packageName = deletedPackage.packageName;
5792 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5793 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005794 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005795 return;
5796 }
5797 PackageParser.Package oldPkg;
5798 PackageSetting oldPkgSetting;
5799 synchronized (mPackages) {
5800 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005801 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005802 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5803 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005804 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005805 return;
5806 }
5807 }
5808 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5809 res.removedInfo.removedPackage = packageName;
5810 // Remove existing system package
5811 removePackageLI(oldPkg, true);
5812 synchronized (mPackages) {
5813 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5814 }
5815
5816 // Successfully disabled the old package. Now proceed with re-installation
5817 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5818 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005819 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005820 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005821 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005822 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5823 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5824 }
5825 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005826 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005827 updatedSettings = true;
5828 }
5829
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005830 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005831 // Re installation failed. Restore old information
5832 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005833 if (newPackage != null) {
5834 removePackageLI(newPackage, true);
5835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005836 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005837 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005838 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005839 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005840 // Restore the old system information in Settings
5841 synchronized(mPackages) {
5842 if(updatedSettings) {
5843 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005844 mSettings.setInstallerPackageName(packageName,
5845 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005846 }
5847 mSettings.writeLP();
5848 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005849 } else {
5850 // If this is an update to an existing update, setup
5851 // to remove the existing update.
5852 synchronized (mPackages) {
5853 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5854 if (ps != null && ps.codePathString != null &&
5855 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
5856 int installFlags = 0;
5857 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
5858 oldPkgSetting.resourcePathString);
5859 }
5860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005861 }
5862 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005863
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005864 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005865 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005866 int retCode;
5867 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5868 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5869 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005870 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005871 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5872 }
5873 }
5874 return PackageManager.INSTALL_SUCCEEDED;
5875 }
5876
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005877 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005878 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005879 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005880 synchronized (mPackages) {
5881 //write settings. the installStatus will be incomplete at this stage.
5882 //note that the new package setting would have already been
5883 //added to mPackages. It hasn't been persisted yet.
5884 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5885 mSettings.writeLP();
5886 }
5887
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005888 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005889 != PackageManager.INSTALL_SUCCEEDED) {
5890 // Discontinue if moving dex files failed.
5891 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005892 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005893 if((res.returnCode = setPermissionsLI(newPackage))
5894 != PackageManager.INSTALL_SUCCEEDED) {
5895 if (mInstaller != null) {
5896 mInstaller.rmdex(newPackage.mScanPath);
5897 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005898 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005899 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005900 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005902 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005903 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005904 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005905 res.name = pkgName;
5906 res.uid = newPackage.applicationInfo.uid;
5907 res.pkg = newPackage;
5908 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005909 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005910 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5911 //to update install status
5912 mSettings.writeLP();
5913 }
5914 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005915
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005916 private void installPackageLI(InstallArgs args,
5917 boolean newInstall, PackageInstalledInfo res) {
5918 int pFlags = args.flags;
5919 String installerPackageName = args.installerPackageName;
5920 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005921 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005922 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005923 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005924 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005925 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005926 // Result object to be returned
5927 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5928
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005929 // Retrieve PackageSettings and parse package
5930 int parseFlags = PackageParser.PARSE_CHATTY |
5931 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5932 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5933 parseFlags |= mDefParseFlags;
5934 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5935 pp.setSeparateProcesses(mSeparateProcesses);
5936 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5937 null, mMetrics, parseFlags);
5938 if (pkg == null) {
5939 res.returnCode = pp.getParseError();
5940 return;
5941 }
5942 String pkgName = res.name = pkg.packageName;
5943 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5944 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5945 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5946 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005947 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005948 }
5949 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5950 res.returnCode = pp.getParseError();
5951 return;
5952 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005953 // Get rid of all references to package scan path via parser.
5954 pp = null;
5955 String oldCodePath = null;
5956 boolean systemApp = false;
5957 synchronized (mPackages) {
5958 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005959 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5960 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005961 if (pkg.mOriginalPackages != null
5962 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005963 && mPackages.containsKey(oldName)) {
5964 // This package is derived from an original package,
5965 // and this device has been updating from that original
5966 // name. We must continue using the original name, so
5967 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005968 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005969 pkgName = pkg.packageName;
5970 replace = true;
5971 } else if (mPackages.containsKey(pkgName)) {
5972 // This package, under its official name, already exists
5973 // on the device; we should replace it.
5974 replace = true;
5975 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005976 }
5977 PackageSetting ps = mSettings.mPackages.get(pkgName);
5978 if (ps != null) {
5979 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5980 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5981 systemApp = (ps.pkg.applicationInfo.flags &
5982 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005983 }
5984 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005985 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005986
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005987 if (systemApp && onSd) {
5988 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005989 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005990 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5991 return;
5992 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005993
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005994 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5995 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5996 return;
5997 }
5998 // Set application objects path explicitly after the rename
5999 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006000 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006001 replacePackageLI(pkg, parseFlags, scanMode,
6002 installerPackageName, res);
6003 } else {
6004 installNewPackageLI(pkg, parseFlags, scanMode,
6005 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006006 }
6007 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006008
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006009 private int setPermissionsLI(PackageParser.Package newPackage) {
6010 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006011 int retCode = 0;
6012 // TODO Gross hack but fix later. Ideally move this to be a post installation
6013 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006014 if ((newPackage.applicationInfo.flags
6015 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
6016 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006017 try {
6018 extractPublicFiles(newPackage, destResourceFile);
6019 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006020 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 -08006021 " forward-locked app.");
6022 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6023 } finally {
6024 //TODO clean up the extracted public files
6025 }
6026 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006027 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006028 newPackage.applicationInfo.uid);
6029 } else {
6030 final int filePermissions =
6031 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006032 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006033 newPackage.applicationInfo.uid);
6034 }
6035 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006036 // The permissions on the resource file was set when it was copied for
6037 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006038 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006040 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006041 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006042 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006043 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006044 // TODO Define new internal error
6045 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006046 }
6047 return PackageManager.INSTALL_SUCCEEDED;
6048 }
6049
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006050 private boolean isForwardLocked(PackageParser.Package pkg) {
6051 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006052 }
6053
Suchi Amalapurapuae181712010-03-30 14:01:02 -07006054 private boolean isExternal(PackageParser.Package pkg) {
6055 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
6056 }
6057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006058 private void extractPublicFiles(PackageParser.Package newPackage,
6059 File publicZipFile) throws IOException {
6060 final ZipOutputStream publicZipOutStream =
6061 new ZipOutputStream(new FileOutputStream(publicZipFile));
6062 final ZipFile privateZip = new ZipFile(newPackage.mPath);
6063
6064 // Copy manifest, resources.arsc and res directory to public zip
6065
6066 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
6067 while (privateZipEntries.hasMoreElements()) {
6068 final ZipEntry zipEntry = privateZipEntries.nextElement();
6069 final String zipEntryName = zipEntry.getName();
6070 if ("AndroidManifest.xml".equals(zipEntryName)
6071 || "resources.arsc".equals(zipEntryName)
6072 || zipEntryName.startsWith("res/")) {
6073 try {
6074 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
6075 } catch (IOException e) {
6076 try {
6077 publicZipOutStream.close();
6078 throw e;
6079 } finally {
6080 publicZipFile.delete();
6081 }
6082 }
6083 }
6084 }
6085
6086 publicZipOutStream.close();
6087 FileUtils.setPermissions(
6088 publicZipFile.getAbsolutePath(),
6089 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
6090 -1, -1);
6091 }
6092
6093 private static void copyZipEntry(ZipEntry zipEntry,
6094 ZipFile inZipFile,
6095 ZipOutputStream outZipStream) throws IOException {
6096 byte[] buffer = new byte[4096];
6097 int num;
6098
6099 ZipEntry newEntry;
6100 if (zipEntry.getMethod() == ZipEntry.STORED) {
6101 // Preserve the STORED method of the input entry.
6102 newEntry = new ZipEntry(zipEntry);
6103 } else {
6104 // Create a new entry so that the compressed len is recomputed.
6105 newEntry = new ZipEntry(zipEntry.getName());
6106 }
6107 outZipStream.putNextEntry(newEntry);
6108
6109 InputStream data = inZipFile.getInputStream(zipEntry);
6110 while ((num = data.read(buffer)) > 0) {
6111 outZipStream.write(buffer, 0, num);
6112 }
6113 outZipStream.flush();
6114 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006116 private void deleteTempPackageFiles() {
6117 FilenameFilter filter = new FilenameFilter() {
6118 public boolean accept(File dir, String name) {
6119 return name.startsWith("vmdl") && name.endsWith(".tmp");
6120 }
6121 };
6122 String tmpFilesList[] = mAppInstallDir.list(filter);
6123 if(tmpFilesList == null) {
6124 return;
6125 }
6126 for(int i = 0; i < tmpFilesList.length; i++) {
6127 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
6128 tmpFile.delete();
6129 }
6130 }
6131
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006132 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006133 File tmpPackageFile;
6134 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006135 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006136 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006137 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006138 return null;
6139 }
6140 try {
6141 FileUtils.setPermissions(
6142 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6143 -1, -1);
6144 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006145 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006146 return null;
6147 }
6148 return tmpPackageFile;
6149 }
6150
6151 public void deletePackage(final String packageName,
6152 final IPackageDeleteObserver observer,
6153 final int flags) {
6154 mContext.enforceCallingOrSelfPermission(
6155 android.Manifest.permission.DELETE_PACKAGES, null);
6156 // Queue up an async operation since the package deletion may take a little while.
6157 mHandler.post(new Runnable() {
6158 public void run() {
6159 mHandler.removeCallbacks(this);
6160 final boolean succeded = deletePackageX(packageName, true, true, flags);
6161 if (observer != null) {
6162 try {
6163 observer.packageDeleted(succeded);
6164 } catch (RemoteException e) {
6165 Log.i(TAG, "Observer no longer exists.");
6166 } //end catch
6167 } //end if
6168 } //end run
6169 });
6170 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006171
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006172 /**
6173 * This method is an internal method that could be get invoked either
6174 * to delete an installed package or to clean up a failed installation.
6175 * After deleting an installed package, a broadcast is sent to notify any
6176 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006177 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006178 * installation wouldn't have sent the initial broadcast either
6179 * The key steps in deleting a package are
6180 * deleting the package information in internal structures like mPackages,
6181 * deleting the packages base directories through installd
6182 * updating mSettings to reflect current status
6183 * persisting settings for later use
6184 * sending a broadcast if necessary
6185 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006186 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6187 boolean deleteCodeAndResources, int flags) {
6188 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006189 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006190
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006191 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6192 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6193 try {
6194 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006195 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006196 return false;
6197 }
6198 } catch (RemoteException e) {
6199 }
6200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006201 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006202 res = deletePackageLI(packageName, deleteCodeAndResources,
6203 flags | REMOVE_CHATTY, info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006204 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006207 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006208 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006209
6210 // If the removed package was a system update, the old system packaged
6211 // was re-enabled; we need to broadcast this information
6212 if (systemUpdate) {
6213 Bundle extras = new Bundle(1);
6214 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6215 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6216
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006217 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6218 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006220 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006221 // Force a gc here.
6222 Runtime.getRuntime().gc();
6223 // Delete the resources here after sending the broadcast to let
6224 // other processes clean up before deleting resources.
6225 if (info.args != null) {
6226 synchronized (mInstallLock) {
6227 info.args.doPostDeleteLI(deleteCodeAndResources);
6228 }
6229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006230 return res;
6231 }
6232
6233 static class PackageRemovedInfo {
6234 String removedPackage;
6235 int uid = -1;
6236 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006237 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006238 // Clean up resources deleted packages.
6239 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006240
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006241 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006242 Bundle extras = new Bundle(1);
6243 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6244 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6245 if (replacing) {
6246 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6247 }
6248 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006249 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250 }
6251 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006252 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006253 }
6254 }
6255 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 /*
6258 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6259 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006260 * 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 -08006261 * delete a partially installed application.
6262 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006263 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 int flags) {
6265 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006266 if (outInfo != null) {
6267 outInfo.removedPackage = packageName;
6268 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006269 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006270 // Retrieve object to delete permissions for shared user later on
6271 PackageSetting deletedPs;
6272 synchronized (mPackages) {
6273 deletedPs = mSettings.mPackages.get(packageName);
6274 }
6275 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006276 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006277 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006278 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006280 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006281 + packageName + ", retcode=" + retCode);
6282 // we don't consider this to be a failure of the core package deletion
6283 }
6284 } else {
6285 //for emulator
6286 PackageParser.Package pkg = mPackages.get(packageName);
6287 File dataDir = new File(pkg.applicationInfo.dataDir);
6288 dataDir.delete();
6289 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006290 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006291 }
6292 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006293 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006294 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6295 if (outInfo != null) {
6296 outInfo.removedUid = mSettings.removePackageLP(packageName);
6297 }
6298 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006299 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006300 if (deletedPs.sharedUser != null) {
6301 // remove permissions associated with package
6302 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6303 }
6304 }
6305 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006306 // remove from preferred activities.
6307 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6308 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6309 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6310 removed.add(pa);
6311 }
6312 }
6313 for (PreferredActivity pa : removed) {
6314 mSettings.mPreferredActivities.removeFilter(pa);
6315 }
6316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006317 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006318 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006319 }
6320 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006322 /*
6323 * Tries to delete system package.
6324 */
6325 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006326 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006327 ApplicationInfo applicationInfo = p.applicationInfo;
6328 //applicable for non-partially installed applications only
6329 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006330 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006331 return false;
6332 }
6333 PackageSetting ps = null;
6334 // Confirm if the system package has been updated
6335 // An updated system app can be deleted. This will also have to restore
6336 // the system pkg from system partition
6337 synchronized (mPackages) {
6338 ps = mSettings.getDisabledSystemPkg(p.packageName);
6339 }
6340 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006341 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006342 return false;
6343 } else {
6344 Log.i(TAG, "Deleting system pkg from data partition");
6345 }
6346 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006347 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006348 boolean deleteCodeAndResources = false;
6349 if (ps.versionCode < p.mVersionCode) {
6350 // Delete code and resources for downgrades
6351 deleteCodeAndResources = true;
6352 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6353 flags &= ~PackageManager.DONT_DELETE_DATA;
6354 }
6355 } else {
6356 // Preserve data by setting flag
6357 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6358 flags |= PackageManager.DONT_DELETE_DATA;
6359 }
6360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006361 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6362 if (!ret) {
6363 return false;
6364 }
6365 synchronized (mPackages) {
6366 // Reinstate the old system package
6367 mSettings.enableSystemPackageLP(p.packageName);
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07006368 // Remove any native libraries.
6369 removeNativeBinariesLI(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 }
6371 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006372 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006374 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006376 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006377 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006378 return false;
6379 }
6380 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006381 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006382 mSettings.writeLP();
6383 }
6384 return true;
6385 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006387 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6388 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6389 ApplicationInfo applicationInfo = p.applicationInfo;
6390 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006391 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006392 return false;
6393 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006394 if (outInfo != null) {
6395 outInfo.uid = applicationInfo.uid;
6396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006397
6398 // Delete package data from internal structures and also remove data if flag is set
6399 removePackageDataLI(p, outInfo, flags);
6400
6401 // Delete application code and resources
6402 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006403 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006404 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006405 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006406 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6407 PackageManager.INSTALL_FORWARD_LOCK : 0;
6408 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006409 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006410 }
6411 return true;
6412 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006414 /*
6415 * This method handles package deletion in general
6416 */
6417 private boolean deletePackageLI(String packageName,
6418 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6419 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006420 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006421 return false;
6422 }
6423 PackageParser.Package p;
6424 boolean dataOnly = false;
6425 synchronized (mPackages) {
6426 p = mPackages.get(packageName);
6427 if (p == null) {
6428 //this retrieves partially installed apps
6429 dataOnly = true;
6430 PackageSetting ps = mSettings.mPackages.get(packageName);
6431 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006432 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006433 return false;
6434 }
6435 p = ps.pkg;
6436 }
6437 }
6438 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006439 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006440 return false;
6441 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006443 if (dataOnly) {
6444 // Delete application data first
6445 removePackageDataLI(p, outInfo, flags);
6446 return true;
6447 }
6448 // At this point the package should have ApplicationInfo associated with it
6449 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006450 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006451 return false;
6452 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006453 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6455 Log.i(TAG, "Removing system package:"+p.packageName);
6456 // When an updated system application is deleted we delete the existing resources as well and
6457 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006458 ret = deleteSystemPackageLI(p, flags, outInfo);
6459 } else {
6460 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006461 // Kill application pre-emptively especially for apps on sd.
6462 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006463 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006464 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006465 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006466 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006468 public void clearApplicationUserData(final String packageName,
6469 final IPackageDataObserver observer) {
6470 mContext.enforceCallingOrSelfPermission(
6471 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6472 // Queue up an async operation since the package deletion may take a little while.
6473 mHandler.post(new Runnable() {
6474 public void run() {
6475 mHandler.removeCallbacks(this);
6476 final boolean succeeded;
6477 synchronized (mInstallLock) {
6478 succeeded = clearApplicationUserDataLI(packageName);
6479 }
6480 if (succeeded) {
6481 // invoke DeviceStorageMonitor's update method to clear any notifications
6482 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6483 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6484 if (dsm != null) {
6485 dsm.updateMemory();
6486 }
6487 }
6488 if(observer != null) {
6489 try {
6490 observer.onRemoveCompleted(packageName, succeeded);
6491 } catch (RemoteException e) {
6492 Log.i(TAG, "Observer no longer exists.");
6493 }
6494 } //end if observer
6495 } //end run
6496 });
6497 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006499 private boolean clearApplicationUserDataLI(String packageName) {
6500 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006501 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006502 return false;
6503 }
6504 PackageParser.Package p;
6505 boolean dataOnly = false;
6506 synchronized (mPackages) {
6507 p = mPackages.get(packageName);
6508 if(p == null) {
6509 dataOnly = true;
6510 PackageSetting ps = mSettings.mPackages.get(packageName);
6511 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006512 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006513 return false;
6514 }
6515 p = ps.pkg;
6516 }
6517 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006518 boolean useEncryptedFSDir = false;
6519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006520 if(!dataOnly) {
6521 //need to check this only for fully installed applications
6522 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006523 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 return false;
6525 }
6526 final ApplicationInfo applicationInfo = p.applicationInfo;
6527 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006528 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006529 return false;
6530 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006531 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006532 }
6533 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006534 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006535 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006536 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006537 + packageName);
6538 return false;
6539 }
6540 }
6541 return true;
6542 }
6543
6544 public void deleteApplicationCacheFiles(final String packageName,
6545 final IPackageDataObserver observer) {
6546 mContext.enforceCallingOrSelfPermission(
6547 android.Manifest.permission.DELETE_CACHE_FILES, null);
6548 // Queue up an async operation since the package deletion may take a little while.
6549 mHandler.post(new Runnable() {
6550 public void run() {
6551 mHandler.removeCallbacks(this);
6552 final boolean succeded;
6553 synchronized (mInstallLock) {
6554 succeded = deleteApplicationCacheFilesLI(packageName);
6555 }
6556 if(observer != null) {
6557 try {
6558 observer.onRemoveCompleted(packageName, succeded);
6559 } catch (RemoteException e) {
6560 Log.i(TAG, "Observer no longer exists.");
6561 }
6562 } //end if observer
6563 } //end run
6564 });
6565 }
6566
6567 private boolean deleteApplicationCacheFilesLI(String packageName) {
6568 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006569 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006570 return false;
6571 }
6572 PackageParser.Package p;
6573 synchronized (mPackages) {
6574 p = mPackages.get(packageName);
6575 }
6576 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006577 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006578 return false;
6579 }
6580 final ApplicationInfo applicationInfo = p.applicationInfo;
6581 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006582 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006583 return false;
6584 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006585 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006586 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006587 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006589 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006590 + packageName);
6591 return false;
6592 }
6593 }
6594 return true;
6595 }
6596
6597 public void getPackageSizeInfo(final String packageName,
6598 final IPackageStatsObserver observer) {
6599 mContext.enforceCallingOrSelfPermission(
6600 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6601 // Queue up an async operation since the package deletion may take a little while.
6602 mHandler.post(new Runnable() {
6603 public void run() {
6604 mHandler.removeCallbacks(this);
6605 PackageStats lStats = new PackageStats(packageName);
6606 final boolean succeded;
6607 synchronized (mInstallLock) {
6608 succeded = getPackageSizeInfoLI(packageName, lStats);
6609 }
6610 if(observer != null) {
6611 try {
6612 observer.onGetStatsCompleted(lStats, succeded);
6613 } catch (RemoteException e) {
6614 Log.i(TAG, "Observer no longer exists.");
6615 }
6616 } //end if observer
6617 } //end run
6618 });
6619 }
6620
6621 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6622 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006623 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006624 return false;
6625 }
6626 PackageParser.Package p;
6627 boolean dataOnly = false;
6628 synchronized (mPackages) {
6629 p = mPackages.get(packageName);
6630 if(p == null) {
6631 dataOnly = true;
6632 PackageSetting ps = mSettings.mPackages.get(packageName);
6633 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006634 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006635 return false;
6636 }
6637 p = ps.pkg;
6638 }
6639 }
6640 String publicSrcDir = null;
6641 if(!dataOnly) {
6642 final ApplicationInfo applicationInfo = p.applicationInfo;
6643 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006644 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006645 return false;
6646 }
6647 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6648 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006649 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006650 if (mInstaller != null) {
6651 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006652 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006653 if (res < 0) {
6654 return false;
6655 } else {
6656 return true;
6657 }
6658 }
6659 return true;
6660 }
6661
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006663 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006664 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006665 }
6666
6667 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006668 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006669 }
6670
6671 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006672 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006673 }
6674
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006675 int getUidTargetSdkVersionLockedLP(int uid) {
6676 Object obj = mSettings.getUserIdLP(uid);
6677 if (obj instanceof SharedUserSetting) {
6678 SharedUserSetting sus = (SharedUserSetting)obj;
6679 final int N = sus.packages.size();
6680 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6681 Iterator<PackageSetting> it = sus.packages.iterator();
6682 int i=0;
6683 while (it.hasNext()) {
6684 PackageSetting ps = it.next();
6685 if (ps.pkg != null) {
6686 int v = ps.pkg.applicationInfo.targetSdkVersion;
6687 if (v < vers) vers = v;
6688 }
6689 }
6690 return vers;
6691 } else if (obj instanceof PackageSetting) {
6692 PackageSetting ps = (PackageSetting)obj;
6693 if (ps.pkg != null) {
6694 return ps.pkg.applicationInfo.targetSdkVersion;
6695 }
6696 }
6697 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6698 }
6699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006700 public void addPreferredActivity(IntentFilter filter, int match,
6701 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006702 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006703 if (mContext.checkCallingOrSelfPermission(
6704 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6705 != PackageManager.PERMISSION_GRANTED) {
6706 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6707 < Build.VERSION_CODES.FROYO) {
6708 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6709 + Binder.getCallingUid());
6710 return;
6711 }
6712 mContext.enforceCallingOrSelfPermission(
6713 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6714 }
6715
6716 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006717 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6718 mSettings.mPreferredActivities.addFilter(
6719 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006720 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006721 }
6722 }
6723
Satish Sampath8dbe6122009-06-02 23:35:54 +01006724 public void replacePreferredActivity(IntentFilter filter, int match,
6725 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006726 if (filter.countActions() != 1) {
6727 throw new IllegalArgumentException(
6728 "replacePreferredActivity expects filter to have only 1 action.");
6729 }
6730 if (filter.countCategories() != 1) {
6731 throw new IllegalArgumentException(
6732 "replacePreferredActivity expects filter to have only 1 category.");
6733 }
6734 if (filter.countDataAuthorities() != 0
6735 || filter.countDataPaths() != 0
6736 || filter.countDataSchemes() != 0
6737 || filter.countDataTypes() != 0) {
6738 throw new IllegalArgumentException(
6739 "replacePreferredActivity expects filter to have no data authorities, " +
6740 "paths, schemes or types.");
6741 }
6742 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006743 if (mContext.checkCallingOrSelfPermission(
6744 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6745 != PackageManager.PERMISSION_GRANTED) {
6746 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6747 < Build.VERSION_CODES.FROYO) {
6748 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6749 + Binder.getCallingUid());
6750 return;
6751 }
6752 mContext.enforceCallingOrSelfPermission(
6753 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6754 }
6755
Satish Sampath8dbe6122009-06-02 23:35:54 +01006756 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6757 String action = filter.getAction(0);
6758 String category = filter.getCategory(0);
6759 while (it.hasNext()) {
6760 PreferredActivity pa = it.next();
6761 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6762 it.remove();
6763 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6764 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6765 }
6766 }
6767 addPreferredActivity(filter, match, set, activity);
6768 }
6769 }
6770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006771 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006772 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006773 int uid = Binder.getCallingUid();
6774 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006775 if (pkg == null || pkg.applicationInfo.uid != uid) {
6776 if (mContext.checkCallingOrSelfPermission(
6777 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6778 != PackageManager.PERMISSION_GRANTED) {
6779 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6780 < Build.VERSION_CODES.FROYO) {
6781 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6782 + Binder.getCallingUid());
6783 return;
6784 }
6785 mContext.enforceCallingOrSelfPermission(
6786 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6787 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006788 }
6789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006790 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006791 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006792 }
6793 }
6794 }
6795
6796 boolean clearPackagePreferredActivitiesLP(String packageName) {
6797 boolean changed = false;
6798 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6799 while (it.hasNext()) {
6800 PreferredActivity pa = it.next();
6801 if (pa.mActivity.getPackageName().equals(packageName)) {
6802 it.remove();
6803 changed = true;
6804 }
6805 }
6806 return changed;
6807 }
6808
6809 public int getPreferredActivities(List<IntentFilter> outFilters,
6810 List<ComponentName> outActivities, String packageName) {
6811
6812 int num = 0;
6813 synchronized (mPackages) {
6814 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6815 while (it.hasNext()) {
6816 PreferredActivity pa = it.next();
6817 if (packageName == null
6818 || pa.mActivity.getPackageName().equals(packageName)) {
6819 if (outFilters != null) {
6820 outFilters.add(new IntentFilter(pa));
6821 }
6822 if (outActivities != null) {
6823 outActivities.add(pa.mActivity);
6824 }
6825 }
6826 }
6827 }
6828
6829 return num;
6830 }
6831
6832 public void setApplicationEnabledSetting(String appPackageName,
6833 int newState, int flags) {
6834 setEnabledSetting(appPackageName, null, newState, flags);
6835 }
6836
6837 public void setComponentEnabledSetting(ComponentName componentName,
6838 int newState, int flags) {
6839 setEnabledSetting(componentName.getPackageName(),
6840 componentName.getClassName(), newState, flags);
6841 }
6842
6843 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006844 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006845 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6846 || newState == COMPONENT_ENABLED_STATE_ENABLED
6847 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6848 throw new IllegalArgumentException("Invalid new component state: "
6849 + newState);
6850 }
6851 PackageSetting pkgSetting;
6852 final int uid = Binder.getCallingUid();
6853 final int permission = mContext.checkCallingPermission(
6854 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6855 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006856 boolean sendNow = false;
6857 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006858 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006859 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006860 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006861 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006862 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006863 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006864 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006865 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006866 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006867 }
6868 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006869 "Unknown component: " + packageName
6870 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006871 }
6872 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6873 throw new SecurityException(
6874 "Permission Denial: attempt to change component state from pid="
6875 + Binder.getCallingPid()
6876 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6877 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006878 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006879 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006880 if (pkgSetting.enabled == newState) {
6881 // Nothing to do
6882 return;
6883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006884 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006885 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006886 } else {
6887 // We're dealing with a component level state change
6888 switch (newState) {
6889 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006890 if (!pkgSetting.enableComponentLP(className)) {
6891 return;
6892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006893 break;
6894 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006895 if (!pkgSetting.disableComponentLP(className)) {
6896 return;
6897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006898 break;
6899 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006900 if (!pkgSetting.restoreComponentLP(className)) {
6901 return;
6902 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006903 break;
6904 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006905 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006906 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006907 }
6908 }
6909 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006910 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006911 components = mPendingBroadcasts.get(packageName);
6912 boolean newPackage = components == null;
6913 if (newPackage) {
6914 components = new ArrayList<String>();
6915 }
6916 if (!components.contains(componentName)) {
6917 components.add(componentName);
6918 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006919 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6920 sendNow = true;
6921 // Purge entry from pending broadcast list if another one exists already
6922 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006923 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006924 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006925 if (newPackage) {
6926 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006927 }
6928 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6929 // Schedule a message
6930 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6931 }
6932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006933 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006935 long callingId = Binder.clearCallingIdentity();
6936 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006937 if (sendNow) {
6938 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006939 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006941 } finally {
6942 Binder.restoreCallingIdentity(callingId);
6943 }
6944 }
6945
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006946 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006947 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6948 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6949 + " components=" + componentNames);
6950 Bundle extras = new Bundle(4);
6951 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6952 String nameList[] = new String[componentNames.size()];
6953 componentNames.toArray(nameList);
6954 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006955 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6956 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006957 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006958 }
6959
Jacek Surazski65e13172009-04-28 15:26:38 +02006960 public String getInstallerPackageName(String packageName) {
6961 synchronized (mPackages) {
6962 PackageSetting pkg = mSettings.mPackages.get(packageName);
6963 if (pkg == null) {
6964 throw new IllegalArgumentException("Unknown package: " + packageName);
6965 }
6966 return pkg.installerPackageName;
6967 }
6968 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006970 public int getApplicationEnabledSetting(String appPackageName) {
6971 synchronized (mPackages) {
6972 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6973 if (pkg == null) {
6974 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6975 }
6976 return pkg.enabled;
6977 }
6978 }
6979
6980 public int getComponentEnabledSetting(ComponentName componentName) {
6981 synchronized (mPackages) {
6982 final String packageNameStr = componentName.getPackageName();
6983 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6984 if (pkg == null) {
6985 throw new IllegalArgumentException("Unknown component: " + componentName);
6986 }
6987 final String classNameStr = componentName.getClassName();
6988 return pkg.currentEnabledStateLP(classNameStr);
6989 }
6990 }
6991
6992 public void enterSafeMode() {
6993 if (!mSystemReady) {
6994 mSafeMode = true;
6995 }
6996 }
6997
6998 public void systemReady() {
6999 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007000
7001 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07007002 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007003 mContext.getContentResolver(),
7004 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07007005 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007006 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07007007 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007009 }
7010
7011 public boolean isSafeMode() {
7012 return mSafeMode;
7013 }
7014
7015 public boolean hasSystemUidErrors() {
7016 return mHasSystemUidErrors;
7017 }
7018
7019 static String arrayToString(int[] array) {
7020 StringBuffer buf = new StringBuffer(128);
7021 buf.append('[');
7022 if (array != null) {
7023 for (int i=0; i<array.length; i++) {
7024 if (i > 0) buf.append(", ");
7025 buf.append(array[i]);
7026 }
7027 }
7028 buf.append(']');
7029 return buf.toString();
7030 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007032 @Override
7033 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
7034 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
7035 != PackageManager.PERMISSION_GRANTED) {
7036 pw.println("Permission Denial: can't dump ActivityManager from from pid="
7037 + Binder.getCallingPid()
7038 + ", uid=" + Binder.getCallingUid()
7039 + " without permission "
7040 + android.Manifest.permission.DUMP);
7041 return;
7042 }
7043
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007044 String packageName = null;
7045
7046 int opti = 0;
7047 while (opti < args.length) {
7048 String opt = args[opti];
7049 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
7050 break;
7051 }
7052 opti++;
7053 if ("-a".equals(opt)) {
7054 // Right now we only know how to print all.
7055 } else if ("-h".equals(opt)) {
7056 pw.println("Package manager dump options:");
7057 pw.println(" [-h] [cmd] ...");
7058 pw.println(" cmd may be one of:");
7059 pw.println(" [package.name]: info about given package");
7060 return;
7061 } else {
7062 pw.println("Unknown argument: " + opt + "; use -h for help");
7063 }
7064 }
7065
7066 // Is the caller requesting to dump a particular piece of data?
7067 if (opti < args.length) {
7068 String cmd = args[opti];
7069 opti++;
7070 // Is this a package name?
7071 if ("android".equals(cmd) || cmd.contains(".")) {
7072 packageName = cmd;
7073 }
7074 }
7075
7076 boolean printedTitle = false;
7077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007078 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007079 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
7080 printedTitle = true;
7081 }
7082 if (mReceivers.dump(pw, printedTitle
7083 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
7084 " ", packageName)) {
7085 printedTitle = true;
7086 }
7087 if (mServices.dump(pw, printedTitle
7088 ? "\nService Resolver Table:" : "Service Resolver Table:",
7089 " ", packageName)) {
7090 printedTitle = true;
7091 }
7092 if (mSettings.mPreferredActivities.dump(pw, printedTitle
7093 ? "\nPreferred Activities:" : "Preferred Activities:",
7094 " ", packageName)) {
7095 printedTitle = true;
7096 }
7097 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007098 {
7099 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007100 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7101 continue;
7102 }
7103 if (!printedSomething) {
7104 if (printedTitle) pw.println(" ");
7105 pw.println("Permissions:");
7106 printedSomething = true;
7107 printedTitle = true;
7108 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007109 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7110 pw.print(Integer.toHexString(System.identityHashCode(p)));
7111 pw.println("):");
7112 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7113 pw.print(" uid="); pw.print(p.uid);
7114 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007115 pw.print(" type="); pw.print(p.type);
7116 pw.print(" prot="); pw.println(p.protectionLevel);
7117 if (p.packageSetting != null) {
7118 pw.print(" packageSetting="); pw.println(p.packageSetting);
7119 }
7120 if (p.perm != null) {
7121 pw.print(" perm="); pw.println(p.perm);
7122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007123 }
7124 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007125 printedSomething = false;
7126 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007127 {
7128 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007129 if (packageName != null && !packageName.equals(ps.realName)
7130 && !packageName.equals(ps.name)) {
7131 continue;
7132 }
7133 if (!printedSomething) {
7134 if (printedTitle) pw.println(" ");
7135 pw.println("Packages:");
7136 printedSomething = true;
7137 printedTitle = true;
7138 }
7139 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007140 pw.print(" Package [");
7141 pw.print(ps.realName != null ? ps.realName : ps.name);
7142 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007143 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7144 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007145 if (ps.realName != null) {
7146 pw.print(" compat name="); pw.println(ps.name);
7147 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007148 pw.print(" userId="); pw.print(ps.userId);
7149 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7150 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7151 pw.print(" pkg="); pw.println(ps.pkg);
7152 pw.print(" codePath="); pw.println(ps.codePathString);
7153 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07007154 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007155 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007156 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007157 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007158 pw.print(" supportsScreens=[");
7159 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007160 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007161 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7162 if (!first) pw.print(", ");
7163 first = false;
7164 pw.print("small");
7165 }
7166 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007167 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007168 if (!first) pw.print(", ");
7169 first = false;
7170 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007171 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007172 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007173 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007174 if (!first) pw.print(", ");
7175 first = false;
7176 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007177 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007178 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007179 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007180 if (!first) pw.print(", ");
7181 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007182 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007183 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007184 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007185 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007186 if (!first) pw.print(", ");
7187 first = false;
7188 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007189 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007190 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007191 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7192 if (!first) pw.print(", ");
7193 first = false;
7194 pw.print("anyDensity");
7195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007196 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007197 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007198 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7199 pw.print(" signatures="); pw.println(ps.signatures);
7200 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007201 pw.print(" haveGids="); pw.println(ps.haveGids);
7202 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007203 pw.print(" installStatus="); pw.print(ps.installStatus);
7204 pw.print(" enabled="); pw.println(ps.enabled);
Kenny Rootdeb11262010-08-02 11:36:21 -07007205 if (ps.pkg.mOperationPending) {
7206 pw.println(" mOperationPending=true");
7207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007208 if (ps.disabledComponents.size() > 0) {
7209 pw.println(" disabledComponents:");
7210 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007211 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007212 }
7213 }
7214 if (ps.enabledComponents.size() > 0) {
7215 pw.println(" enabledComponents:");
7216 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007217 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007218 }
7219 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007220 if (ps.grantedPermissions.size() > 0) {
7221 pw.println(" grantedPermissions:");
7222 for (String s : ps.grantedPermissions) {
7223 pw.print(" "); pw.println(s);
7224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007226 }
7227 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007228 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007229 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007230 for (HashMap.Entry<String, String> e
7231 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007232 if (packageName != null && !packageName.equals(e.getKey())
7233 && !packageName.equals(e.getValue())) {
7234 continue;
7235 }
7236 if (!printedSomething) {
7237 if (printedTitle) pw.println(" ");
7238 pw.println("Renamed packages:");
7239 printedSomething = true;
7240 printedTitle = true;
7241 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007242 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7243 pw.println(e.getValue());
7244 }
7245 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007246 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007247 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007248 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007249 if (packageName != null && !packageName.equals(ps.realName)
7250 && !packageName.equals(ps.name)) {
7251 continue;
7252 }
7253 if (!printedSomething) {
7254 if (printedTitle) pw.println(" ");
7255 pw.println("Hidden system packages:");
7256 printedSomething = true;
7257 printedTitle = true;
7258 }
7259 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007260 pw.print(ps.realName != null ? ps.realName : ps.name);
7261 pw.print("] (");
7262 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7263 pw.println("):");
7264 if (ps.realName != null) {
7265 pw.print(" compat name="); pw.println(ps.name);
7266 }
7267 pw.print(" userId="); pw.println(ps.userId);
7268 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7269 pw.print(" codePath="); pw.println(ps.codePathString);
7270 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7271 }
7272 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007273 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007274 {
7275 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007276 if (packageName != null && su != packageSharedUser) {
7277 continue;
7278 }
7279 if (!printedSomething) {
7280 if (printedTitle) pw.println(" ");
7281 pw.println("Shared users:");
7282 printedSomething = true;
7283 printedTitle = true;
7284 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007285 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7286 pw.print(Integer.toHexString(System.identityHashCode(su)));
7287 pw.println("):");
7288 pw.print(" userId="); pw.print(su.userId);
7289 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007290 pw.println(" grantedPermissions:");
7291 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007292 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007294 }
7295 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007296
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007297 if (packageName == null) {
7298 if (printedTitle) pw.println(" ");
7299 printedTitle = true;
7300 pw.println("Settings parse messages:");
7301 pw.println(mSettings.mReadMessages.toString());
7302
7303 pw.println(" ");
7304 pw.println("Package warning messages:");
7305 File fname = getSettingsProblemFile();
7306 FileInputStream in;
7307 try {
7308 in = new FileInputStream(fname);
7309 int avail = in.available();
7310 byte[] data = new byte[avail];
7311 in.read(data);
7312 pw.println(new String(data));
7313 } catch (FileNotFoundException e) {
7314 } catch (IOException e) {
7315 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007317 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007318
7319 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007320 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007321 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007322 if (packageName != null && !packageName.equals(p.info.packageName)) {
7323 continue;
7324 }
7325 if (!printedSomething) {
7326 if (printedTitle) pw.println(" ");
7327 pw.println("Registered ContentProviders:");
7328 printedSomething = true;
7329 printedTitle = true;
7330 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007331 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007332 pw.println(p.toString());
7333 }
7334 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007335 }
7336
7337 static final class BasePermission {
7338 final static int TYPE_NORMAL = 0;
7339 final static int TYPE_BUILTIN = 1;
7340 final static int TYPE_DYNAMIC = 2;
7341
7342 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007343 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007344 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007345 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007346 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007347 PackageParser.Permission perm;
7348 PermissionInfo pendingInfo;
7349 int uid;
7350 int[] gids;
7351
7352 BasePermission(String _name, String _sourcePackage, int _type) {
7353 name = _name;
7354 sourcePackage = _sourcePackage;
7355 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007356 // Default to most conservative protection level.
7357 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7358 }
7359
7360 public String toString() {
7361 return "BasePermission{"
7362 + Integer.toHexString(System.identityHashCode(this))
7363 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007364 }
7365 }
7366
7367 static class PackageSignatures {
7368 private Signature[] mSignatures;
7369
7370 PackageSignatures(Signature[] sigs) {
7371 assignSignatures(sigs);
7372 }
7373
7374 PackageSignatures() {
7375 }
7376
7377 void writeXml(XmlSerializer serializer, String tagName,
7378 ArrayList<Signature> pastSignatures) throws IOException {
7379 if (mSignatures == null) {
7380 return;
7381 }
7382 serializer.startTag(null, tagName);
7383 serializer.attribute(null, "count",
7384 Integer.toString(mSignatures.length));
7385 for (int i=0; i<mSignatures.length; i++) {
7386 serializer.startTag(null, "cert");
7387 final Signature sig = mSignatures[i];
7388 final int sigHash = sig.hashCode();
7389 final int numPast = pastSignatures.size();
7390 int j;
7391 for (j=0; j<numPast; j++) {
7392 Signature pastSig = pastSignatures.get(j);
7393 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7394 serializer.attribute(null, "index", Integer.toString(j));
7395 break;
7396 }
7397 }
7398 if (j >= numPast) {
7399 pastSignatures.add(sig);
7400 serializer.attribute(null, "index", Integer.toString(numPast));
7401 serializer.attribute(null, "key", sig.toCharsString());
7402 }
7403 serializer.endTag(null, "cert");
7404 }
7405 serializer.endTag(null, tagName);
7406 }
7407
7408 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7409 throws IOException, XmlPullParserException {
7410 String countStr = parser.getAttributeValue(null, "count");
7411 if (countStr == null) {
7412 reportSettingsProblem(Log.WARN,
7413 "Error in package manager settings: <signatures> has"
7414 + " no count at " + parser.getPositionDescription());
7415 XmlUtils.skipCurrentTag(parser);
7416 }
7417 final int count = Integer.parseInt(countStr);
7418 mSignatures = new Signature[count];
7419 int pos = 0;
7420
7421 int outerDepth = parser.getDepth();
7422 int type;
7423 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7424 && (type != XmlPullParser.END_TAG
7425 || parser.getDepth() > outerDepth)) {
7426 if (type == XmlPullParser.END_TAG
7427 || type == XmlPullParser.TEXT) {
7428 continue;
7429 }
7430
7431 String tagName = parser.getName();
7432 if (tagName.equals("cert")) {
7433 if (pos < count) {
7434 String index = parser.getAttributeValue(null, "index");
7435 if (index != null) {
7436 try {
7437 int idx = Integer.parseInt(index);
7438 String key = parser.getAttributeValue(null, "key");
7439 if (key == null) {
7440 if (idx >= 0 && idx < pastSignatures.size()) {
7441 Signature sig = pastSignatures.get(idx);
7442 if (sig != null) {
7443 mSignatures[pos] = pastSignatures.get(idx);
7444 pos++;
7445 } else {
7446 reportSettingsProblem(Log.WARN,
7447 "Error in package manager settings: <cert> "
7448 + "index " + index + " is not defined at "
7449 + parser.getPositionDescription());
7450 }
7451 } else {
7452 reportSettingsProblem(Log.WARN,
7453 "Error in package manager settings: <cert> "
7454 + "index " + index + " is out of bounds at "
7455 + parser.getPositionDescription());
7456 }
7457 } else {
7458 while (pastSignatures.size() <= idx) {
7459 pastSignatures.add(null);
7460 }
7461 Signature sig = new Signature(key);
7462 pastSignatures.set(idx, sig);
7463 mSignatures[pos] = sig;
7464 pos++;
7465 }
7466 } catch (NumberFormatException e) {
7467 reportSettingsProblem(Log.WARN,
7468 "Error in package manager settings: <cert> "
7469 + "index " + index + " is not a number at "
7470 + parser.getPositionDescription());
7471 }
7472 } else {
7473 reportSettingsProblem(Log.WARN,
7474 "Error in package manager settings: <cert> has"
7475 + " no index at " + parser.getPositionDescription());
7476 }
7477 } else {
7478 reportSettingsProblem(Log.WARN,
7479 "Error in package manager settings: too "
7480 + "many <cert> tags, expected " + count
7481 + " at " + parser.getPositionDescription());
7482 }
7483 } else {
7484 reportSettingsProblem(Log.WARN,
7485 "Unknown element under <cert>: "
7486 + parser.getName());
7487 }
7488 XmlUtils.skipCurrentTag(parser);
7489 }
7490
7491 if (pos < count) {
7492 // Should never happen -- there is an error in the written
7493 // settings -- but if it does we don't want to generate
7494 // a bad array.
7495 Signature[] newSigs = new Signature[pos];
7496 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7497 mSignatures = newSigs;
7498 }
7499 }
7500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007501 private void assignSignatures(Signature[] sigs) {
7502 if (sigs == null) {
7503 mSignatures = null;
7504 return;
7505 }
7506 mSignatures = new Signature[sigs.length];
7507 for (int i=0; i<sigs.length; i++) {
7508 mSignatures[i] = sigs[i];
7509 }
7510 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007512 @Override
7513 public String toString() {
7514 StringBuffer buf = new StringBuffer(128);
7515 buf.append("PackageSignatures{");
7516 buf.append(Integer.toHexString(System.identityHashCode(this)));
7517 buf.append(" [");
7518 if (mSignatures != null) {
7519 for (int i=0; i<mSignatures.length; i++) {
7520 if (i > 0) buf.append(", ");
7521 buf.append(Integer.toHexString(
7522 System.identityHashCode(mSignatures[i])));
7523 }
7524 }
7525 buf.append("]}");
7526 return buf.toString();
7527 }
7528 }
7529
7530 static class PreferredActivity extends IntentFilter {
7531 final int mMatch;
7532 final String[] mSetPackages;
7533 final String[] mSetClasses;
7534 final String[] mSetComponents;
7535 final ComponentName mActivity;
7536 final String mShortActivity;
7537 String mParseError;
7538
7539 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7540 ComponentName activity) {
7541 super(filter);
7542 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7543 mActivity = activity;
7544 mShortActivity = activity.flattenToShortString();
7545 mParseError = null;
7546 if (set != null) {
7547 final int N = set.length;
7548 String[] myPackages = new String[N];
7549 String[] myClasses = new String[N];
7550 String[] myComponents = new String[N];
7551 for (int i=0; i<N; i++) {
7552 ComponentName cn = set[i];
7553 if (cn == null) {
7554 mSetPackages = null;
7555 mSetClasses = null;
7556 mSetComponents = null;
7557 return;
7558 }
7559 myPackages[i] = cn.getPackageName().intern();
7560 myClasses[i] = cn.getClassName().intern();
7561 myComponents[i] = cn.flattenToShortString().intern();
7562 }
7563 mSetPackages = myPackages;
7564 mSetClasses = myClasses;
7565 mSetComponents = myComponents;
7566 } else {
7567 mSetPackages = null;
7568 mSetClasses = null;
7569 mSetComponents = null;
7570 }
7571 }
7572
7573 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7574 IOException {
7575 mShortActivity = parser.getAttributeValue(null, "name");
7576 mActivity = ComponentName.unflattenFromString(mShortActivity);
7577 if (mActivity == null) {
7578 mParseError = "Bad activity name " + mShortActivity;
7579 }
7580 String matchStr = parser.getAttributeValue(null, "match");
7581 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7582 String setCountStr = parser.getAttributeValue(null, "set");
7583 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7584
7585 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7586 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7587 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7588
7589 int setPos = 0;
7590
7591 int outerDepth = parser.getDepth();
7592 int type;
7593 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7594 && (type != XmlPullParser.END_TAG
7595 || parser.getDepth() > outerDepth)) {
7596 if (type == XmlPullParser.END_TAG
7597 || type == XmlPullParser.TEXT) {
7598 continue;
7599 }
7600
7601 String tagName = parser.getName();
7602 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7603 // + parser.getDepth() + " tag=" + tagName);
7604 if (tagName.equals("set")) {
7605 String name = parser.getAttributeValue(null, "name");
7606 if (name == null) {
7607 if (mParseError == null) {
7608 mParseError = "No name in set tag in preferred activity "
7609 + mShortActivity;
7610 }
7611 } else if (setPos >= setCount) {
7612 if (mParseError == null) {
7613 mParseError = "Too many set tags in preferred activity "
7614 + mShortActivity;
7615 }
7616 } else {
7617 ComponentName cn = ComponentName.unflattenFromString(name);
7618 if (cn == null) {
7619 if (mParseError == null) {
7620 mParseError = "Bad set name " + name + " in preferred activity "
7621 + mShortActivity;
7622 }
7623 } else {
7624 myPackages[setPos] = cn.getPackageName();
7625 myClasses[setPos] = cn.getClassName();
7626 myComponents[setPos] = name;
7627 setPos++;
7628 }
7629 }
7630 XmlUtils.skipCurrentTag(parser);
7631 } else if (tagName.equals("filter")) {
7632 //Log.i(TAG, "Starting to parse filter...");
7633 readFromXml(parser);
7634 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7635 // + parser.getDepth() + " tag=" + parser.getName());
7636 } else {
7637 reportSettingsProblem(Log.WARN,
7638 "Unknown element under <preferred-activities>: "
7639 + parser.getName());
7640 XmlUtils.skipCurrentTag(parser);
7641 }
7642 }
7643
7644 if (setPos != setCount) {
7645 if (mParseError == null) {
7646 mParseError = "Not enough set tags (expected " + setCount
7647 + " but found " + setPos + ") in " + mShortActivity;
7648 }
7649 }
7650
7651 mSetPackages = myPackages;
7652 mSetClasses = myClasses;
7653 mSetComponents = myComponents;
7654 }
7655
7656 public void writeToXml(XmlSerializer serializer) throws IOException {
7657 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7658 serializer.attribute(null, "name", mShortActivity);
7659 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7660 serializer.attribute(null, "set", Integer.toString(NS));
7661 for (int s=0; s<NS; s++) {
7662 serializer.startTag(null, "set");
7663 serializer.attribute(null, "name", mSetComponents[s]);
7664 serializer.endTag(null, "set");
7665 }
7666 serializer.startTag(null, "filter");
7667 super.writeToXml(serializer);
7668 serializer.endTag(null, "filter");
7669 }
7670
7671 boolean sameSet(List<ResolveInfo> query, int priority) {
7672 if (mSetPackages == null) return false;
7673 final int NQ = query.size();
7674 final int NS = mSetPackages.length;
7675 int numMatch = 0;
7676 for (int i=0; i<NQ; i++) {
7677 ResolveInfo ri = query.get(i);
7678 if (ri.priority != priority) continue;
7679 ActivityInfo ai = ri.activityInfo;
7680 boolean good = false;
7681 for (int j=0; j<NS; j++) {
7682 if (mSetPackages[j].equals(ai.packageName)
7683 && mSetClasses[j].equals(ai.name)) {
7684 numMatch++;
7685 good = true;
7686 break;
7687 }
7688 }
7689 if (!good) return false;
7690 }
7691 return numMatch == NS;
7692 }
7693 }
7694
7695 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007696 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007698 HashSet<String> grantedPermissions = new HashSet<String>();
7699 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007701 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007702 setFlags(pkgFlags);
7703 }
7704
7705 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007706 this.pkgFlags = pkgFlags & (
7707 ApplicationInfo.FLAG_SYSTEM |
7708 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007709 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007710 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007711 }
7712 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007714 /**
7715 * Settings base class for pending and resolved classes.
7716 */
7717 static class PackageSettingBase extends GrantedPermissions {
7718 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007719 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007720 File codePath;
7721 String codePathString;
7722 File resourcePath;
7723 String resourcePathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007724 String obbPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007725 private long timeStamp;
7726 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007727 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007728
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007729 boolean uidError;
7730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007731 PackageSignatures signatures = new PackageSignatures();
7732
7733 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007734 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007736 /* Explicitly disabled components */
7737 HashSet<String> disabledComponents = new HashSet<String>(0);
7738 /* Explicitly enabled components */
7739 HashSet<String> enabledComponents = new HashSet<String>(0);
7740 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7741 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007742
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007743 PackageSettingBase origPackage;
7744
Jacek Surazski65e13172009-04-28 15:26:38 +02007745 /* package name of the app that installed this package */
7746 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007747
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007748 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007749 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007750 super(pkgFlags);
7751 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007752 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007753 init(codePath, resourcePath, pVersionCode);
7754 }
7755
7756 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007757 this.codePath = codePath;
7758 this.codePathString = codePath.toString();
7759 this.resourcePath = resourcePath;
7760 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007761 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007762 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007763
Jacek Surazski65e13172009-04-28 15:26:38 +02007764 public void setInstallerPackageName(String packageName) {
7765 installerPackageName = packageName;
7766 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007767
Jacek Surazski65e13172009-04-28 15:26:38 +02007768 String getInstallerPackageName() {
7769 return installerPackageName;
7770 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007772 public void setInstallStatus(int newStatus) {
7773 installStatus = newStatus;
7774 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007776 public int getInstallStatus() {
7777 return installStatus;
7778 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007780 public void setTimeStamp(long newStamp) {
7781 if (newStamp != timeStamp) {
7782 timeStamp = newStamp;
7783 timeStampString = Long.toString(newStamp);
7784 }
7785 }
7786
7787 public void setTimeStamp(long newStamp, String newStampStr) {
7788 timeStamp = newStamp;
7789 timeStampString = newStampStr;
7790 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007792 public long getTimeStamp() {
7793 return timeStamp;
7794 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007796 public String getTimeStampStr() {
7797 return timeStampString;
7798 }
7799
7800 public void copyFrom(PackageSettingBase base) {
7801 grantedPermissions = base.grantedPermissions;
7802 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007804 timeStamp = base.timeStamp;
7805 timeStampString = base.timeStampString;
7806 signatures = base.signatures;
7807 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007808 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007809 disabledComponents = base.disabledComponents;
7810 enabledComponents = base.enabledComponents;
7811 enabled = base.enabled;
7812 installStatus = base.installStatus;
7813 }
7814
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007815 boolean enableComponentLP(String componentClassName) {
7816 boolean changed = disabledComponents.remove(componentClassName);
7817 changed |= enabledComponents.add(componentClassName);
7818 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007819 }
7820
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007821 boolean disableComponentLP(String componentClassName) {
7822 boolean changed = enabledComponents.remove(componentClassName);
7823 changed |= disabledComponents.add(componentClassName);
7824 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007825 }
7826
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007827 boolean restoreComponentLP(String componentClassName) {
7828 boolean changed = enabledComponents.remove(componentClassName);
7829 changed |= disabledComponents.remove(componentClassName);
7830 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007831 }
7832
7833 int currentEnabledStateLP(String componentName) {
7834 if (enabledComponents.contains(componentName)) {
7835 return COMPONENT_ENABLED_STATE_ENABLED;
7836 } else if (disabledComponents.contains(componentName)) {
7837 return COMPONENT_ENABLED_STATE_DISABLED;
7838 } else {
7839 return COMPONENT_ENABLED_STATE_DEFAULT;
7840 }
7841 }
7842 }
7843
7844 /**
7845 * Settings data for a particular package we know about.
7846 */
7847 static final class PackageSetting extends PackageSettingBase {
7848 int userId;
7849 PackageParser.Package pkg;
7850 SharedUserSetting sharedUser;
7851
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007852 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007853 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007854 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007855 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007857 @Override
7858 public String toString() {
7859 return "PackageSetting{"
7860 + Integer.toHexString(System.identityHashCode(this))
7861 + " " + name + "/" + userId + "}";
7862 }
7863 }
7864
7865 /**
7866 * Settings data for a particular shared user ID we know about.
7867 */
7868 static final class SharedUserSetting extends GrantedPermissions {
7869 final String name;
7870 int userId;
7871 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7872 final PackageSignatures signatures = new PackageSignatures();
7873
7874 SharedUserSetting(String _name, int _pkgFlags) {
7875 super(_pkgFlags);
7876 name = _name;
7877 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007879 @Override
7880 public String toString() {
7881 return "SharedUserSetting{"
7882 + Integer.toHexString(System.identityHashCode(this))
7883 + " " + name + "/" + userId + "}";
7884 }
7885 }
7886
7887 /**
7888 * Holds information about dynamic settings.
7889 */
7890 private static final class Settings {
7891 private final File mSettingsFilename;
7892 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007893 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007894 private final HashMap<String, PackageSetting> mPackages =
7895 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007896 // List of replaced system applications
7897 final HashMap<String, PackageSetting> mDisabledSysPackages =
7898 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007899
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007900 // These are the last platform API version we were using for
7901 // the apps installed on internal and external storage. It is
7902 // used to grant newer permissions one time during a system upgrade.
7903 int mInternalSdkPlatform;
7904 int mExternalSdkPlatform;
7905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007906 // The user's preferred activities associated with particular intent
7907 // filters.
7908 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7909 new IntentResolver<PreferredActivity, PreferredActivity>() {
7910 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007911 protected String packageForFilter(PreferredActivity filter) {
7912 return filter.mActivity.getPackageName();
7913 }
7914 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007915 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007916 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007917 out.print(prefix); out.print(
7918 Integer.toHexString(System.identityHashCode(filter)));
7919 out.print(' ');
7920 out.print(filter.mActivity.flattenToShortString());
7921 out.print(" match=0x");
7922 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007923 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007924 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007925 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007926 out.print(prefix); out.print(" ");
7927 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007928 }
7929 }
7930 }
7931 };
7932 private final HashMap<String, SharedUserSetting> mSharedUsers =
7933 new HashMap<String, SharedUserSetting>();
7934 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7935 private final SparseArray<Object> mOtherUserIds =
7936 new SparseArray<Object>();
7937
7938 // For reading/writing settings file.
7939 private final ArrayList<Signature> mPastSignatures =
7940 new ArrayList<Signature>();
7941
7942 // Mapping from permission names to info about them.
7943 final HashMap<String, BasePermission> mPermissions =
7944 new HashMap<String, BasePermission>();
7945
7946 // Mapping from permission tree names to info about them.
7947 final HashMap<String, BasePermission> mPermissionTrees =
7948 new HashMap<String, BasePermission>();
7949
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007950 // Packages that have been uninstalled and still need their external
7951 // storage data deleted.
7952 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7953
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007954 // Packages that have been renamed since they were first installed.
7955 // Keys are the new names of the packages, values are the original
7956 // names. The packages appear everwhere else under their original
7957 // names.
7958 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007960 private final StringBuilder mReadMessages = new StringBuilder();
7961
7962 private static final class PendingPackage extends PackageSettingBase {
7963 final int sharedId;
7964
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007965 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007966 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007967 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007968 this.sharedId = sharedId;
7969 }
7970 }
7971 private final ArrayList<PendingPackage> mPendingPackages
7972 = new ArrayList<PendingPackage>();
7973
7974 Settings() {
7975 File dataDir = Environment.getDataDirectory();
7976 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007977 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7978 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007979 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007980 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007981 FileUtils.setPermissions(systemDir.toString(),
7982 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7983 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7984 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007985 FileUtils.setPermissions(systemSecureDir.toString(),
7986 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7987 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7988 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007989 mSettingsFilename = new File(systemDir, "packages.xml");
7990 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007991 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007992 }
7993
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007994 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007995 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007996 int pkgFlags, boolean create, boolean add) {
7997 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007998 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007999 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008000 return p;
8001 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008002
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008003 PackageSetting peekPackageLP(String name) {
8004 return mPackages.get(name);
8005 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008006 PackageSetting p = mPackages.get(name);
8007 if (p != null && p.codePath.getPath().equals(codePath)) {
8008 return p;
8009 }
8010 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008011 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008012 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008014 void setInstallStatus(String pkgName, int status) {
8015 PackageSetting p = mPackages.get(pkgName);
8016 if(p != null) {
8017 if(p.getInstallStatus() != status) {
8018 p.setInstallStatus(status);
8019 }
8020 }
8021 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008022
Jacek Surazski65e13172009-04-28 15:26:38 +02008023 void setInstallerPackageName(String pkgName,
8024 String installerPkgName) {
8025 PackageSetting p = mPackages.get(pkgName);
8026 if(p != null) {
8027 p.setInstallerPackageName(installerPkgName);
8028 }
8029 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008030
Jacek Surazski65e13172009-04-28 15:26:38 +02008031 String getInstallerPackageName(String pkgName) {
8032 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008033 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02008034 }
8035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008036 int getInstallStatus(String pkgName) {
8037 PackageSetting p = mPackages.get(pkgName);
8038 if(p != null) {
8039 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008041 return -1;
8042 }
8043
8044 SharedUserSetting getSharedUserLP(String name,
8045 int pkgFlags, boolean create) {
8046 SharedUserSetting s = mSharedUsers.get(name);
8047 if (s == null) {
8048 if (!create) {
8049 return null;
8050 }
8051 s = new SharedUserSetting(name, pkgFlags);
8052 if (MULTIPLE_APPLICATION_UIDS) {
8053 s.userId = newUserIdLP(s);
8054 } else {
8055 s.userId = FIRST_APPLICATION_UID;
8056 }
8057 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
8058 // < 0 means we couldn't assign a userid; fall out and return
8059 // s, which is currently null
8060 if (s.userId >= 0) {
8061 mSharedUsers.put(name, s);
8062 }
8063 }
8064
8065 return s;
8066 }
8067
8068 int disableSystemPackageLP(String name) {
8069 PackageSetting p = mPackages.get(name);
8070 if(p == null) {
8071 Log.w(TAG, "Package:"+name+" is not an installed package");
8072 return -1;
8073 }
8074 PackageSetting dp = mDisabledSysPackages.get(name);
8075 // always make sure the system package code and resource paths dont change
8076 if(dp == null) {
8077 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8078 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8079 }
8080 mDisabledSysPackages.put(name, p);
8081 }
8082 return removePackageLP(name);
8083 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008085 PackageSetting enableSystemPackageLP(String name) {
8086 PackageSetting p = mDisabledSysPackages.get(name);
8087 if(p == null) {
8088 Log.w(TAG, "Package:"+name+" is not disabled");
8089 return null;
8090 }
8091 // Reset flag in ApplicationInfo object
8092 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8093 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8094 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008095 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008096 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008097 mDisabledSysPackages.remove(name);
8098 return ret;
8099 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008100
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008101 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008102 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008103 PackageSetting p = mPackages.get(name);
8104 if (p != null) {
8105 if (p.userId == uid) {
8106 return p;
8107 }
8108 reportSettingsProblem(Log.ERROR,
8109 "Adding duplicate package, keeping first: " + name);
8110 return null;
8111 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008112 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008113 p.userId = uid;
8114 if (addUserIdLP(uid, p, name)) {
8115 mPackages.put(name, p);
8116 return p;
8117 }
8118 return null;
8119 }
8120
8121 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8122 SharedUserSetting s = mSharedUsers.get(name);
8123 if (s != null) {
8124 if (s.userId == uid) {
8125 return s;
8126 }
8127 reportSettingsProblem(Log.ERROR,
8128 "Adding duplicate shared user, keeping first: " + name);
8129 return null;
8130 }
8131 s = new SharedUserSetting(name, pkgFlags);
8132 s.userId = uid;
8133 if (addUserIdLP(uid, s, name)) {
8134 mSharedUsers.put(name, s);
8135 return s;
8136 }
8137 return null;
8138 }
8139
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008140 // Transfer ownership of permissions from one package to another.
8141 private void transferPermissions(String origPkg, String newPkg) {
8142 // Transfer ownership of permissions to the new package.
8143 for (int i=0; i<2; i++) {
8144 HashMap<String, BasePermission> permissions =
8145 i == 0 ? mPermissionTrees : mPermissions;
8146 for (BasePermission bp : permissions.values()) {
8147 if (origPkg.equals(bp.sourcePackage)) {
8148 if (DEBUG_UPGRADE) Log.v(TAG,
8149 "Moving permission " + bp.name
8150 + " from pkg " + bp.sourcePackage
8151 + " to " + newPkg);
8152 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008153 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008154 bp.perm = null;
8155 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008156 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008157 }
8158 bp.uid = 0;
8159 bp.gids = null;
8160 }
8161 }
8162 }
8163 }
8164
8165 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008166 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008167 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008168 PackageSetting p = mPackages.get(name);
8169 if (p != null) {
8170 if (!p.codePath.equals(codePath)) {
8171 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008172 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008173 // This is an updated system app with versions in both system
8174 // and data partition. Just let the most recent version
8175 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008176 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008177 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008178 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008179 // Just a change in the code path is not an issue, but
8180 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008181 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008182 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008183 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008184 }
8185 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008186 reportSettingsProblem(Log.WARN,
8187 "Package " + name + " shared user changed from "
8188 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8189 + " to "
8190 + (sharedUser != null ? sharedUser.name : "<nothing>")
8191 + "; replacing with new");
8192 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008193 } else {
8194 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8195 // If what we are scanning is a system package, then
8196 // make it so, regardless of whether it was previously
8197 // installed only in the data partition.
8198 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008200 }
8201 }
8202 if (p == null) {
8203 // Create a new PackageSettings entry. this can end up here because
8204 // of code path mismatch or user id mismatch of an updated system partition
8205 if (!create) {
8206 return null;
8207 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008208 if (origPackage != null) {
8209 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008210 p = new PackageSetting(origPackage.name, name, codePath,
8211 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008212 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8213 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008214 // Note that we will retain the new package's signature so
8215 // that we can keep its data.
8216 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008217 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008218 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008219 p.sharedUser = origPackage.sharedUser;
8220 p.userId = origPackage.userId;
8221 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008222 mRenamedPackages.put(name, origPackage.name);
8223 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008224 // Update new package state.
8225 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008226 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008227 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008228 p.setTimeStamp(codePath.lastModified());
8229 p.sharedUser = sharedUser;
8230 if (sharedUser != null) {
8231 p.userId = sharedUser.userId;
8232 } else if (MULTIPLE_APPLICATION_UIDS) {
8233 // Clone the setting here for disabled system packages
8234 PackageSetting dis = mDisabledSysPackages.get(name);
8235 if (dis != null) {
8236 // For disabled packages a new setting is created
8237 // from the existing user id. This still has to be
8238 // added to list of user id's
8239 // Copy signatures from previous setting
8240 if (dis.signatures.mSignatures != null) {
8241 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8242 }
8243 p.userId = dis.userId;
8244 // Clone permissions
8245 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008246 // Clone component info
8247 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8248 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8249 // Add new setting to list of user ids
8250 addUserIdLP(p.userId, p, name);
8251 } else {
8252 // Assign new user id
8253 p.userId = newUserIdLP(p);
8254 }
8255 } else {
8256 p.userId = FIRST_APPLICATION_UID;
8257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008258 }
8259 if (p.userId < 0) {
8260 reportSettingsProblem(Log.WARN,
8261 "Package " + name + " could not be assigned a valid uid");
8262 return null;
8263 }
8264 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008265 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008266 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008267 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008268 }
8269 }
8270 return p;
8271 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008272
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008273 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008274 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008275 pkg.mSetEnabled = p.enabled;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008276 String codePath = pkg.applicationInfo.sourceDir;
8277 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008278 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008279 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008280 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008281 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008282 p.codePath = new File(codePath);
8283 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008284 }
8285 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008286 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008287 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008288 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008289 p.resourcePath = new File(resourcePath);
8290 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008291 }
8292 // Update version code if needed
8293 if (pkg.mVersionCode != p.versionCode) {
8294 p.versionCode = pkg.mVersionCode;
8295 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008296 // Update signatures if needed.
8297 if (p.signatures.mSignatures == null) {
8298 p.signatures.assignSignatures(pkg.mSignatures);
8299 }
8300 // If this app defines a shared user id initialize
8301 // the shared user signatures as well.
8302 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8303 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8304 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008305 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8306 }
8307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008308 // Utility method that adds a PackageSetting to mPackages and
8309 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008310 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008311 SharedUserSetting sharedUser) {
8312 mPackages.put(name, p);
8313 if (sharedUser != null) {
8314 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8315 reportSettingsProblem(Log.ERROR,
8316 "Package " + p.name + " was user "
8317 + p.sharedUser + " but is now " + sharedUser
8318 + "; I am not changing its files so it will probably fail!");
8319 p.sharedUser.packages.remove(p);
8320 } else if (p.userId != sharedUser.userId) {
8321 reportSettingsProblem(Log.ERROR,
8322 "Package " + p.name + " was user id " + p.userId
8323 + " but is now user " + sharedUser
8324 + " with id " + sharedUser.userId
8325 + "; I am not changing its files so it will probably fail!");
8326 }
8327
8328 sharedUser.packages.add(p);
8329 p.sharedUser = sharedUser;
8330 p.userId = sharedUser.userId;
8331 }
8332 }
8333
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008334 /*
8335 * Update the shared user setting when a package using
8336 * specifying the shared user id is removed. The gids
8337 * associated with each permission of the deleted package
8338 * are removed from the shared user's gid list only if its
8339 * not in use by other permissions of packages in the
8340 * shared user setting.
8341 */
8342 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008343 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008344 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008345 return;
8346 }
8347 // No sharedUserId
8348 if (deletedPs.sharedUser == null) {
8349 return;
8350 }
8351 SharedUserSetting sus = deletedPs.sharedUser;
8352 // Update permissions
8353 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8354 boolean used = false;
8355 if (!sus.grantedPermissions.contains (eachPerm)) {
8356 continue;
8357 }
8358 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008359 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008360 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008361 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008362 used = true;
8363 break;
8364 }
8365 }
8366 if (!used) {
8367 // can safely delete this permission from list
8368 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008369 }
8370 }
8371 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008372 int newGids[] = globalGids;
8373 for (String eachPerm : sus.grantedPermissions) {
8374 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008375 if (bp != null) {
8376 newGids = appendInts(newGids, bp.gids);
8377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008378 }
8379 sus.gids = newGids;
8380 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008382 private int removePackageLP(String name) {
8383 PackageSetting p = mPackages.get(name);
8384 if (p != null) {
8385 mPackages.remove(name);
8386 if (p.sharedUser != null) {
8387 p.sharedUser.packages.remove(p);
8388 if (p.sharedUser.packages.size() == 0) {
8389 mSharedUsers.remove(p.sharedUser.name);
8390 removeUserIdLP(p.sharedUser.userId);
8391 return p.sharedUser.userId;
8392 }
8393 } else {
8394 removeUserIdLP(p.userId);
8395 return p.userId;
8396 }
8397 }
8398 return -1;
8399 }
8400
8401 private boolean addUserIdLP(int uid, Object obj, Object name) {
8402 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8403 return false;
8404 }
8405
8406 if (uid >= FIRST_APPLICATION_UID) {
8407 int N = mUserIds.size();
8408 final int index = uid - FIRST_APPLICATION_UID;
8409 while (index >= N) {
8410 mUserIds.add(null);
8411 N++;
8412 }
8413 if (mUserIds.get(index) != null) {
8414 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008415 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008416 + " name=" + name);
8417 return false;
8418 }
8419 mUserIds.set(index, obj);
8420 } else {
8421 if (mOtherUserIds.get(uid) != null) {
8422 reportSettingsProblem(Log.ERROR,
8423 "Adding duplicate shared id: " + uid
8424 + " name=" + name);
8425 return false;
8426 }
8427 mOtherUserIds.put(uid, obj);
8428 }
8429 return true;
8430 }
8431
8432 public Object getUserIdLP(int uid) {
8433 if (uid >= FIRST_APPLICATION_UID) {
8434 int N = mUserIds.size();
8435 final int index = uid - FIRST_APPLICATION_UID;
8436 return index < N ? mUserIds.get(index) : null;
8437 } else {
8438 return mOtherUserIds.get(uid);
8439 }
8440 }
8441
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008442 private Set<String> findPackagesWithFlag(int flag) {
8443 Set<String> ret = new HashSet<String>();
8444 for (PackageSetting ps : mPackages.values()) {
8445 // Has to match atleast all the flag bits set on flag
8446 if ((ps.pkgFlags & flag) == flag) {
8447 ret.add(ps.name);
8448 }
8449 }
8450 return ret;
8451 }
8452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008453 private void removeUserIdLP(int uid) {
8454 if (uid >= FIRST_APPLICATION_UID) {
8455 int N = mUserIds.size();
8456 final int index = uid - FIRST_APPLICATION_UID;
8457 if (index < N) mUserIds.set(index, null);
8458 } else {
8459 mOtherUserIds.remove(uid);
8460 }
8461 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008463 void writeLP() {
8464 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8465
8466 // Keep the old settings around until we know the new ones have
8467 // been successfully written.
8468 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008469 // Presence of backup settings file indicates that we failed
8470 // to persist settings earlier. So preserve the older
8471 // backup for future reference since the current settings
8472 // might have been corrupted.
8473 if (!mBackupSettingsFilename.exists()) {
8474 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008475 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008476 return;
8477 }
8478 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008479 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008480 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008482 }
8483
8484 mPastSignatures.clear();
8485
8486 try {
8487 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8488
8489 //XmlSerializer serializer = XmlUtils.serializerInstance();
8490 XmlSerializer serializer = new FastXmlSerializer();
8491 serializer.setOutput(str, "utf-8");
8492 serializer.startDocument(null, true);
8493 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8494
8495 serializer.startTag(null, "packages");
8496
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008497 serializer.startTag(null, "last-platform-version");
8498 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8499 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8500 serializer.endTag(null, "last-platform-version");
8501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008502 serializer.startTag(null, "permission-trees");
8503 for (BasePermission bp : mPermissionTrees.values()) {
8504 writePermission(serializer, bp);
8505 }
8506 serializer.endTag(null, "permission-trees");
8507
8508 serializer.startTag(null, "permissions");
8509 for (BasePermission bp : mPermissions.values()) {
8510 writePermission(serializer, bp);
8511 }
8512 serializer.endTag(null, "permissions");
8513
8514 for (PackageSetting pkg : mPackages.values()) {
8515 writePackage(serializer, pkg);
8516 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008518 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8519 writeDisabledSysPackage(serializer, pkg);
8520 }
8521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008522 serializer.startTag(null, "preferred-activities");
8523 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8524 serializer.startTag(null, "item");
8525 pa.writeToXml(serializer);
8526 serializer.endTag(null, "item");
8527 }
8528 serializer.endTag(null, "preferred-activities");
8529
8530 for (SharedUserSetting usr : mSharedUsers.values()) {
8531 serializer.startTag(null, "shared-user");
8532 serializer.attribute(null, "name", usr.name);
8533 serializer.attribute(null, "userId",
8534 Integer.toString(usr.userId));
8535 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8536 serializer.startTag(null, "perms");
8537 for (String name : usr.grantedPermissions) {
8538 serializer.startTag(null, "item");
8539 serializer.attribute(null, "name", name);
8540 serializer.endTag(null, "item");
8541 }
8542 serializer.endTag(null, "perms");
8543 serializer.endTag(null, "shared-user");
8544 }
8545
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008546 if (mPackagesToBeCleaned.size() > 0) {
8547 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8548 serializer.startTag(null, "cleaning-package");
8549 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8550 serializer.endTag(null, "cleaning-package");
8551 }
8552 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008553
8554 if (mRenamedPackages.size() > 0) {
8555 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8556 serializer.startTag(null, "renamed-package");
8557 serializer.attribute(null, "new", e.getKey());
8558 serializer.attribute(null, "old", e.getValue());
8559 serializer.endTag(null, "renamed-package");
8560 }
8561 }
8562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008563 serializer.endTag(null, "packages");
8564
8565 serializer.endDocument();
8566
8567 str.flush();
8568 str.close();
8569
8570 // New settings successfully written, old ones are no longer
8571 // needed.
8572 mBackupSettingsFilename.delete();
8573 FileUtils.setPermissions(mSettingsFilename.toString(),
8574 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8575 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8576 |FileUtils.S_IROTH,
8577 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008578
8579 // Write package list file now, use a JournaledFile.
8580 //
8581 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8582 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8583
8584 str = new FileOutputStream(journal.chooseForWrite());
8585 try {
8586 StringBuilder sb = new StringBuilder();
8587 for (PackageSetting pkg : mPackages.values()) {
8588 ApplicationInfo ai = pkg.pkg.applicationInfo;
8589 String dataPath = ai.dataDir;
8590 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8591
8592 // Avoid any application that has a space in its path
8593 // or that is handled by the system.
8594 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8595 continue;
8596
8597 // we store on each line the following information for now:
8598 //
8599 // pkgName - package name
8600 // userId - application-specific user id
8601 // debugFlag - 0 or 1 if the package is debuggable.
8602 // dataPath - path to package's data path
8603 //
8604 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8605 //
8606 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8607 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8608 // system/core/run-as/run-as.c
8609 //
8610 sb.setLength(0);
8611 sb.append(ai.packageName);
8612 sb.append(" ");
8613 sb.append((int)ai.uid);
8614 sb.append(isDebug ? " 1 " : " 0 ");
8615 sb.append(dataPath);
8616 sb.append("\n");
8617 str.write(sb.toString().getBytes());
8618 }
8619 str.flush();
8620 str.close();
8621 journal.commit();
8622 }
8623 catch (Exception e) {
8624 journal.rollback();
8625 }
8626
8627 FileUtils.setPermissions(mPackageListFilename.toString(),
8628 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8629 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8630 |FileUtils.S_IROTH,
8631 -1, -1);
8632
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008633 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008634
8635 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008636 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 -08008637 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008638 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 -08008639 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008640 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008641 if (mSettingsFilename.exists()) {
8642 if (!mSettingsFilename.delete()) {
8643 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8644 }
8645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008646 //Debug.stopMethodTracing();
8647 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008648
8649 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008650 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008651 serializer.startTag(null, "updated-package");
8652 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008653 if (pkg.realName != null) {
8654 serializer.attribute(null, "realName", pkg.realName);
8655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008656 serializer.attribute(null, "codePath", pkg.codePathString);
8657 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008658 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008659 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8660 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8661 }
8662 if (pkg.sharedUser == null) {
8663 serializer.attribute(null, "userId",
8664 Integer.toString(pkg.userId));
8665 } else {
8666 serializer.attribute(null, "sharedUserId",
8667 Integer.toString(pkg.userId));
8668 }
8669 serializer.startTag(null, "perms");
8670 if (pkg.sharedUser == null) {
8671 // If this is a shared user, the permissions will
8672 // be written there. We still need to write an
8673 // empty permissions list so permissionsFixed will
8674 // be set.
8675 for (final String name : pkg.grantedPermissions) {
8676 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008677 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008678 // We only need to write signature or system permissions but this wont
8679 // match the semantics of grantedPermissions. So write all permissions.
8680 serializer.startTag(null, "item");
8681 serializer.attribute(null, "name", name);
8682 serializer.endTag(null, "item");
8683 }
8684 }
8685 }
8686 serializer.endTag(null, "perms");
8687 serializer.endTag(null, "updated-package");
8688 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008689
8690 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008691 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008692 serializer.startTag(null, "package");
8693 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008694 if (pkg.realName != null) {
8695 serializer.attribute(null, "realName", pkg.realName);
8696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008697 serializer.attribute(null, "codePath", pkg.codePathString);
8698 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8699 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8700 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008701 serializer.attribute(null, "flags",
8702 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008703 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008704 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008705 if (pkg.sharedUser == null) {
8706 serializer.attribute(null, "userId",
8707 Integer.toString(pkg.userId));
8708 } else {
8709 serializer.attribute(null, "sharedUserId",
8710 Integer.toString(pkg.userId));
8711 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008712 if (pkg.uidError) {
8713 serializer.attribute(null, "uidError", "true");
8714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008715 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8716 serializer.attribute(null, "enabled",
8717 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8718 ? "true" : "false");
8719 }
8720 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8721 serializer.attribute(null, "installStatus", "false");
8722 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008723 if (pkg.installerPackageName != null) {
8724 serializer.attribute(null, "installer", pkg.installerPackageName);
8725 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008726 if (pkg.obbPathString != null) {
8727 serializer.attribute(null, "obbPath", pkg.obbPathString);
8728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008729 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8730 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8731 serializer.startTag(null, "perms");
8732 if (pkg.sharedUser == null) {
8733 // If this is a shared user, the permissions will
8734 // be written there. We still need to write an
8735 // empty permissions list so permissionsFixed will
8736 // be set.
8737 for (final String name : pkg.grantedPermissions) {
8738 serializer.startTag(null, "item");
8739 serializer.attribute(null, "name", name);
8740 serializer.endTag(null, "item");
8741 }
8742 }
8743 serializer.endTag(null, "perms");
8744 }
8745 if (pkg.disabledComponents.size() > 0) {
8746 serializer.startTag(null, "disabled-components");
8747 for (final String name : pkg.disabledComponents) {
8748 serializer.startTag(null, "item");
8749 serializer.attribute(null, "name", name);
8750 serializer.endTag(null, "item");
8751 }
8752 serializer.endTag(null, "disabled-components");
8753 }
8754 if (pkg.enabledComponents.size() > 0) {
8755 serializer.startTag(null, "enabled-components");
8756 for (final String name : pkg.enabledComponents) {
8757 serializer.startTag(null, "item");
8758 serializer.attribute(null, "name", name);
8759 serializer.endTag(null, "item");
8760 }
8761 serializer.endTag(null, "enabled-components");
8762 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008764 serializer.endTag(null, "package");
8765 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008767 void writePermission(XmlSerializer serializer, BasePermission bp)
8768 throws XmlPullParserException, java.io.IOException {
8769 if (bp.type != BasePermission.TYPE_BUILTIN
8770 && bp.sourcePackage != null) {
8771 serializer.startTag(null, "item");
8772 serializer.attribute(null, "name", bp.name);
8773 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008774 if (bp.protectionLevel !=
8775 PermissionInfo.PROTECTION_NORMAL) {
8776 serializer.attribute(null, "protection",
8777 Integer.toString(bp.protectionLevel));
8778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008779 if (DEBUG_SETTINGS) Log.v(TAG,
8780 "Writing perm: name=" + bp.name + " type=" + bp.type);
8781 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8782 PermissionInfo pi = bp.perm != null ? bp.perm.info
8783 : bp.pendingInfo;
8784 if (pi != null) {
8785 serializer.attribute(null, "type", "dynamic");
8786 if (pi.icon != 0) {
8787 serializer.attribute(null, "icon",
8788 Integer.toString(pi.icon));
8789 }
8790 if (pi.nonLocalizedLabel != null) {
8791 serializer.attribute(null, "label",
8792 pi.nonLocalizedLabel.toString());
8793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008794 }
8795 }
8796 serializer.endTag(null, "item");
8797 }
8798 }
8799
8800 String getReadMessagesLP() {
8801 return mReadMessages.toString();
8802 }
8803
Oscar Montemayora8529f62009-11-18 10:14:20 -08008804 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008805 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8806 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008807 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008808 while(its.hasNext()) {
8809 String key = its.next();
8810 PackageSetting ps = mPackages.get(key);
8811 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008812 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008813 }
8814 }
8815 return ret;
8816 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008818 boolean readLP() {
8819 FileInputStream str = null;
8820 if (mBackupSettingsFilename.exists()) {
8821 try {
8822 str = new FileInputStream(mBackupSettingsFilename);
8823 mReadMessages.append("Reading from backup settings file\n");
8824 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008825 if (mSettingsFilename.exists()) {
8826 // If both the backup and settings file exist, we
8827 // ignore the settings since it might have been
8828 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008829 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008830 mSettingsFilename.delete();
8831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008832 } catch (java.io.IOException e) {
8833 // We'll try for the normal settings file.
8834 }
8835 }
8836
8837 mPastSignatures.clear();
8838
8839 try {
8840 if (str == null) {
8841 if (!mSettingsFilename.exists()) {
8842 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008843 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008844 return false;
8845 }
8846 str = new FileInputStream(mSettingsFilename);
8847 }
8848 XmlPullParser parser = Xml.newPullParser();
8849 parser.setInput(str, null);
8850
8851 int type;
8852 while ((type=parser.next()) != XmlPullParser.START_TAG
8853 && type != XmlPullParser.END_DOCUMENT) {
8854 ;
8855 }
8856
8857 if (type != XmlPullParser.START_TAG) {
8858 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008859 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008860 return false;
8861 }
8862
8863 int outerDepth = parser.getDepth();
8864 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8865 && (type != XmlPullParser.END_TAG
8866 || parser.getDepth() > outerDepth)) {
8867 if (type == XmlPullParser.END_TAG
8868 || type == XmlPullParser.TEXT) {
8869 continue;
8870 }
8871
8872 String tagName = parser.getName();
8873 if (tagName.equals("package")) {
8874 readPackageLP(parser);
8875 } else if (tagName.equals("permissions")) {
8876 readPermissionsLP(mPermissions, parser);
8877 } else if (tagName.equals("permission-trees")) {
8878 readPermissionsLP(mPermissionTrees, parser);
8879 } else if (tagName.equals("shared-user")) {
8880 readSharedUserLP(parser);
8881 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008882 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008883 } else if (tagName.equals("preferred-activities")) {
8884 readPreferredActivitiesLP(parser);
8885 } else if(tagName.equals("updated-package")) {
8886 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008887 } else if (tagName.equals("cleaning-package")) {
8888 String name = parser.getAttributeValue(null, "name");
8889 if (name != null) {
8890 mPackagesToBeCleaned.add(name);
8891 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008892 } else if (tagName.equals("renamed-package")) {
8893 String nname = parser.getAttributeValue(null, "new");
8894 String oname = parser.getAttributeValue(null, "old");
8895 if (nname != null && oname != null) {
8896 mRenamedPackages.put(nname, oname);
8897 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008898 } else if (tagName.equals("last-platform-version")) {
8899 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8900 try {
8901 String internal = parser.getAttributeValue(null, "internal");
8902 if (internal != null) {
8903 mInternalSdkPlatform = Integer.parseInt(internal);
8904 }
8905 String external = parser.getAttributeValue(null, "external");
8906 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008907 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008908 }
8909 } catch (NumberFormatException e) {
8910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008911 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008912 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008913 + parser.getName());
8914 XmlUtils.skipCurrentTag(parser);
8915 }
8916 }
8917
8918 str.close();
8919
8920 } catch(XmlPullParserException e) {
8921 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008922 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008923
8924 } catch(java.io.IOException e) {
8925 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008926 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008927
8928 }
8929
8930 int N = mPendingPackages.size();
8931 for (int i=0; i<N; i++) {
8932 final PendingPackage pp = mPendingPackages.get(i);
8933 Object idObj = getUserIdLP(pp.sharedId);
8934 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008935 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008936 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008937 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008938 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008939 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008940 + pp.name);
8941 continue;
8942 }
8943 p.copyFrom(pp);
8944 } else if (idObj != null) {
8945 String msg = "Bad package setting: package " + pp.name
8946 + " has shared uid " + pp.sharedId
8947 + " that is not a shared uid\n";
8948 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008949 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008950 } else {
8951 String msg = "Bad package setting: package " + pp.name
8952 + " has shared uid " + pp.sharedId
8953 + " that is not defined\n";
8954 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008955 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008956 }
8957 }
8958 mPendingPackages.clear();
8959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008960 mReadMessages.append("Read completed successfully: "
8961 + mPackages.size() + " packages, "
8962 + mSharedUsers.size() + " shared uids\n");
8963
8964 return true;
8965 }
8966
8967 private int readInt(XmlPullParser parser, String ns, String name,
8968 int defValue) {
8969 String v = parser.getAttributeValue(ns, name);
8970 try {
8971 if (v == null) {
8972 return defValue;
8973 }
8974 return Integer.parseInt(v);
8975 } catch (NumberFormatException e) {
8976 reportSettingsProblem(Log.WARN,
8977 "Error in package manager settings: attribute " +
8978 name + " has bad integer value " + v + " at "
8979 + parser.getPositionDescription());
8980 }
8981 return defValue;
8982 }
8983
8984 private void readPermissionsLP(HashMap<String, BasePermission> out,
8985 XmlPullParser parser)
8986 throws IOException, XmlPullParserException {
8987 int outerDepth = parser.getDepth();
8988 int type;
8989 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8990 && (type != XmlPullParser.END_TAG
8991 || parser.getDepth() > outerDepth)) {
8992 if (type == XmlPullParser.END_TAG
8993 || type == XmlPullParser.TEXT) {
8994 continue;
8995 }
8996
8997 String tagName = parser.getName();
8998 if (tagName.equals("item")) {
8999 String name = parser.getAttributeValue(null, "name");
9000 String sourcePackage = parser.getAttributeValue(null, "package");
9001 String ptype = parser.getAttributeValue(null, "type");
9002 if (name != null && sourcePackage != null) {
9003 boolean dynamic = "dynamic".equals(ptype);
9004 BasePermission bp = new BasePermission(name, sourcePackage,
9005 dynamic
9006 ? BasePermission.TYPE_DYNAMIC
9007 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009008 bp.protectionLevel = readInt(parser, null, "protection",
9009 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009010 if (dynamic) {
9011 PermissionInfo pi = new PermissionInfo();
9012 pi.packageName = sourcePackage.intern();
9013 pi.name = name.intern();
9014 pi.icon = readInt(parser, null, "icon", 0);
9015 pi.nonLocalizedLabel = parser.getAttributeValue(
9016 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009017 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009018 bp.pendingInfo = pi;
9019 }
9020 out.put(bp.name, bp);
9021 } else {
9022 reportSettingsProblem(Log.WARN,
9023 "Error in package manager settings: permissions has"
9024 + " no name at " + parser.getPositionDescription());
9025 }
9026 } else {
9027 reportSettingsProblem(Log.WARN,
9028 "Unknown element reading permissions: "
9029 + parser.getName() + " at "
9030 + parser.getPositionDescription());
9031 }
9032 XmlUtils.skipCurrentTag(parser);
9033 }
9034 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009036 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009037 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009038 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009039 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009040 String codePathStr = parser.getAttributeValue(null, "codePath");
9041 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009042 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009043 resourcePathStr = codePathStr;
9044 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009045 String version = parser.getAttributeValue(null, "version");
9046 int versionCode = 0;
9047 if (version != null) {
9048 try {
9049 versionCode = Integer.parseInt(version);
9050 } catch (NumberFormatException e) {
9051 }
9052 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009054 int pkgFlags = 0;
9055 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009056 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009057 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009058 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009059 String timeStampStr = parser.getAttributeValue(null, "ts");
9060 if (timeStampStr != null) {
9061 try {
9062 long timeStamp = Long.parseLong(timeStampStr);
9063 ps.setTimeStamp(timeStamp, timeStampStr);
9064 } catch (NumberFormatException e) {
9065 }
9066 }
9067 String idStr = parser.getAttributeValue(null, "userId");
9068 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
9069 if(ps.userId <= 0) {
9070 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9071 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
9072 }
9073 int outerDepth = parser.getDepth();
9074 int type;
9075 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9076 && (type != XmlPullParser.END_TAG
9077 || parser.getDepth() > outerDepth)) {
9078 if (type == XmlPullParser.END_TAG
9079 || type == XmlPullParser.TEXT) {
9080 continue;
9081 }
9082
9083 String tagName = parser.getName();
9084 if (tagName.equals("perms")) {
9085 readGrantedPermissionsLP(parser,
9086 ps.grantedPermissions);
9087 } else {
9088 reportSettingsProblem(Log.WARN,
9089 "Unknown element under <updated-package>: "
9090 + parser.getName());
9091 XmlUtils.skipCurrentTag(parser);
9092 }
9093 }
9094 mDisabledSysPackages.put(name, ps);
9095 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009097 private void readPackageLP(XmlPullParser parser)
9098 throws XmlPullParserException, IOException {
9099 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009100 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009101 String idStr = null;
9102 String sharedIdStr = null;
9103 String codePathStr = null;
9104 String resourcePathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07009105 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009106 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009107 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009108 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009109 int pkgFlags = 0;
9110 String timeStampStr;
9111 long timeStamp = 0;
9112 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009113 String version = null;
9114 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009115 try {
9116 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009117 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009118 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009119 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009120 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9121 codePathStr = parser.getAttributeValue(null, "codePath");
9122 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root93565c4b2010-06-18 15:46:06 -07009123 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009124 version = parser.getAttributeValue(null, "version");
9125 if (version != null) {
9126 try {
9127 versionCode = Integer.parseInt(version);
9128 } catch (NumberFormatException e) {
9129 }
9130 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009131 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009132
9133 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009134 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009135 try {
9136 pkgFlags = Integer.parseInt(systemStr);
9137 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009138 }
9139 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009140 // For backward compatibility
9141 systemStr = parser.getAttributeValue(null, "system");
9142 if (systemStr != null) {
9143 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9144 } else {
9145 // Old settings that don't specify system... just treat
9146 // them as system, good enough.
9147 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009149 }
9150 timeStampStr = parser.getAttributeValue(null, "ts");
9151 if (timeStampStr != null) {
9152 try {
9153 timeStamp = Long.parseLong(timeStampStr);
9154 } catch (NumberFormatException e) {
9155 }
9156 }
9157 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9158 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9159 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9160 if (resourcePathStr == null) {
9161 resourcePathStr = codePathStr;
9162 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009163 if (realName != null) {
9164 realName = realName.intern();
9165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009166 if (name == null) {
9167 reportSettingsProblem(Log.WARN,
9168 "Error in package manager settings: <package> has no name at "
9169 + parser.getPositionDescription());
9170 } else if (codePathStr == null) {
9171 reportSettingsProblem(Log.WARN,
9172 "Error in package manager settings: <package> has no codePath at "
9173 + parser.getPositionDescription());
9174 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009175 packageSetting = addPackageLP(name.intern(), realName,
9176 new File(codePathStr), new File(resourcePathStr),
9177 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009178 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9179 + ": userId=" + userId + " pkg=" + packageSetting);
9180 if (packageSetting == null) {
9181 reportSettingsProblem(Log.ERROR,
9182 "Failure adding uid " + userId
9183 + " while parsing settings at "
9184 + parser.getPositionDescription());
9185 } else {
9186 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9187 }
9188 } else if (sharedIdStr != null) {
9189 userId = sharedIdStr != null
9190 ? Integer.parseInt(sharedIdStr) : 0;
9191 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009192 packageSetting = new PendingPackage(name.intern(), realName,
9193 new File(codePathStr), new File(resourcePathStr),
9194 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009195 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9196 mPendingPackages.add((PendingPackage) packageSetting);
9197 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9198 + ": sharedUserId=" + userId + " pkg="
9199 + packageSetting);
9200 } else {
9201 reportSettingsProblem(Log.WARN,
9202 "Error in package manager settings: package "
9203 + name + " has bad sharedId " + sharedIdStr
9204 + " at " + parser.getPositionDescription());
9205 }
9206 } else {
9207 reportSettingsProblem(Log.WARN,
9208 "Error in package manager settings: package "
9209 + name + " has bad userId " + idStr + " at "
9210 + parser.getPositionDescription());
9211 }
9212 } catch (NumberFormatException e) {
9213 reportSettingsProblem(Log.WARN,
9214 "Error in package manager settings: package "
9215 + name + " has bad userId " + idStr + " at "
9216 + parser.getPositionDescription());
9217 }
9218 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009219 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009220 packageSetting.installerPackageName = installerPackageName;
Kenny Root93565c4b2010-06-18 15:46:06 -07009221 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009222 final String enabledStr = parser.getAttributeValue(null, "enabled");
9223 if (enabledStr != null) {
9224 if (enabledStr.equalsIgnoreCase("true")) {
9225 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9226 } else if (enabledStr.equalsIgnoreCase("false")) {
9227 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9228 } else if (enabledStr.equalsIgnoreCase("default")) {
9229 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9230 } else {
9231 reportSettingsProblem(Log.WARN,
9232 "Error in package manager settings: package "
9233 + name + " has bad enabled value: " + idStr
9234 + " at " + parser.getPositionDescription());
9235 }
9236 } else {
9237 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9238 }
9239 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9240 if (installStatusStr != null) {
9241 if (installStatusStr.equalsIgnoreCase("false")) {
9242 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9243 } else {
9244 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9245 }
9246 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009248 int outerDepth = parser.getDepth();
9249 int type;
9250 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9251 && (type != XmlPullParser.END_TAG
9252 || parser.getDepth() > outerDepth)) {
9253 if (type == XmlPullParser.END_TAG
9254 || type == XmlPullParser.TEXT) {
9255 continue;
9256 }
9257
9258 String tagName = parser.getName();
9259 if (tagName.equals("disabled-components")) {
9260 readDisabledComponentsLP(packageSetting, parser);
9261 } else if (tagName.equals("enabled-components")) {
9262 readEnabledComponentsLP(packageSetting, parser);
9263 } else if (tagName.equals("sigs")) {
9264 packageSetting.signatures.readXml(parser, mPastSignatures);
9265 } else if (tagName.equals("perms")) {
9266 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009267 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009268 packageSetting.permissionsFixed = true;
9269 } else {
9270 reportSettingsProblem(Log.WARN,
9271 "Unknown element under <package>: "
9272 + parser.getName());
9273 XmlUtils.skipCurrentTag(parser);
9274 }
9275 }
9276 } else {
9277 XmlUtils.skipCurrentTag(parser);
9278 }
9279 }
9280
9281 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9282 XmlPullParser parser)
9283 throws IOException, XmlPullParserException {
9284 int outerDepth = parser.getDepth();
9285 int type;
9286 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9287 && (type != XmlPullParser.END_TAG
9288 || parser.getDepth() > outerDepth)) {
9289 if (type == XmlPullParser.END_TAG
9290 || type == XmlPullParser.TEXT) {
9291 continue;
9292 }
9293
9294 String tagName = parser.getName();
9295 if (tagName.equals("item")) {
9296 String name = parser.getAttributeValue(null, "name");
9297 if (name != null) {
9298 packageSetting.disabledComponents.add(name.intern());
9299 } else {
9300 reportSettingsProblem(Log.WARN,
9301 "Error in package manager settings: <disabled-components> has"
9302 + " no name at " + parser.getPositionDescription());
9303 }
9304 } else {
9305 reportSettingsProblem(Log.WARN,
9306 "Unknown element under <disabled-components>: "
9307 + parser.getName());
9308 }
9309 XmlUtils.skipCurrentTag(parser);
9310 }
9311 }
9312
9313 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9314 XmlPullParser parser)
9315 throws IOException, XmlPullParserException {
9316 int outerDepth = parser.getDepth();
9317 int type;
9318 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9319 && (type != XmlPullParser.END_TAG
9320 || parser.getDepth() > outerDepth)) {
9321 if (type == XmlPullParser.END_TAG
9322 || type == XmlPullParser.TEXT) {
9323 continue;
9324 }
9325
9326 String tagName = parser.getName();
9327 if (tagName.equals("item")) {
9328 String name = parser.getAttributeValue(null, "name");
9329 if (name != null) {
9330 packageSetting.enabledComponents.add(name.intern());
9331 } else {
9332 reportSettingsProblem(Log.WARN,
9333 "Error in package manager settings: <enabled-components> has"
9334 + " no name at " + parser.getPositionDescription());
9335 }
9336 } else {
9337 reportSettingsProblem(Log.WARN,
9338 "Unknown element under <enabled-components>: "
9339 + parser.getName());
9340 }
9341 XmlUtils.skipCurrentTag(parser);
9342 }
9343 }
9344
9345 private void readSharedUserLP(XmlPullParser parser)
9346 throws XmlPullParserException, IOException {
9347 String name = null;
9348 String idStr = null;
9349 int pkgFlags = 0;
9350 SharedUserSetting su = null;
9351 try {
9352 name = parser.getAttributeValue(null, "name");
9353 idStr = parser.getAttributeValue(null, "userId");
9354 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9355 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9356 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9357 }
9358 if (name == null) {
9359 reportSettingsProblem(Log.WARN,
9360 "Error in package manager settings: <shared-user> has no name at "
9361 + parser.getPositionDescription());
9362 } else if (userId == 0) {
9363 reportSettingsProblem(Log.WARN,
9364 "Error in package manager settings: shared-user "
9365 + name + " has bad userId " + idStr + " at "
9366 + parser.getPositionDescription());
9367 } else {
9368 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9369 reportSettingsProblem(Log.ERROR,
9370 "Occurred while parsing settings at "
9371 + parser.getPositionDescription());
9372 }
9373 }
9374 } catch (NumberFormatException e) {
9375 reportSettingsProblem(Log.WARN,
9376 "Error in package manager settings: package "
9377 + name + " has bad userId " + idStr + " at "
9378 + parser.getPositionDescription());
9379 };
9380
9381 if (su != null) {
9382 int outerDepth = parser.getDepth();
9383 int type;
9384 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9385 && (type != XmlPullParser.END_TAG
9386 || parser.getDepth() > outerDepth)) {
9387 if (type == XmlPullParser.END_TAG
9388 || type == XmlPullParser.TEXT) {
9389 continue;
9390 }
9391
9392 String tagName = parser.getName();
9393 if (tagName.equals("sigs")) {
9394 su.signatures.readXml(parser, mPastSignatures);
9395 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009396 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009397 } else {
9398 reportSettingsProblem(Log.WARN,
9399 "Unknown element under <shared-user>: "
9400 + parser.getName());
9401 XmlUtils.skipCurrentTag(parser);
9402 }
9403 }
9404
9405 } else {
9406 XmlUtils.skipCurrentTag(parser);
9407 }
9408 }
9409
9410 private void readGrantedPermissionsLP(XmlPullParser parser,
9411 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9412 int outerDepth = parser.getDepth();
9413 int type;
9414 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9415 && (type != XmlPullParser.END_TAG
9416 || parser.getDepth() > outerDepth)) {
9417 if (type == XmlPullParser.END_TAG
9418 || type == XmlPullParser.TEXT) {
9419 continue;
9420 }
9421
9422 String tagName = parser.getName();
9423 if (tagName.equals("item")) {
9424 String name = parser.getAttributeValue(null, "name");
9425 if (name != null) {
9426 outPerms.add(name.intern());
9427 } else {
9428 reportSettingsProblem(Log.WARN,
9429 "Error in package manager settings: <perms> has"
9430 + " no name at " + parser.getPositionDescription());
9431 }
9432 } else {
9433 reportSettingsProblem(Log.WARN,
9434 "Unknown element under <perms>: "
9435 + parser.getName());
9436 }
9437 XmlUtils.skipCurrentTag(parser);
9438 }
9439 }
9440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009441 private void readPreferredActivitiesLP(XmlPullParser parser)
9442 throws XmlPullParserException, IOException {
9443 int outerDepth = parser.getDepth();
9444 int type;
9445 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9446 && (type != XmlPullParser.END_TAG
9447 || parser.getDepth() > outerDepth)) {
9448 if (type == XmlPullParser.END_TAG
9449 || type == XmlPullParser.TEXT) {
9450 continue;
9451 }
9452
9453 String tagName = parser.getName();
9454 if (tagName.equals("item")) {
9455 PreferredActivity pa = new PreferredActivity(parser);
9456 if (pa.mParseError == null) {
9457 mPreferredActivities.addFilter(pa);
9458 } else {
9459 reportSettingsProblem(Log.WARN,
9460 "Error in package manager settings: <preferred-activity> "
9461 + pa.mParseError + " at "
9462 + parser.getPositionDescription());
9463 }
9464 } else {
9465 reportSettingsProblem(Log.WARN,
9466 "Unknown element under <preferred-activities>: "
9467 + parser.getName());
9468 XmlUtils.skipCurrentTag(parser);
9469 }
9470 }
9471 }
9472
9473 // Returns -1 if we could not find an available UserId to assign
9474 private int newUserIdLP(Object obj) {
9475 // Let's be stupidly inefficient for now...
9476 final int N = mUserIds.size();
9477 for (int i=0; i<N; i++) {
9478 if (mUserIds.get(i) == null) {
9479 mUserIds.set(i, obj);
9480 return FIRST_APPLICATION_UID + i;
9481 }
9482 }
9483
9484 // None left?
9485 if (N >= MAX_APPLICATION_UIDS) {
9486 return -1;
9487 }
9488
9489 mUserIds.add(obj);
9490 return FIRST_APPLICATION_UID + N;
9491 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009493 public PackageSetting getDisabledSystemPkg(String name) {
9494 synchronized(mPackages) {
9495 PackageSetting ps = mDisabledSysPackages.get(name);
9496 return ps;
9497 }
9498 }
9499
9500 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009501 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9502 return true;
9503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009504 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9505 if (Config.LOGV) {
9506 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9507 + " componentName = " + componentInfo.name);
9508 Log.v(TAG, "enabledComponents: "
9509 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9510 Log.v(TAG, "disabledComponents: "
9511 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9512 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009513 if (packageSettings == null) {
9514 if (false) {
9515 Log.w(TAG, "WAITING FOR DEBUGGER");
9516 Debug.waitForDebugger();
9517 Log.i(TAG, "We will crash!");
9518 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009519 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009520 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009521 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9522 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9523 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9524 return false;
9525 }
9526 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9527 return true;
9528 }
9529 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9530 return false;
9531 }
9532 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009533 }
9534 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009535
9536 // ------- apps on sdcard specific code -------
9537 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009538 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009539 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009540 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009541 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009542
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009543 private String getEncryptKey() {
9544 try {
9545 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9546 if (sdEncKey == null) {
9547 sdEncKey = SystemKeyStore.getInstance().
9548 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9549 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009550 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009551 return null;
9552 }
9553 }
9554 return sdEncKey;
9555 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009556 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009557 return null;
9558 }
9559 }
9560
Kenny Rootc78a8072010-07-27 15:18:38 -07009561 /* package */ static String getTempContainerId() {
9562 int tmpIdx = 1;
9563 String list[] = PackageHelper.getSecureContainerList();
9564 if (list != null) {
9565 for (final String name : list) {
9566 // Ignore null and non-temporary container entries
9567 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9568 continue;
9569 }
9570
9571 String subStr = name.substring(mTempContainerPrefix.length());
9572 try {
9573 int cid = Integer.parseInt(subStr);
9574 if (cid >= tmpIdx) {
9575 tmpIdx = cid + 1;
9576 }
9577 } catch (NumberFormatException e) {
9578 }
9579 }
9580 }
9581 return mTempContainerPrefix + tmpIdx;
9582 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009583
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009584 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009585 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009586 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009587 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9588 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9589 throw new SecurityException("Media status can only be updated by the system");
9590 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009591 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009592 Log.i(TAG, "Updating external media status from " +
9593 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9594 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009595 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9596 mediaStatus+", mMediaMounted=" + mMediaMounted);
9597 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009598 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9599 reportStatus ? 1 : 0, -1);
9600 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009601 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009602 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009603 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009604 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009605 // Queue up an async operation since the package installation may take a little while.
9606 mHandler.post(new Runnable() {
9607 public void run() {
9608 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009609 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009610 }
9611 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009612 }
9613
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009614 /*
9615 * Collect information of applications on external media, map them
9616 * against existing containers and update information based on current
9617 * mount status. Please note that we always have to report status
9618 * if reportStatus has been set to true especially when unloading packages.
9619 */
9620 private void updateExternalMediaStatusInner(boolean mediaStatus,
9621 boolean reportStatus) {
9622 // Collection of uids
9623 int uidArr[] = null;
9624 // Collection of stale containers
9625 HashSet<String> removeCids = new HashSet<String>();
9626 // Collection of packages on external media with valid containers.
9627 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9628 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009629 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009630 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009631 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009632 } else {
9633 // Process list of secure containers and categorize them
9634 // as active or stale based on their package internal state.
9635 int uidList[] = new int[list.length];
9636 int num = 0;
9637 synchronized (mPackages) {
9638 for (String cid : list) {
9639 SdInstallArgs args = new SdInstallArgs(cid);
9640 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009641 String pkgName = args.getPackageName();
9642 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009643 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9644 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009645 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009646 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009647 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9648 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009649 // The package status is changed only if the code path
9650 // matches between settings and the container id.
9651 if (ps != null && ps.codePathString != null &&
9652 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009653 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9654 " corresponds to pkg : " + pkgName +
9655 " at code path: " + ps.codePathString);
9656 // We do have a valid package installed on sdcard
9657 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009658 int uid = ps.userId;
9659 if (uid != -1) {
9660 uidList[num++] = uid;
9661 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009662 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009663 // Stale container on sdcard. Just delete
9664 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9665 removeCids.add(cid);
9666 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009667 }
9668 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009669
9670 if (num > 0) {
9671 // Sort uid list
9672 Arrays.sort(uidList, 0, num);
9673 // Throw away duplicates
9674 uidArr = new int[num];
9675 uidArr[0] = uidList[0];
9676 int di = 0;
9677 for (int i = 1; i < num; i++) {
9678 if (uidList[i-1] != uidList[i]) {
9679 uidArr[di++] = uidList[i];
9680 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009681 }
9682 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009683 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009684 // Process packages with valid entries.
9685 if (mediaStatus) {
9686 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009687 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009688 startCleaningPackages();
9689 } else {
9690 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009691 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009692 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009693 }
9694
9695 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009696 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009697 int size = pkgList.size();
9698 if (size > 0) {
9699 // Send broadcasts here
9700 Bundle extras = new Bundle();
9701 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9702 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009703 if (uidArr != null) {
9704 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9705 }
9706 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9707 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009708 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009709 }
9710 }
9711
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009712 /*
9713 * Look at potentially valid container ids from processCids
9714 * If package information doesn't match the one on record
9715 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009716 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009717 */
9718 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009719 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009720 ArrayList<String> pkgList = new ArrayList<String>();
9721 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009722 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009723 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009724 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009725 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9726 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009727 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009728 try {
9729 // Make sure there are no container errors first.
9730 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9731 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009732 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009733 " when installing from sdcard");
9734 continue;
9735 }
9736 // Check code path here.
9737 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009738 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009739 " does not match one in settings " + codePath);
9740 continue;
9741 }
9742 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009743 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009744 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009745 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009746 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9747 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009748 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009749 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009750 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009751 retCode = PackageManager.INSTALL_SUCCEEDED;
9752 pkgList.add(pkg.packageName);
9753 // Post process args
9754 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9755 }
9756 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009757 Slog.i(TAG, "Failed to install pkg from " +
9758 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009759 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009760 }
9761
9762 } finally {
9763 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9764 // Don't destroy container here. Wait till gc clears things up.
9765 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009766 }
9767 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009768 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009769 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009770 // If the platform SDK has changed since the last time we booted,
9771 // we need to re-grant app permission to catch any new ones that
9772 // appear. This is really a hack, and means that apps can in some
9773 // cases get permissions that the user didn't initially explicitly
9774 // allow... it would be nice to have some better way to handle
9775 // this situation.
9776 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9777 != mSdkVersion;
9778 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9779 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9780 + "; regranting permissions for external storage");
9781 mSettings.mExternalSdkPlatform = mSdkVersion;
9782
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009783 // Make sure group IDs have been assigned, and any permission
9784 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009785 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009786 // Persist settings
9787 mSettings.writeLP();
9788 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009789 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009790 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009791 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009792 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009793 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009794 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009795 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009796 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009797 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009798 if (removeCids != null) {
9799 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009800 if (cid.startsWith(mTempContainerPrefix)) {
9801 Log.i(TAG, "Destroying stale temporary container " + cid);
9802 PackageHelper.destroySdDir(cid);
9803 } else {
9804 Log.w(TAG, "Container " + cid + " is stale");
9805 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009806 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009807 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009808 }
9809
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009810 /*
9811 * Utility method to unload a list of specified containers
9812 */
9813 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9814 // Just unmount all valid containers.
9815 for (SdInstallArgs arg : cidArgs) {
9816 synchronized (mInstallLock) {
9817 arg.doPostDeleteLI(false);
9818 }
9819 }
9820 }
9821
9822 /*
9823 * Unload packages mounted on external media. This involves deleting
9824 * package data from internal structures, sending broadcasts about
9825 * diabled packages, gc'ing to free up references, unmounting all
9826 * secure containers corresponding to packages on external media, and
9827 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9828 * Please note that we always have to post this message if status has
9829 * been requested no matter what.
9830 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009831 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009832 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009833 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009834 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009835 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009836 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009837 for (SdInstallArgs args : keys) {
9838 String cid = args.cid;
9839 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009840 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009841 // Delete package internally
9842 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9843 synchronized (mInstallLock) {
9844 boolean res = deletePackageLI(pkgName, false,
9845 PackageManager.DONT_DELETE_DATA, outInfo);
9846 if (res) {
9847 pkgList.add(pkgName);
9848 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009849 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009850 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009851 }
9852 }
9853 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009854 // We have to absolutely send UPDATED_MEDIA_STATUS only
9855 // after confirming that all the receivers processed the ordered
9856 // broadcast when packages get disabled, force a gc to clean things up.
9857 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009858 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009859 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9860 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9861 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009862 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9863 reportStatus ? 1 : 0, 1, keys);
9864 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009865 }
9866 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009867 } else {
9868 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9869 reportStatus ? 1 : 0, -1, keys);
9870 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009871 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009872 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009873
9874 public void movePackage(final String packageName,
9875 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009876 mContext.enforceCallingOrSelfPermission(
9877 android.Manifest.permission.MOVE_PACKAGE, null);
9878 int returnCode = PackageManager.MOVE_SUCCEEDED;
9879 int currFlags = 0;
9880 int newFlags = 0;
9881 synchronized (mPackages) {
9882 PackageParser.Package pkg = mPackages.get(packageName);
9883 if (pkg == null) {
9884 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009885 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009886 // Disable moving fwd locked apps and system packages
9887 if (pkg.applicationInfo != null &&
9888 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9889 Slog.w(TAG, "Cannot move system application");
9890 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9891 } else if (pkg.applicationInfo != null &&
9892 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9893 Slog.w(TAG, "Cannot move forward locked app.");
9894 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009895 } else if (pkg.mOperationPending) {
9896 Slog.w(TAG, "Attempt to move package which has pending operations");
9897 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009898 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009899 // Find install location first
9900 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9901 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9902 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009903 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009904 } else {
9905 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9906 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9907 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
9908 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9909 if (newFlags == currFlags) {
9910 Slog.w(TAG, "No move required. Trying to move to same location");
9911 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9912 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009913 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009914 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9915 pkg.mOperationPending = true;
9916 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009917 }
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 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010029
10030 // Allow more operations on this file if we didn't fail because
10031 // an operation was already pending for this package.
10032 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
10033 synchronized (mPackages) {
10034 PackageParser.Package pkg = mPackages.get(mp.packageName);
10035 if (pkg != null) {
10036 pkg.mOperationPending = false;
10037 }
10038 }
10039 }
10040
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010041 IPackageMoveObserver observer = mp.observer;
10042 if (observer != null) {
10043 try {
10044 observer.packageMoved(mp.packageName, returnCode);
10045 } catch (RemoteException e) {
10046 Log.i(TAG, "Observer no longer exists.");
10047 }
10048 }
10049 }
10050 });
10051 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070010052
10053 public boolean setInstallLocation(int loc) {
10054 mContext.enforceCallingOrSelfPermission(
10055 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
10056 if (getInstallLocation() == loc) {
10057 return true;
10058 }
10059 if (loc == PackageHelper.APP_INSTALL_AUTO ||
10060 loc == PackageHelper.APP_INSTALL_INTERNAL ||
10061 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
10062 android.provider.Settings.System.putInt(mContext.getContentResolver(),
10063 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
10064 return true;
10065 }
10066 return false;
10067 }
10068
10069 public int getInstallLocation() {
10070 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
10071 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
10072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010073}