blob: 0ff33d1486834ec0aa625d2a30df3dd1ec984253 [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) {
Kenny Roote2f74172010-08-04 13:35:33 -07005870 if (mNoDexOpt) {
5871 /*
5872 * If we're in an engineering build, programs are lazily run
5873 * through dexopt. If the .dex file doesn't exist yet, it
5874 * will be created when the program is run next.
5875 */
5876 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5877 } else {
5878 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5879 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5880 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005881 }
5882 }
5883 return PackageManager.INSTALL_SUCCEEDED;
5884 }
5885
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005886 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005887 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005888 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005889 synchronized (mPackages) {
5890 //write settings. the installStatus will be incomplete at this stage.
5891 //note that the new package setting would have already been
5892 //added to mPackages. It hasn't been persisted yet.
5893 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5894 mSettings.writeLP();
5895 }
5896
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005897 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005898 != PackageManager.INSTALL_SUCCEEDED) {
5899 // Discontinue if moving dex files failed.
5900 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005901 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005902 if((res.returnCode = setPermissionsLI(newPackage))
5903 != PackageManager.INSTALL_SUCCEEDED) {
5904 if (mInstaller != null) {
5905 mInstaller.rmdex(newPackage.mScanPath);
5906 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005907 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005908 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005909 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005911 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005912 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005913 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005914 res.name = pkgName;
5915 res.uid = newPackage.applicationInfo.uid;
5916 res.pkg = newPackage;
5917 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005918 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005919 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5920 //to update install status
5921 mSettings.writeLP();
5922 }
5923 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005924
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005925 private void installPackageLI(InstallArgs args,
5926 boolean newInstall, PackageInstalledInfo res) {
5927 int pFlags = args.flags;
5928 String installerPackageName = args.installerPackageName;
5929 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005930 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005931 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005932 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005933 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005934 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005935 // Result object to be returned
5936 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5937
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005938 // Retrieve PackageSettings and parse package
5939 int parseFlags = PackageParser.PARSE_CHATTY |
5940 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5941 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5942 parseFlags |= mDefParseFlags;
5943 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5944 pp.setSeparateProcesses(mSeparateProcesses);
5945 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5946 null, mMetrics, parseFlags);
5947 if (pkg == null) {
5948 res.returnCode = pp.getParseError();
5949 return;
5950 }
5951 String pkgName = res.name = pkg.packageName;
5952 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5953 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5954 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5955 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005956 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005957 }
5958 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5959 res.returnCode = pp.getParseError();
5960 return;
5961 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005962 // Get rid of all references to package scan path via parser.
5963 pp = null;
5964 String oldCodePath = null;
5965 boolean systemApp = false;
5966 synchronized (mPackages) {
5967 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005968 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5969 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005970 if (pkg.mOriginalPackages != null
5971 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005972 && mPackages.containsKey(oldName)) {
5973 // This package is derived from an original package,
5974 // and this device has been updating from that original
5975 // name. We must continue using the original name, so
5976 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005977 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005978 pkgName = pkg.packageName;
5979 replace = true;
5980 } else if (mPackages.containsKey(pkgName)) {
5981 // This package, under its official name, already exists
5982 // on the device; we should replace it.
5983 replace = true;
5984 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005985 }
5986 PackageSetting ps = mSettings.mPackages.get(pkgName);
5987 if (ps != null) {
5988 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5989 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5990 systemApp = (ps.pkg.applicationInfo.flags &
5991 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005992 }
5993 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005994 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005995
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005996 if (systemApp && onSd) {
5997 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005998 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005999 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
6000 return;
6001 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08006002
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006003 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
6004 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6005 return;
6006 }
6007 // Set application objects path explicitly after the rename
6008 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006009 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006010 replacePackageLI(pkg, parseFlags, scanMode,
6011 installerPackageName, res);
6012 } else {
6013 installNewPackageLI(pkg, parseFlags, scanMode,
6014 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 }
6016 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006017
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006018 private int setPermissionsLI(PackageParser.Package newPackage) {
6019 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006020 int retCode = 0;
6021 // TODO Gross hack but fix later. Ideally move this to be a post installation
6022 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006023 if ((newPackage.applicationInfo.flags
6024 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
6025 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 try {
6027 extractPublicFiles(newPackage, destResourceFile);
6028 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006029 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 -08006030 " forward-locked app.");
6031 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6032 } finally {
6033 //TODO clean up the extracted public files
6034 }
6035 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006036 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006037 newPackage.applicationInfo.uid);
6038 } else {
6039 final int filePermissions =
6040 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006041 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006042 newPackage.applicationInfo.uid);
6043 }
6044 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006045 // The permissions on the resource file was set when it was copied for
6046 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006047 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006049 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006050 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006051 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006052 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006053 // TODO Define new internal error
6054 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006055 }
6056 return PackageManager.INSTALL_SUCCEEDED;
6057 }
6058
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006059 private boolean isForwardLocked(PackageParser.Package pkg) {
6060 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061 }
6062
Suchi Amalapurapuae181712010-03-30 14:01:02 -07006063 private boolean isExternal(PackageParser.Package pkg) {
6064 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
6065 }
6066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006067 private void extractPublicFiles(PackageParser.Package newPackage,
6068 File publicZipFile) throws IOException {
6069 final ZipOutputStream publicZipOutStream =
6070 new ZipOutputStream(new FileOutputStream(publicZipFile));
6071 final ZipFile privateZip = new ZipFile(newPackage.mPath);
6072
6073 // Copy manifest, resources.arsc and res directory to public zip
6074
6075 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
6076 while (privateZipEntries.hasMoreElements()) {
6077 final ZipEntry zipEntry = privateZipEntries.nextElement();
6078 final String zipEntryName = zipEntry.getName();
6079 if ("AndroidManifest.xml".equals(zipEntryName)
6080 || "resources.arsc".equals(zipEntryName)
6081 || zipEntryName.startsWith("res/")) {
6082 try {
6083 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
6084 } catch (IOException e) {
6085 try {
6086 publicZipOutStream.close();
6087 throw e;
6088 } finally {
6089 publicZipFile.delete();
6090 }
6091 }
6092 }
6093 }
6094
6095 publicZipOutStream.close();
6096 FileUtils.setPermissions(
6097 publicZipFile.getAbsolutePath(),
6098 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
6099 -1, -1);
6100 }
6101
6102 private static void copyZipEntry(ZipEntry zipEntry,
6103 ZipFile inZipFile,
6104 ZipOutputStream outZipStream) throws IOException {
6105 byte[] buffer = new byte[4096];
6106 int num;
6107
6108 ZipEntry newEntry;
6109 if (zipEntry.getMethod() == ZipEntry.STORED) {
6110 // Preserve the STORED method of the input entry.
6111 newEntry = new ZipEntry(zipEntry);
6112 } else {
6113 // Create a new entry so that the compressed len is recomputed.
6114 newEntry = new ZipEntry(zipEntry.getName());
6115 }
6116 outZipStream.putNextEntry(newEntry);
6117
6118 InputStream data = inZipFile.getInputStream(zipEntry);
6119 while ((num = data.read(buffer)) > 0) {
6120 outZipStream.write(buffer, 0, num);
6121 }
6122 outZipStream.flush();
6123 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006125 private void deleteTempPackageFiles() {
6126 FilenameFilter filter = new FilenameFilter() {
6127 public boolean accept(File dir, String name) {
6128 return name.startsWith("vmdl") && name.endsWith(".tmp");
6129 }
6130 };
6131 String tmpFilesList[] = mAppInstallDir.list(filter);
6132 if(tmpFilesList == null) {
6133 return;
6134 }
6135 for(int i = 0; i < tmpFilesList.length; i++) {
6136 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
6137 tmpFile.delete();
6138 }
6139 }
6140
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006141 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006142 File tmpPackageFile;
6143 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006144 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006145 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006146 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006147 return null;
6148 }
6149 try {
6150 FileUtils.setPermissions(
6151 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6152 -1, -1);
6153 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006154 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006155 return null;
6156 }
6157 return tmpPackageFile;
6158 }
6159
6160 public void deletePackage(final String packageName,
6161 final IPackageDeleteObserver observer,
6162 final int flags) {
6163 mContext.enforceCallingOrSelfPermission(
6164 android.Manifest.permission.DELETE_PACKAGES, null);
6165 // Queue up an async operation since the package deletion may take a little while.
6166 mHandler.post(new Runnable() {
6167 public void run() {
6168 mHandler.removeCallbacks(this);
6169 final boolean succeded = deletePackageX(packageName, true, true, flags);
6170 if (observer != null) {
6171 try {
6172 observer.packageDeleted(succeded);
6173 } catch (RemoteException e) {
6174 Log.i(TAG, "Observer no longer exists.");
6175 } //end catch
6176 } //end if
6177 } //end run
6178 });
6179 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006181 /**
6182 * This method is an internal method that could be get invoked either
6183 * to delete an installed package or to clean up a failed installation.
6184 * After deleting an installed package, a broadcast is sent to notify any
6185 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006186 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187 * installation wouldn't have sent the initial broadcast either
6188 * The key steps in deleting a package are
6189 * deleting the package information in internal structures like mPackages,
6190 * deleting the packages base directories through installd
6191 * updating mSettings to reflect current status
6192 * persisting settings for later use
6193 * sending a broadcast if necessary
6194 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006195 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6196 boolean deleteCodeAndResources, int flags) {
6197 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006198 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006200 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6201 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6202 try {
6203 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006204 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006205 return false;
6206 }
6207 } catch (RemoteException e) {
6208 }
6209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006211 res = deletePackageLI(packageName, deleteCodeAndResources,
6212 flags | REMOVE_CHATTY, info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006213 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006216 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006217 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006218
6219 // If the removed package was a system update, the old system packaged
6220 // was re-enabled; we need to broadcast this information
6221 if (systemUpdate) {
6222 Bundle extras = new Bundle(1);
6223 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6224 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6225
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006226 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6227 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006229 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006230 // Force a gc here.
6231 Runtime.getRuntime().gc();
6232 // Delete the resources here after sending the broadcast to let
6233 // other processes clean up before deleting resources.
6234 if (info.args != null) {
6235 synchronized (mInstallLock) {
6236 info.args.doPostDeleteLI(deleteCodeAndResources);
6237 }
6238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006239 return res;
6240 }
6241
6242 static class PackageRemovedInfo {
6243 String removedPackage;
6244 int uid = -1;
6245 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006246 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006247 // Clean up resources deleted packages.
6248 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006249
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006250 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 Bundle extras = new Bundle(1);
6252 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6253 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6254 if (replacing) {
6255 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6256 }
6257 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006258 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 }
6260 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006261 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006262 }
6263 }
6264 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006266 /*
6267 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6268 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006269 * 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 -08006270 * delete a partially installed application.
6271 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006272 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006273 int flags) {
6274 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006275 if (outInfo != null) {
6276 outInfo.removedPackage = packageName;
6277 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006278 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 // Retrieve object to delete permissions for shared user later on
6280 PackageSetting deletedPs;
6281 synchronized (mPackages) {
6282 deletedPs = mSettings.mPackages.get(packageName);
6283 }
6284 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006285 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006287 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006289 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006290 + packageName + ", retcode=" + retCode);
6291 // we don't consider this to be a failure of the core package deletion
6292 }
6293 } else {
6294 //for emulator
6295 PackageParser.Package pkg = mPackages.get(packageName);
6296 File dataDir = new File(pkg.applicationInfo.dataDir);
6297 dataDir.delete();
6298 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006299 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006300 }
6301 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006302 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006303 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6304 if (outInfo != null) {
6305 outInfo.removedUid = mSettings.removePackageLP(packageName);
6306 }
6307 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006308 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006309 if (deletedPs.sharedUser != null) {
6310 // remove permissions associated with package
6311 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6312 }
6313 }
6314 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006315 // remove from preferred activities.
6316 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6317 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6318 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6319 removed.add(pa);
6320 }
6321 }
6322 for (PreferredActivity pa : removed) {
6323 mSettings.mPreferredActivities.removeFilter(pa);
6324 }
6325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006326 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006327 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006328 }
6329 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006331 /*
6332 * Tries to delete system package.
6333 */
6334 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006335 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 ApplicationInfo applicationInfo = p.applicationInfo;
6337 //applicable for non-partially installed applications only
6338 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006339 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006340 return false;
6341 }
6342 PackageSetting ps = null;
6343 // Confirm if the system package has been updated
6344 // An updated system app can be deleted. This will also have to restore
6345 // the system pkg from system partition
6346 synchronized (mPackages) {
6347 ps = mSettings.getDisabledSystemPkg(p.packageName);
6348 }
6349 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006350 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351 return false;
6352 } else {
6353 Log.i(TAG, "Deleting system pkg from data partition");
6354 }
6355 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006356 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006357 boolean deleteCodeAndResources = false;
6358 if (ps.versionCode < p.mVersionCode) {
6359 // Delete code and resources for downgrades
6360 deleteCodeAndResources = true;
6361 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6362 flags &= ~PackageManager.DONT_DELETE_DATA;
6363 }
6364 } else {
6365 // Preserve data by setting flag
6366 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6367 flags |= PackageManager.DONT_DELETE_DATA;
6368 }
6369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6371 if (!ret) {
6372 return false;
6373 }
6374 synchronized (mPackages) {
6375 // Reinstate the old system package
6376 mSettings.enableSystemPackageLP(p.packageName);
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07006377 // Remove any native libraries.
6378 removeNativeBinariesLI(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006379 }
6380 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006381 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006382 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006383 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006385 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006386 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006387 return false;
6388 }
6389 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006390 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391 mSettings.writeLP();
6392 }
6393 return true;
6394 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006396 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6397 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6398 ApplicationInfo applicationInfo = p.applicationInfo;
6399 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006400 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006401 return false;
6402 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006403 if (outInfo != null) {
6404 outInfo.uid = applicationInfo.uid;
6405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006406
6407 // Delete package data from internal structures and also remove data if flag is set
6408 removePackageDataLI(p, outInfo, flags);
6409
6410 // Delete application code and resources
6411 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006412 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006413 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006414 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006415 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6416 PackageManager.INSTALL_FORWARD_LOCK : 0;
6417 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006418 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006419 }
6420 return true;
6421 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006423 /*
6424 * This method handles package deletion in general
6425 */
6426 private boolean deletePackageLI(String packageName,
6427 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6428 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006429 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006430 return false;
6431 }
6432 PackageParser.Package p;
6433 boolean dataOnly = false;
6434 synchronized (mPackages) {
6435 p = mPackages.get(packageName);
6436 if (p == null) {
6437 //this retrieves partially installed apps
6438 dataOnly = true;
6439 PackageSetting ps = mSettings.mPackages.get(packageName);
6440 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006441 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006442 return false;
6443 }
6444 p = ps.pkg;
6445 }
6446 }
6447 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006448 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006449 return false;
6450 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006452 if (dataOnly) {
6453 // Delete application data first
6454 removePackageDataLI(p, outInfo, flags);
6455 return true;
6456 }
6457 // At this point the package should have ApplicationInfo associated with it
6458 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006459 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006460 return false;
6461 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006462 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006463 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6464 Log.i(TAG, "Removing system package:"+p.packageName);
6465 // When an updated system application is deleted we delete the existing resources as well and
6466 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006467 ret = deleteSystemPackageLI(p, flags, outInfo);
6468 } else {
6469 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006470 // Kill application pre-emptively especially for apps on sd.
6471 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006472 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006473 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006474 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006475 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 public void clearApplicationUserData(final String packageName,
6478 final IPackageDataObserver observer) {
6479 mContext.enforceCallingOrSelfPermission(
6480 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6481 // Queue up an async operation since the package deletion may take a little while.
6482 mHandler.post(new Runnable() {
6483 public void run() {
6484 mHandler.removeCallbacks(this);
6485 final boolean succeeded;
6486 synchronized (mInstallLock) {
6487 succeeded = clearApplicationUserDataLI(packageName);
6488 }
6489 if (succeeded) {
6490 // invoke DeviceStorageMonitor's update method to clear any notifications
6491 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6492 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6493 if (dsm != null) {
6494 dsm.updateMemory();
6495 }
6496 }
6497 if(observer != null) {
6498 try {
6499 observer.onRemoveCompleted(packageName, succeeded);
6500 } catch (RemoteException e) {
6501 Log.i(TAG, "Observer no longer exists.");
6502 }
6503 } //end if observer
6504 } //end run
6505 });
6506 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006508 private boolean clearApplicationUserDataLI(String packageName) {
6509 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006510 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006511 return false;
6512 }
6513 PackageParser.Package p;
6514 boolean dataOnly = false;
6515 synchronized (mPackages) {
6516 p = mPackages.get(packageName);
6517 if(p == null) {
6518 dataOnly = true;
6519 PackageSetting ps = mSettings.mPackages.get(packageName);
6520 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006521 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006522 return false;
6523 }
6524 p = ps.pkg;
6525 }
6526 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006527 boolean useEncryptedFSDir = false;
6528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006529 if(!dataOnly) {
6530 //need to check this only for fully installed applications
6531 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006532 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006533 return false;
6534 }
6535 final ApplicationInfo applicationInfo = p.applicationInfo;
6536 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006537 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006538 return false;
6539 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006540 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006541 }
6542 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006543 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006544 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006545 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006546 + packageName);
6547 return false;
6548 }
6549 }
6550 return true;
6551 }
6552
6553 public void deleteApplicationCacheFiles(final String packageName,
6554 final IPackageDataObserver observer) {
6555 mContext.enforceCallingOrSelfPermission(
6556 android.Manifest.permission.DELETE_CACHE_FILES, null);
6557 // Queue up an async operation since the package deletion may take a little while.
6558 mHandler.post(new Runnable() {
6559 public void run() {
6560 mHandler.removeCallbacks(this);
6561 final boolean succeded;
6562 synchronized (mInstallLock) {
6563 succeded = deleteApplicationCacheFilesLI(packageName);
6564 }
6565 if(observer != null) {
6566 try {
6567 observer.onRemoveCompleted(packageName, succeded);
6568 } catch (RemoteException e) {
6569 Log.i(TAG, "Observer no longer exists.");
6570 }
6571 } //end if observer
6572 } //end run
6573 });
6574 }
6575
6576 private boolean deleteApplicationCacheFilesLI(String packageName) {
6577 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006578 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006579 return false;
6580 }
6581 PackageParser.Package p;
6582 synchronized (mPackages) {
6583 p = mPackages.get(packageName);
6584 }
6585 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006586 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006587 return false;
6588 }
6589 final ApplicationInfo applicationInfo = p.applicationInfo;
6590 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006591 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006592 return false;
6593 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006594 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006595 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006596 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006597 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006598 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006599 + packageName);
6600 return false;
6601 }
6602 }
6603 return true;
6604 }
6605
6606 public void getPackageSizeInfo(final String packageName,
6607 final IPackageStatsObserver observer) {
6608 mContext.enforceCallingOrSelfPermission(
6609 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6610 // Queue up an async operation since the package deletion may take a little while.
6611 mHandler.post(new Runnable() {
6612 public void run() {
6613 mHandler.removeCallbacks(this);
6614 PackageStats lStats = new PackageStats(packageName);
6615 final boolean succeded;
6616 synchronized (mInstallLock) {
6617 succeded = getPackageSizeInfoLI(packageName, lStats);
6618 }
6619 if(observer != null) {
6620 try {
6621 observer.onGetStatsCompleted(lStats, succeded);
6622 } catch (RemoteException e) {
6623 Log.i(TAG, "Observer no longer exists.");
6624 }
6625 } //end if observer
6626 } //end run
6627 });
6628 }
6629
6630 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6631 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006632 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006633 return false;
6634 }
6635 PackageParser.Package p;
6636 boolean dataOnly = false;
6637 synchronized (mPackages) {
6638 p = mPackages.get(packageName);
6639 if(p == null) {
6640 dataOnly = true;
6641 PackageSetting ps = mSettings.mPackages.get(packageName);
6642 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006643 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006644 return false;
6645 }
6646 p = ps.pkg;
6647 }
6648 }
6649 String publicSrcDir = null;
6650 if(!dataOnly) {
6651 final ApplicationInfo applicationInfo = p.applicationInfo;
6652 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006653 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006654 return false;
6655 }
6656 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6657 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006658 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006659 if (mInstaller != null) {
6660 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006661 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006662 if (res < 0) {
6663 return false;
6664 } else {
6665 return true;
6666 }
6667 }
6668 return true;
6669 }
6670
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006672 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006673 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006674 }
6675
6676 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006677 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006678 }
6679
6680 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006681 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006682 }
6683
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006684 int getUidTargetSdkVersionLockedLP(int uid) {
6685 Object obj = mSettings.getUserIdLP(uid);
6686 if (obj instanceof SharedUserSetting) {
6687 SharedUserSetting sus = (SharedUserSetting)obj;
6688 final int N = sus.packages.size();
6689 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6690 Iterator<PackageSetting> it = sus.packages.iterator();
6691 int i=0;
6692 while (it.hasNext()) {
6693 PackageSetting ps = it.next();
6694 if (ps.pkg != null) {
6695 int v = ps.pkg.applicationInfo.targetSdkVersion;
6696 if (v < vers) vers = v;
6697 }
6698 }
6699 return vers;
6700 } else if (obj instanceof PackageSetting) {
6701 PackageSetting ps = (PackageSetting)obj;
6702 if (ps.pkg != null) {
6703 return ps.pkg.applicationInfo.targetSdkVersion;
6704 }
6705 }
6706 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6707 }
6708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006709 public void addPreferredActivity(IntentFilter filter, int match,
6710 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006711 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006712 if (mContext.checkCallingOrSelfPermission(
6713 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6714 != PackageManager.PERMISSION_GRANTED) {
6715 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6716 < Build.VERSION_CODES.FROYO) {
6717 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6718 + Binder.getCallingUid());
6719 return;
6720 }
6721 mContext.enforceCallingOrSelfPermission(
6722 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6723 }
6724
6725 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006726 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6727 mSettings.mPreferredActivities.addFilter(
6728 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006729 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006730 }
6731 }
6732
Satish Sampath8dbe6122009-06-02 23:35:54 +01006733 public void replacePreferredActivity(IntentFilter filter, int match,
6734 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006735 if (filter.countActions() != 1) {
6736 throw new IllegalArgumentException(
6737 "replacePreferredActivity expects filter to have only 1 action.");
6738 }
6739 if (filter.countCategories() != 1) {
6740 throw new IllegalArgumentException(
6741 "replacePreferredActivity expects filter to have only 1 category.");
6742 }
6743 if (filter.countDataAuthorities() != 0
6744 || filter.countDataPaths() != 0
6745 || filter.countDataSchemes() != 0
6746 || filter.countDataTypes() != 0) {
6747 throw new IllegalArgumentException(
6748 "replacePreferredActivity expects filter to have no data authorities, " +
6749 "paths, schemes or types.");
6750 }
6751 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006752 if (mContext.checkCallingOrSelfPermission(
6753 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6754 != PackageManager.PERMISSION_GRANTED) {
6755 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6756 < Build.VERSION_CODES.FROYO) {
6757 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6758 + Binder.getCallingUid());
6759 return;
6760 }
6761 mContext.enforceCallingOrSelfPermission(
6762 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6763 }
6764
Satish Sampath8dbe6122009-06-02 23:35:54 +01006765 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6766 String action = filter.getAction(0);
6767 String category = filter.getCategory(0);
6768 while (it.hasNext()) {
6769 PreferredActivity pa = it.next();
6770 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6771 it.remove();
6772 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6773 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6774 }
6775 }
6776 addPreferredActivity(filter, match, set, activity);
6777 }
6778 }
6779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006780 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006781 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006782 int uid = Binder.getCallingUid();
6783 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006784 if (pkg == null || pkg.applicationInfo.uid != uid) {
6785 if (mContext.checkCallingOrSelfPermission(
6786 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6787 != PackageManager.PERMISSION_GRANTED) {
6788 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6789 < Build.VERSION_CODES.FROYO) {
6790 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6791 + Binder.getCallingUid());
6792 return;
6793 }
6794 mContext.enforceCallingOrSelfPermission(
6795 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6796 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006797 }
6798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006799 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006800 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006801 }
6802 }
6803 }
6804
6805 boolean clearPackagePreferredActivitiesLP(String packageName) {
6806 boolean changed = false;
6807 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6808 while (it.hasNext()) {
6809 PreferredActivity pa = it.next();
6810 if (pa.mActivity.getPackageName().equals(packageName)) {
6811 it.remove();
6812 changed = true;
6813 }
6814 }
6815 return changed;
6816 }
6817
6818 public int getPreferredActivities(List<IntentFilter> outFilters,
6819 List<ComponentName> outActivities, String packageName) {
6820
6821 int num = 0;
6822 synchronized (mPackages) {
6823 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6824 while (it.hasNext()) {
6825 PreferredActivity pa = it.next();
6826 if (packageName == null
6827 || pa.mActivity.getPackageName().equals(packageName)) {
6828 if (outFilters != null) {
6829 outFilters.add(new IntentFilter(pa));
6830 }
6831 if (outActivities != null) {
6832 outActivities.add(pa.mActivity);
6833 }
6834 }
6835 }
6836 }
6837
6838 return num;
6839 }
6840
6841 public void setApplicationEnabledSetting(String appPackageName,
6842 int newState, int flags) {
6843 setEnabledSetting(appPackageName, null, newState, flags);
6844 }
6845
6846 public void setComponentEnabledSetting(ComponentName componentName,
6847 int newState, int flags) {
6848 setEnabledSetting(componentName.getPackageName(),
6849 componentName.getClassName(), newState, flags);
6850 }
6851
6852 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006853 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006854 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6855 || newState == COMPONENT_ENABLED_STATE_ENABLED
6856 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6857 throw new IllegalArgumentException("Invalid new component state: "
6858 + newState);
6859 }
6860 PackageSetting pkgSetting;
6861 final int uid = Binder.getCallingUid();
6862 final int permission = mContext.checkCallingPermission(
6863 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6864 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006865 boolean sendNow = false;
6866 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006867 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006868 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006869 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006870 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006871 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006872 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006873 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006874 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006875 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006876 }
6877 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006878 "Unknown component: " + packageName
6879 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006880 }
6881 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6882 throw new SecurityException(
6883 "Permission Denial: attempt to change component state from pid="
6884 + Binder.getCallingPid()
6885 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6886 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006887 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006888 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006889 if (pkgSetting.enabled == newState) {
6890 // Nothing to do
6891 return;
6892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006893 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006894 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006895 } else {
6896 // We're dealing with a component level state change
6897 switch (newState) {
6898 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006899 if (!pkgSetting.enableComponentLP(className)) {
6900 return;
6901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006902 break;
6903 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006904 if (!pkgSetting.disableComponentLP(className)) {
6905 return;
6906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006907 break;
6908 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006909 if (!pkgSetting.restoreComponentLP(className)) {
6910 return;
6911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006912 break;
6913 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006914 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006915 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006916 }
6917 }
6918 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006919 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006920 components = mPendingBroadcasts.get(packageName);
6921 boolean newPackage = components == null;
6922 if (newPackage) {
6923 components = new ArrayList<String>();
6924 }
6925 if (!components.contains(componentName)) {
6926 components.add(componentName);
6927 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006928 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6929 sendNow = true;
6930 // Purge entry from pending broadcast list if another one exists already
6931 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006932 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006933 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006934 if (newPackage) {
6935 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006936 }
6937 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6938 // Schedule a message
6939 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6940 }
6941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006942 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006944 long callingId = Binder.clearCallingIdentity();
6945 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006946 if (sendNow) {
6947 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006948 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006950 } finally {
6951 Binder.restoreCallingIdentity(callingId);
6952 }
6953 }
6954
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006955 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006956 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6957 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6958 + " components=" + componentNames);
6959 Bundle extras = new Bundle(4);
6960 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6961 String nameList[] = new String[componentNames.size()];
6962 componentNames.toArray(nameList);
6963 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006964 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6965 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006966 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006967 }
6968
Jacek Surazski65e13172009-04-28 15:26:38 +02006969 public String getInstallerPackageName(String packageName) {
6970 synchronized (mPackages) {
6971 PackageSetting pkg = mSettings.mPackages.get(packageName);
6972 if (pkg == null) {
6973 throw new IllegalArgumentException("Unknown package: " + packageName);
6974 }
6975 return pkg.installerPackageName;
6976 }
6977 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006979 public int getApplicationEnabledSetting(String appPackageName) {
6980 synchronized (mPackages) {
6981 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6982 if (pkg == null) {
6983 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6984 }
6985 return pkg.enabled;
6986 }
6987 }
6988
6989 public int getComponentEnabledSetting(ComponentName componentName) {
6990 synchronized (mPackages) {
6991 final String packageNameStr = componentName.getPackageName();
6992 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6993 if (pkg == null) {
6994 throw new IllegalArgumentException("Unknown component: " + componentName);
6995 }
6996 final String classNameStr = componentName.getClassName();
6997 return pkg.currentEnabledStateLP(classNameStr);
6998 }
6999 }
7000
7001 public void enterSafeMode() {
7002 if (!mSystemReady) {
7003 mSafeMode = true;
7004 }
7005 }
7006
7007 public void systemReady() {
7008 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007009
7010 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07007011 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007012 mContext.getContentResolver(),
7013 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07007014 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007015 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07007016 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007018 }
7019
7020 public boolean isSafeMode() {
7021 return mSafeMode;
7022 }
7023
7024 public boolean hasSystemUidErrors() {
7025 return mHasSystemUidErrors;
7026 }
7027
7028 static String arrayToString(int[] array) {
7029 StringBuffer buf = new StringBuffer(128);
7030 buf.append('[');
7031 if (array != null) {
7032 for (int i=0; i<array.length; i++) {
7033 if (i > 0) buf.append(", ");
7034 buf.append(array[i]);
7035 }
7036 }
7037 buf.append(']');
7038 return buf.toString();
7039 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007041 @Override
7042 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
7043 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
7044 != PackageManager.PERMISSION_GRANTED) {
7045 pw.println("Permission Denial: can't dump ActivityManager from from pid="
7046 + Binder.getCallingPid()
7047 + ", uid=" + Binder.getCallingUid()
7048 + " without permission "
7049 + android.Manifest.permission.DUMP);
7050 return;
7051 }
7052
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007053 String packageName = null;
7054
7055 int opti = 0;
7056 while (opti < args.length) {
7057 String opt = args[opti];
7058 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
7059 break;
7060 }
7061 opti++;
7062 if ("-a".equals(opt)) {
7063 // Right now we only know how to print all.
7064 } else if ("-h".equals(opt)) {
7065 pw.println("Package manager dump options:");
7066 pw.println(" [-h] [cmd] ...");
7067 pw.println(" cmd may be one of:");
7068 pw.println(" [package.name]: info about given package");
7069 return;
7070 } else {
7071 pw.println("Unknown argument: " + opt + "; use -h for help");
7072 }
7073 }
7074
7075 // Is the caller requesting to dump a particular piece of data?
7076 if (opti < args.length) {
7077 String cmd = args[opti];
7078 opti++;
7079 // Is this a package name?
7080 if ("android".equals(cmd) || cmd.contains(".")) {
7081 packageName = cmd;
7082 }
7083 }
7084
7085 boolean printedTitle = false;
7086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007087 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007088 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
7089 printedTitle = true;
7090 }
7091 if (mReceivers.dump(pw, printedTitle
7092 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
7093 " ", packageName)) {
7094 printedTitle = true;
7095 }
7096 if (mServices.dump(pw, printedTitle
7097 ? "\nService Resolver Table:" : "Service Resolver Table:",
7098 " ", packageName)) {
7099 printedTitle = true;
7100 }
7101 if (mSettings.mPreferredActivities.dump(pw, printedTitle
7102 ? "\nPreferred Activities:" : "Preferred Activities:",
7103 " ", packageName)) {
7104 printedTitle = true;
7105 }
7106 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007107 {
7108 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007109 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7110 continue;
7111 }
7112 if (!printedSomething) {
7113 if (printedTitle) pw.println(" ");
7114 pw.println("Permissions:");
7115 printedSomething = true;
7116 printedTitle = true;
7117 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007118 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7119 pw.print(Integer.toHexString(System.identityHashCode(p)));
7120 pw.println("):");
7121 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7122 pw.print(" uid="); pw.print(p.uid);
7123 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007124 pw.print(" type="); pw.print(p.type);
7125 pw.print(" prot="); pw.println(p.protectionLevel);
7126 if (p.packageSetting != null) {
7127 pw.print(" packageSetting="); pw.println(p.packageSetting);
7128 }
7129 if (p.perm != null) {
7130 pw.print(" perm="); pw.println(p.perm);
7131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007132 }
7133 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007134 printedSomething = false;
7135 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007136 {
7137 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007138 if (packageName != null && !packageName.equals(ps.realName)
7139 && !packageName.equals(ps.name)) {
7140 continue;
7141 }
7142 if (!printedSomething) {
7143 if (printedTitle) pw.println(" ");
7144 pw.println("Packages:");
7145 printedSomething = true;
7146 printedTitle = true;
7147 }
7148 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007149 pw.print(" Package [");
7150 pw.print(ps.realName != null ? ps.realName : ps.name);
7151 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007152 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7153 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007154 if (ps.realName != null) {
7155 pw.print(" compat name="); pw.println(ps.name);
7156 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007157 pw.print(" userId="); pw.print(ps.userId);
7158 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7159 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7160 pw.print(" pkg="); pw.println(ps.pkg);
7161 pw.print(" codePath="); pw.println(ps.codePathString);
7162 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07007163 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007164 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007165 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007166 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007167 pw.print(" supportsScreens=[");
7168 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007169 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007170 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7171 if (!first) pw.print(", ");
7172 first = false;
7173 pw.print("small");
7174 }
7175 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007176 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007177 if (!first) pw.print(", ");
7178 first = false;
7179 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007180 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007181 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007182 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007183 if (!first) pw.print(", ");
7184 first = false;
7185 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007186 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007187 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007188 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007189 if (!first) pw.print(", ");
7190 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007191 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007192 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007193 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007194 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007195 if (!first) pw.print(", ");
7196 first = false;
7197 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007198 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007199 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007200 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7201 if (!first) pw.print(", ");
7202 first = false;
7203 pw.print("anyDensity");
7204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007205 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007206 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007207 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7208 pw.print(" signatures="); pw.println(ps.signatures);
7209 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007210 pw.print(" haveGids="); pw.println(ps.haveGids);
7211 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007212 pw.print(" installStatus="); pw.print(ps.installStatus);
7213 pw.print(" enabled="); pw.println(ps.enabled);
Kenny Rootdeb11262010-08-02 11:36:21 -07007214 if (ps.pkg.mOperationPending) {
7215 pw.println(" mOperationPending=true");
7216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007217 if (ps.disabledComponents.size() > 0) {
7218 pw.println(" disabledComponents:");
7219 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007220 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007221 }
7222 }
7223 if (ps.enabledComponents.size() > 0) {
7224 pw.println(" enabledComponents:");
7225 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007226 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007227 }
7228 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007229 if (ps.grantedPermissions.size() > 0) {
7230 pw.println(" grantedPermissions:");
7231 for (String s : ps.grantedPermissions) {
7232 pw.print(" "); pw.println(s);
7233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007235 }
7236 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007237 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007238 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007239 for (HashMap.Entry<String, String> e
7240 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007241 if (packageName != null && !packageName.equals(e.getKey())
7242 && !packageName.equals(e.getValue())) {
7243 continue;
7244 }
7245 if (!printedSomething) {
7246 if (printedTitle) pw.println(" ");
7247 pw.println("Renamed packages:");
7248 printedSomething = true;
7249 printedTitle = true;
7250 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007251 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7252 pw.println(e.getValue());
7253 }
7254 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007255 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007256 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007257 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007258 if (packageName != null && !packageName.equals(ps.realName)
7259 && !packageName.equals(ps.name)) {
7260 continue;
7261 }
7262 if (!printedSomething) {
7263 if (printedTitle) pw.println(" ");
7264 pw.println("Hidden system packages:");
7265 printedSomething = true;
7266 printedTitle = true;
7267 }
7268 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007269 pw.print(ps.realName != null ? ps.realName : ps.name);
7270 pw.print("] (");
7271 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7272 pw.println("):");
7273 if (ps.realName != null) {
7274 pw.print(" compat name="); pw.println(ps.name);
7275 }
7276 pw.print(" userId="); pw.println(ps.userId);
7277 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7278 pw.print(" codePath="); pw.println(ps.codePathString);
7279 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7280 }
7281 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007282 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007283 {
7284 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007285 if (packageName != null && su != packageSharedUser) {
7286 continue;
7287 }
7288 if (!printedSomething) {
7289 if (printedTitle) pw.println(" ");
7290 pw.println("Shared users:");
7291 printedSomething = true;
7292 printedTitle = true;
7293 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007294 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7295 pw.print(Integer.toHexString(System.identityHashCode(su)));
7296 pw.println("):");
7297 pw.print(" userId="); pw.print(su.userId);
7298 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007299 pw.println(" grantedPermissions:");
7300 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007301 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007303 }
7304 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007305
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007306 if (packageName == null) {
7307 if (printedTitle) pw.println(" ");
7308 printedTitle = true;
7309 pw.println("Settings parse messages:");
7310 pw.println(mSettings.mReadMessages.toString());
7311
7312 pw.println(" ");
7313 pw.println("Package warning messages:");
7314 File fname = getSettingsProblemFile();
7315 FileInputStream in;
7316 try {
7317 in = new FileInputStream(fname);
7318 int avail = in.available();
7319 byte[] data = new byte[avail];
7320 in.read(data);
7321 pw.println(new String(data));
7322 } catch (FileNotFoundException e) {
7323 } catch (IOException e) {
7324 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007326 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007327
7328 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007329 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007330 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007331 if (packageName != null && !packageName.equals(p.info.packageName)) {
7332 continue;
7333 }
7334 if (!printedSomething) {
7335 if (printedTitle) pw.println(" ");
7336 pw.println("Registered ContentProviders:");
7337 printedSomething = true;
7338 printedTitle = true;
7339 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007340 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007341 pw.println(p.toString());
7342 }
7343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007344 }
7345
7346 static final class BasePermission {
7347 final static int TYPE_NORMAL = 0;
7348 final static int TYPE_BUILTIN = 1;
7349 final static int TYPE_DYNAMIC = 2;
7350
7351 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007352 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007353 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007354 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007355 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007356 PackageParser.Permission perm;
7357 PermissionInfo pendingInfo;
7358 int uid;
7359 int[] gids;
7360
7361 BasePermission(String _name, String _sourcePackage, int _type) {
7362 name = _name;
7363 sourcePackage = _sourcePackage;
7364 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007365 // Default to most conservative protection level.
7366 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7367 }
7368
7369 public String toString() {
7370 return "BasePermission{"
7371 + Integer.toHexString(System.identityHashCode(this))
7372 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007373 }
7374 }
7375
7376 static class PackageSignatures {
7377 private Signature[] mSignatures;
7378
7379 PackageSignatures(Signature[] sigs) {
7380 assignSignatures(sigs);
7381 }
7382
7383 PackageSignatures() {
7384 }
7385
7386 void writeXml(XmlSerializer serializer, String tagName,
7387 ArrayList<Signature> pastSignatures) throws IOException {
7388 if (mSignatures == null) {
7389 return;
7390 }
7391 serializer.startTag(null, tagName);
7392 serializer.attribute(null, "count",
7393 Integer.toString(mSignatures.length));
7394 for (int i=0; i<mSignatures.length; i++) {
7395 serializer.startTag(null, "cert");
7396 final Signature sig = mSignatures[i];
7397 final int sigHash = sig.hashCode();
7398 final int numPast = pastSignatures.size();
7399 int j;
7400 for (j=0; j<numPast; j++) {
7401 Signature pastSig = pastSignatures.get(j);
7402 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7403 serializer.attribute(null, "index", Integer.toString(j));
7404 break;
7405 }
7406 }
7407 if (j >= numPast) {
7408 pastSignatures.add(sig);
7409 serializer.attribute(null, "index", Integer.toString(numPast));
7410 serializer.attribute(null, "key", sig.toCharsString());
7411 }
7412 serializer.endTag(null, "cert");
7413 }
7414 serializer.endTag(null, tagName);
7415 }
7416
7417 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7418 throws IOException, XmlPullParserException {
7419 String countStr = parser.getAttributeValue(null, "count");
7420 if (countStr == null) {
7421 reportSettingsProblem(Log.WARN,
7422 "Error in package manager settings: <signatures> has"
7423 + " no count at " + parser.getPositionDescription());
7424 XmlUtils.skipCurrentTag(parser);
7425 }
7426 final int count = Integer.parseInt(countStr);
7427 mSignatures = new Signature[count];
7428 int pos = 0;
7429
7430 int outerDepth = parser.getDepth();
7431 int type;
7432 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7433 && (type != XmlPullParser.END_TAG
7434 || parser.getDepth() > outerDepth)) {
7435 if (type == XmlPullParser.END_TAG
7436 || type == XmlPullParser.TEXT) {
7437 continue;
7438 }
7439
7440 String tagName = parser.getName();
7441 if (tagName.equals("cert")) {
7442 if (pos < count) {
7443 String index = parser.getAttributeValue(null, "index");
7444 if (index != null) {
7445 try {
7446 int idx = Integer.parseInt(index);
7447 String key = parser.getAttributeValue(null, "key");
7448 if (key == null) {
7449 if (idx >= 0 && idx < pastSignatures.size()) {
7450 Signature sig = pastSignatures.get(idx);
7451 if (sig != null) {
7452 mSignatures[pos] = pastSignatures.get(idx);
7453 pos++;
7454 } else {
7455 reportSettingsProblem(Log.WARN,
7456 "Error in package manager settings: <cert> "
7457 + "index " + index + " is not defined at "
7458 + parser.getPositionDescription());
7459 }
7460 } else {
7461 reportSettingsProblem(Log.WARN,
7462 "Error in package manager settings: <cert> "
7463 + "index " + index + " is out of bounds at "
7464 + parser.getPositionDescription());
7465 }
7466 } else {
7467 while (pastSignatures.size() <= idx) {
7468 pastSignatures.add(null);
7469 }
7470 Signature sig = new Signature(key);
7471 pastSignatures.set(idx, sig);
7472 mSignatures[pos] = sig;
7473 pos++;
7474 }
7475 } catch (NumberFormatException e) {
7476 reportSettingsProblem(Log.WARN,
7477 "Error in package manager settings: <cert> "
7478 + "index " + index + " is not a number at "
7479 + parser.getPositionDescription());
7480 }
7481 } else {
7482 reportSettingsProblem(Log.WARN,
7483 "Error in package manager settings: <cert> has"
7484 + " no index at " + parser.getPositionDescription());
7485 }
7486 } else {
7487 reportSettingsProblem(Log.WARN,
7488 "Error in package manager settings: too "
7489 + "many <cert> tags, expected " + count
7490 + " at " + parser.getPositionDescription());
7491 }
7492 } else {
7493 reportSettingsProblem(Log.WARN,
7494 "Unknown element under <cert>: "
7495 + parser.getName());
7496 }
7497 XmlUtils.skipCurrentTag(parser);
7498 }
7499
7500 if (pos < count) {
7501 // Should never happen -- there is an error in the written
7502 // settings -- but if it does we don't want to generate
7503 // a bad array.
7504 Signature[] newSigs = new Signature[pos];
7505 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7506 mSignatures = newSigs;
7507 }
7508 }
7509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007510 private void assignSignatures(Signature[] sigs) {
7511 if (sigs == null) {
7512 mSignatures = null;
7513 return;
7514 }
7515 mSignatures = new Signature[sigs.length];
7516 for (int i=0; i<sigs.length; i++) {
7517 mSignatures[i] = sigs[i];
7518 }
7519 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007521 @Override
7522 public String toString() {
7523 StringBuffer buf = new StringBuffer(128);
7524 buf.append("PackageSignatures{");
7525 buf.append(Integer.toHexString(System.identityHashCode(this)));
7526 buf.append(" [");
7527 if (mSignatures != null) {
7528 for (int i=0; i<mSignatures.length; i++) {
7529 if (i > 0) buf.append(", ");
7530 buf.append(Integer.toHexString(
7531 System.identityHashCode(mSignatures[i])));
7532 }
7533 }
7534 buf.append("]}");
7535 return buf.toString();
7536 }
7537 }
7538
7539 static class PreferredActivity extends IntentFilter {
7540 final int mMatch;
7541 final String[] mSetPackages;
7542 final String[] mSetClasses;
7543 final String[] mSetComponents;
7544 final ComponentName mActivity;
7545 final String mShortActivity;
7546 String mParseError;
7547
7548 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7549 ComponentName activity) {
7550 super(filter);
7551 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7552 mActivity = activity;
7553 mShortActivity = activity.flattenToShortString();
7554 mParseError = null;
7555 if (set != null) {
7556 final int N = set.length;
7557 String[] myPackages = new String[N];
7558 String[] myClasses = new String[N];
7559 String[] myComponents = new String[N];
7560 for (int i=0; i<N; i++) {
7561 ComponentName cn = set[i];
7562 if (cn == null) {
7563 mSetPackages = null;
7564 mSetClasses = null;
7565 mSetComponents = null;
7566 return;
7567 }
7568 myPackages[i] = cn.getPackageName().intern();
7569 myClasses[i] = cn.getClassName().intern();
7570 myComponents[i] = cn.flattenToShortString().intern();
7571 }
7572 mSetPackages = myPackages;
7573 mSetClasses = myClasses;
7574 mSetComponents = myComponents;
7575 } else {
7576 mSetPackages = null;
7577 mSetClasses = null;
7578 mSetComponents = null;
7579 }
7580 }
7581
7582 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7583 IOException {
7584 mShortActivity = parser.getAttributeValue(null, "name");
7585 mActivity = ComponentName.unflattenFromString(mShortActivity);
7586 if (mActivity == null) {
7587 mParseError = "Bad activity name " + mShortActivity;
7588 }
7589 String matchStr = parser.getAttributeValue(null, "match");
7590 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7591 String setCountStr = parser.getAttributeValue(null, "set");
7592 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7593
7594 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7595 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7596 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7597
7598 int setPos = 0;
7599
7600 int outerDepth = parser.getDepth();
7601 int type;
7602 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7603 && (type != XmlPullParser.END_TAG
7604 || parser.getDepth() > outerDepth)) {
7605 if (type == XmlPullParser.END_TAG
7606 || type == XmlPullParser.TEXT) {
7607 continue;
7608 }
7609
7610 String tagName = parser.getName();
7611 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7612 // + parser.getDepth() + " tag=" + tagName);
7613 if (tagName.equals("set")) {
7614 String name = parser.getAttributeValue(null, "name");
7615 if (name == null) {
7616 if (mParseError == null) {
7617 mParseError = "No name in set tag in preferred activity "
7618 + mShortActivity;
7619 }
7620 } else if (setPos >= setCount) {
7621 if (mParseError == null) {
7622 mParseError = "Too many set tags in preferred activity "
7623 + mShortActivity;
7624 }
7625 } else {
7626 ComponentName cn = ComponentName.unflattenFromString(name);
7627 if (cn == null) {
7628 if (mParseError == null) {
7629 mParseError = "Bad set name " + name + " in preferred activity "
7630 + mShortActivity;
7631 }
7632 } else {
7633 myPackages[setPos] = cn.getPackageName();
7634 myClasses[setPos] = cn.getClassName();
7635 myComponents[setPos] = name;
7636 setPos++;
7637 }
7638 }
7639 XmlUtils.skipCurrentTag(parser);
7640 } else if (tagName.equals("filter")) {
7641 //Log.i(TAG, "Starting to parse filter...");
7642 readFromXml(parser);
7643 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7644 // + parser.getDepth() + " tag=" + parser.getName());
7645 } else {
7646 reportSettingsProblem(Log.WARN,
7647 "Unknown element under <preferred-activities>: "
7648 + parser.getName());
7649 XmlUtils.skipCurrentTag(parser);
7650 }
7651 }
7652
7653 if (setPos != setCount) {
7654 if (mParseError == null) {
7655 mParseError = "Not enough set tags (expected " + setCount
7656 + " but found " + setPos + ") in " + mShortActivity;
7657 }
7658 }
7659
7660 mSetPackages = myPackages;
7661 mSetClasses = myClasses;
7662 mSetComponents = myComponents;
7663 }
7664
7665 public void writeToXml(XmlSerializer serializer) throws IOException {
7666 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7667 serializer.attribute(null, "name", mShortActivity);
7668 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7669 serializer.attribute(null, "set", Integer.toString(NS));
7670 for (int s=0; s<NS; s++) {
7671 serializer.startTag(null, "set");
7672 serializer.attribute(null, "name", mSetComponents[s]);
7673 serializer.endTag(null, "set");
7674 }
7675 serializer.startTag(null, "filter");
7676 super.writeToXml(serializer);
7677 serializer.endTag(null, "filter");
7678 }
7679
7680 boolean sameSet(List<ResolveInfo> query, int priority) {
7681 if (mSetPackages == null) return false;
7682 final int NQ = query.size();
7683 final int NS = mSetPackages.length;
7684 int numMatch = 0;
7685 for (int i=0; i<NQ; i++) {
7686 ResolveInfo ri = query.get(i);
7687 if (ri.priority != priority) continue;
7688 ActivityInfo ai = ri.activityInfo;
7689 boolean good = false;
7690 for (int j=0; j<NS; j++) {
7691 if (mSetPackages[j].equals(ai.packageName)
7692 && mSetClasses[j].equals(ai.name)) {
7693 numMatch++;
7694 good = true;
7695 break;
7696 }
7697 }
7698 if (!good) return false;
7699 }
7700 return numMatch == NS;
7701 }
7702 }
7703
7704 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007705 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007707 HashSet<String> grantedPermissions = new HashSet<String>();
7708 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007710 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007711 setFlags(pkgFlags);
7712 }
7713
7714 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007715 this.pkgFlags = pkgFlags & (
7716 ApplicationInfo.FLAG_SYSTEM |
7717 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007718 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007719 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007720 }
7721 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007723 /**
7724 * Settings base class for pending and resolved classes.
7725 */
7726 static class PackageSettingBase extends GrantedPermissions {
7727 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007728 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007729 File codePath;
7730 String codePathString;
7731 File resourcePath;
7732 String resourcePathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007733 String obbPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007734 private long timeStamp;
7735 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007736 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007737
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007738 boolean uidError;
7739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740 PackageSignatures signatures = new PackageSignatures();
7741
7742 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007743 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007745 /* Explicitly disabled components */
7746 HashSet<String> disabledComponents = new HashSet<String>(0);
7747 /* Explicitly enabled components */
7748 HashSet<String> enabledComponents = new HashSet<String>(0);
7749 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7750 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007751
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007752 PackageSettingBase origPackage;
7753
Jacek Surazski65e13172009-04-28 15:26:38 +02007754 /* package name of the app that installed this package */
7755 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007756
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007757 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007758 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007759 super(pkgFlags);
7760 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007761 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007762 init(codePath, resourcePath, pVersionCode);
7763 }
7764
7765 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007766 this.codePath = codePath;
7767 this.codePathString = codePath.toString();
7768 this.resourcePath = resourcePath;
7769 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007770 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007771 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007772
Jacek Surazski65e13172009-04-28 15:26:38 +02007773 public void setInstallerPackageName(String packageName) {
7774 installerPackageName = packageName;
7775 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007776
Jacek Surazski65e13172009-04-28 15:26:38 +02007777 String getInstallerPackageName() {
7778 return installerPackageName;
7779 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007781 public void setInstallStatus(int newStatus) {
7782 installStatus = newStatus;
7783 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007785 public int getInstallStatus() {
7786 return installStatus;
7787 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007789 public void setTimeStamp(long newStamp) {
7790 if (newStamp != timeStamp) {
7791 timeStamp = newStamp;
7792 timeStampString = Long.toString(newStamp);
7793 }
7794 }
7795
7796 public void setTimeStamp(long newStamp, String newStampStr) {
7797 timeStamp = newStamp;
7798 timeStampString = newStampStr;
7799 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007801 public long getTimeStamp() {
7802 return timeStamp;
7803 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007805 public String getTimeStampStr() {
7806 return timeStampString;
7807 }
7808
7809 public void copyFrom(PackageSettingBase base) {
7810 grantedPermissions = base.grantedPermissions;
7811 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007813 timeStamp = base.timeStamp;
7814 timeStampString = base.timeStampString;
7815 signatures = base.signatures;
7816 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007817 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007818 disabledComponents = base.disabledComponents;
7819 enabledComponents = base.enabledComponents;
7820 enabled = base.enabled;
7821 installStatus = base.installStatus;
7822 }
7823
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007824 boolean enableComponentLP(String componentClassName) {
7825 boolean changed = disabledComponents.remove(componentClassName);
7826 changed |= enabledComponents.add(componentClassName);
7827 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007828 }
7829
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007830 boolean disableComponentLP(String componentClassName) {
7831 boolean changed = enabledComponents.remove(componentClassName);
7832 changed |= disabledComponents.add(componentClassName);
7833 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007834 }
7835
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007836 boolean restoreComponentLP(String componentClassName) {
7837 boolean changed = enabledComponents.remove(componentClassName);
7838 changed |= disabledComponents.remove(componentClassName);
7839 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007840 }
7841
7842 int currentEnabledStateLP(String componentName) {
7843 if (enabledComponents.contains(componentName)) {
7844 return COMPONENT_ENABLED_STATE_ENABLED;
7845 } else if (disabledComponents.contains(componentName)) {
7846 return COMPONENT_ENABLED_STATE_DISABLED;
7847 } else {
7848 return COMPONENT_ENABLED_STATE_DEFAULT;
7849 }
7850 }
7851 }
7852
7853 /**
7854 * Settings data for a particular package we know about.
7855 */
7856 static final class PackageSetting extends PackageSettingBase {
7857 int userId;
7858 PackageParser.Package pkg;
7859 SharedUserSetting sharedUser;
7860
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007861 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007862 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007863 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007864 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007866 @Override
7867 public String toString() {
7868 return "PackageSetting{"
7869 + Integer.toHexString(System.identityHashCode(this))
7870 + " " + name + "/" + userId + "}";
7871 }
7872 }
7873
7874 /**
7875 * Settings data for a particular shared user ID we know about.
7876 */
7877 static final class SharedUserSetting extends GrantedPermissions {
7878 final String name;
7879 int userId;
7880 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7881 final PackageSignatures signatures = new PackageSignatures();
7882
7883 SharedUserSetting(String _name, int _pkgFlags) {
7884 super(_pkgFlags);
7885 name = _name;
7886 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007888 @Override
7889 public String toString() {
7890 return "SharedUserSetting{"
7891 + Integer.toHexString(System.identityHashCode(this))
7892 + " " + name + "/" + userId + "}";
7893 }
7894 }
7895
7896 /**
7897 * Holds information about dynamic settings.
7898 */
7899 private static final class Settings {
7900 private final File mSettingsFilename;
7901 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007902 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007903 private final HashMap<String, PackageSetting> mPackages =
7904 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007905 // List of replaced system applications
7906 final HashMap<String, PackageSetting> mDisabledSysPackages =
7907 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007908
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007909 // These are the last platform API version we were using for
7910 // the apps installed on internal and external storage. It is
7911 // used to grant newer permissions one time during a system upgrade.
7912 int mInternalSdkPlatform;
7913 int mExternalSdkPlatform;
7914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007915 // The user's preferred activities associated with particular intent
7916 // filters.
7917 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7918 new IntentResolver<PreferredActivity, PreferredActivity>() {
7919 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007920 protected String packageForFilter(PreferredActivity filter) {
7921 return filter.mActivity.getPackageName();
7922 }
7923 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007924 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007925 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007926 out.print(prefix); out.print(
7927 Integer.toHexString(System.identityHashCode(filter)));
7928 out.print(' ');
7929 out.print(filter.mActivity.flattenToShortString());
7930 out.print(" match=0x");
7931 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007932 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007933 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007934 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007935 out.print(prefix); out.print(" ");
7936 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007937 }
7938 }
7939 }
7940 };
7941 private final HashMap<String, SharedUserSetting> mSharedUsers =
7942 new HashMap<String, SharedUserSetting>();
7943 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7944 private final SparseArray<Object> mOtherUserIds =
7945 new SparseArray<Object>();
7946
7947 // For reading/writing settings file.
7948 private final ArrayList<Signature> mPastSignatures =
7949 new ArrayList<Signature>();
7950
7951 // Mapping from permission names to info about them.
7952 final HashMap<String, BasePermission> mPermissions =
7953 new HashMap<String, BasePermission>();
7954
7955 // Mapping from permission tree names to info about them.
7956 final HashMap<String, BasePermission> mPermissionTrees =
7957 new HashMap<String, BasePermission>();
7958
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007959 // Packages that have been uninstalled and still need their external
7960 // storage data deleted.
7961 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7962
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007963 // Packages that have been renamed since they were first installed.
7964 // Keys are the new names of the packages, values are the original
7965 // names. The packages appear everwhere else under their original
7966 // names.
7967 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007969 private final StringBuilder mReadMessages = new StringBuilder();
7970
7971 private static final class PendingPackage extends PackageSettingBase {
7972 final int sharedId;
7973
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007974 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007975 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007976 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007977 this.sharedId = sharedId;
7978 }
7979 }
7980 private final ArrayList<PendingPackage> mPendingPackages
7981 = new ArrayList<PendingPackage>();
7982
7983 Settings() {
7984 File dataDir = Environment.getDataDirectory();
7985 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007986 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7987 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007988 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007989 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007990 FileUtils.setPermissions(systemDir.toString(),
7991 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7992 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7993 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007994 FileUtils.setPermissions(systemSecureDir.toString(),
7995 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7996 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7997 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007998 mSettingsFilename = new File(systemDir, "packages.xml");
7999 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008000 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008001 }
8002
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008003 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008004 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008005 int pkgFlags, boolean create, boolean add) {
8006 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008007 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008008 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008009 return p;
8010 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008011
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008012 PackageSetting peekPackageLP(String name) {
8013 return mPackages.get(name);
8014 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008015 PackageSetting p = mPackages.get(name);
8016 if (p != null && p.codePath.getPath().equals(codePath)) {
8017 return p;
8018 }
8019 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008020 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008021 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008023 void setInstallStatus(String pkgName, int status) {
8024 PackageSetting p = mPackages.get(pkgName);
8025 if(p != null) {
8026 if(p.getInstallStatus() != status) {
8027 p.setInstallStatus(status);
8028 }
8029 }
8030 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008031
Jacek Surazski65e13172009-04-28 15:26:38 +02008032 void setInstallerPackageName(String pkgName,
8033 String installerPkgName) {
8034 PackageSetting p = mPackages.get(pkgName);
8035 if(p != null) {
8036 p.setInstallerPackageName(installerPkgName);
8037 }
8038 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008039
Jacek Surazski65e13172009-04-28 15:26:38 +02008040 String getInstallerPackageName(String pkgName) {
8041 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008042 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02008043 }
8044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008045 int getInstallStatus(String pkgName) {
8046 PackageSetting p = mPackages.get(pkgName);
8047 if(p != null) {
8048 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008050 return -1;
8051 }
8052
8053 SharedUserSetting getSharedUserLP(String name,
8054 int pkgFlags, boolean create) {
8055 SharedUserSetting s = mSharedUsers.get(name);
8056 if (s == null) {
8057 if (!create) {
8058 return null;
8059 }
8060 s = new SharedUserSetting(name, pkgFlags);
8061 if (MULTIPLE_APPLICATION_UIDS) {
8062 s.userId = newUserIdLP(s);
8063 } else {
8064 s.userId = FIRST_APPLICATION_UID;
8065 }
8066 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
8067 // < 0 means we couldn't assign a userid; fall out and return
8068 // s, which is currently null
8069 if (s.userId >= 0) {
8070 mSharedUsers.put(name, s);
8071 }
8072 }
8073
8074 return s;
8075 }
8076
8077 int disableSystemPackageLP(String name) {
8078 PackageSetting p = mPackages.get(name);
8079 if(p == null) {
8080 Log.w(TAG, "Package:"+name+" is not an installed package");
8081 return -1;
8082 }
8083 PackageSetting dp = mDisabledSysPackages.get(name);
8084 // always make sure the system package code and resource paths dont change
8085 if(dp == null) {
8086 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8087 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8088 }
8089 mDisabledSysPackages.put(name, p);
8090 }
8091 return removePackageLP(name);
8092 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008094 PackageSetting enableSystemPackageLP(String name) {
8095 PackageSetting p = mDisabledSysPackages.get(name);
8096 if(p == null) {
8097 Log.w(TAG, "Package:"+name+" is not disabled");
8098 return null;
8099 }
8100 // Reset flag in ApplicationInfo object
8101 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8102 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8103 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008104 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008105 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008106 mDisabledSysPackages.remove(name);
8107 return ret;
8108 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008109
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008110 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008111 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008112 PackageSetting p = mPackages.get(name);
8113 if (p != null) {
8114 if (p.userId == uid) {
8115 return p;
8116 }
8117 reportSettingsProblem(Log.ERROR,
8118 "Adding duplicate package, keeping first: " + name);
8119 return null;
8120 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008121 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008122 p.userId = uid;
8123 if (addUserIdLP(uid, p, name)) {
8124 mPackages.put(name, p);
8125 return p;
8126 }
8127 return null;
8128 }
8129
8130 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8131 SharedUserSetting s = mSharedUsers.get(name);
8132 if (s != null) {
8133 if (s.userId == uid) {
8134 return s;
8135 }
8136 reportSettingsProblem(Log.ERROR,
8137 "Adding duplicate shared user, keeping first: " + name);
8138 return null;
8139 }
8140 s = new SharedUserSetting(name, pkgFlags);
8141 s.userId = uid;
8142 if (addUserIdLP(uid, s, name)) {
8143 mSharedUsers.put(name, s);
8144 return s;
8145 }
8146 return null;
8147 }
8148
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008149 // Transfer ownership of permissions from one package to another.
8150 private void transferPermissions(String origPkg, String newPkg) {
8151 // Transfer ownership of permissions to the new package.
8152 for (int i=0; i<2; i++) {
8153 HashMap<String, BasePermission> permissions =
8154 i == 0 ? mPermissionTrees : mPermissions;
8155 for (BasePermission bp : permissions.values()) {
8156 if (origPkg.equals(bp.sourcePackage)) {
8157 if (DEBUG_UPGRADE) Log.v(TAG,
8158 "Moving permission " + bp.name
8159 + " from pkg " + bp.sourcePackage
8160 + " to " + newPkg);
8161 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008162 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008163 bp.perm = null;
8164 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008165 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008166 }
8167 bp.uid = 0;
8168 bp.gids = null;
8169 }
8170 }
8171 }
8172 }
8173
8174 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008175 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008176 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008177 PackageSetting p = mPackages.get(name);
8178 if (p != null) {
8179 if (!p.codePath.equals(codePath)) {
8180 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008181 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008182 // This is an updated system app with versions in both system
8183 // and data partition. Just let the most recent version
8184 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008185 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008186 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008187 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008188 // Just a change in the code path is not an issue, but
8189 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008190 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008191 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008192 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008193 }
8194 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008195 reportSettingsProblem(Log.WARN,
8196 "Package " + name + " shared user changed from "
8197 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8198 + " to "
8199 + (sharedUser != null ? sharedUser.name : "<nothing>")
8200 + "; replacing with new");
8201 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008202 } else {
8203 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8204 // If what we are scanning is a system package, then
8205 // make it so, regardless of whether it was previously
8206 // installed only in the data partition.
8207 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008209 }
8210 }
8211 if (p == null) {
8212 // Create a new PackageSettings entry. this can end up here because
8213 // of code path mismatch or user id mismatch of an updated system partition
8214 if (!create) {
8215 return null;
8216 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008217 if (origPackage != null) {
8218 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008219 p = new PackageSetting(origPackage.name, name, codePath,
8220 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008221 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8222 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008223 // Note that we will retain the new package's signature so
8224 // that we can keep its data.
8225 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008226 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008227 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008228 p.sharedUser = origPackage.sharedUser;
8229 p.userId = origPackage.userId;
8230 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008231 mRenamedPackages.put(name, origPackage.name);
8232 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008233 // Update new package state.
8234 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008235 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008236 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008237 p.setTimeStamp(codePath.lastModified());
8238 p.sharedUser = sharedUser;
8239 if (sharedUser != null) {
8240 p.userId = sharedUser.userId;
8241 } else if (MULTIPLE_APPLICATION_UIDS) {
8242 // Clone the setting here for disabled system packages
8243 PackageSetting dis = mDisabledSysPackages.get(name);
8244 if (dis != null) {
8245 // For disabled packages a new setting is created
8246 // from the existing user id. This still has to be
8247 // added to list of user id's
8248 // Copy signatures from previous setting
8249 if (dis.signatures.mSignatures != null) {
8250 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8251 }
8252 p.userId = dis.userId;
8253 // Clone permissions
8254 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008255 // Clone component info
8256 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8257 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8258 // Add new setting to list of user ids
8259 addUserIdLP(p.userId, p, name);
8260 } else {
8261 // Assign new user id
8262 p.userId = newUserIdLP(p);
8263 }
8264 } else {
8265 p.userId = FIRST_APPLICATION_UID;
8266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008267 }
8268 if (p.userId < 0) {
8269 reportSettingsProblem(Log.WARN,
8270 "Package " + name + " could not be assigned a valid uid");
8271 return null;
8272 }
8273 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008274 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008275 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008276 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008277 }
8278 }
8279 return p;
8280 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008281
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008282 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008283 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008284 pkg.mSetEnabled = p.enabled;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008285 String codePath = pkg.applicationInfo.sourceDir;
8286 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008287 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008288 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008289 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008290 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008291 p.codePath = new File(codePath);
8292 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008293 }
8294 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008295 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008296 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008297 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008298 p.resourcePath = new File(resourcePath);
8299 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008300 }
8301 // Update version code if needed
8302 if (pkg.mVersionCode != p.versionCode) {
8303 p.versionCode = pkg.mVersionCode;
8304 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008305 // Update signatures if needed.
8306 if (p.signatures.mSignatures == null) {
8307 p.signatures.assignSignatures(pkg.mSignatures);
8308 }
8309 // If this app defines a shared user id initialize
8310 // the shared user signatures as well.
8311 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8312 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8313 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008314 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8315 }
8316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008317 // Utility method that adds a PackageSetting to mPackages and
8318 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008319 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008320 SharedUserSetting sharedUser) {
8321 mPackages.put(name, p);
8322 if (sharedUser != null) {
8323 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8324 reportSettingsProblem(Log.ERROR,
8325 "Package " + p.name + " was user "
8326 + p.sharedUser + " but is now " + sharedUser
8327 + "; I am not changing its files so it will probably fail!");
8328 p.sharedUser.packages.remove(p);
8329 } else if (p.userId != sharedUser.userId) {
8330 reportSettingsProblem(Log.ERROR,
8331 "Package " + p.name + " was user id " + p.userId
8332 + " but is now user " + sharedUser
8333 + " with id " + sharedUser.userId
8334 + "; I am not changing its files so it will probably fail!");
8335 }
8336
8337 sharedUser.packages.add(p);
8338 p.sharedUser = sharedUser;
8339 p.userId = sharedUser.userId;
8340 }
8341 }
8342
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008343 /*
8344 * Update the shared user setting when a package using
8345 * specifying the shared user id is removed. The gids
8346 * associated with each permission of the deleted package
8347 * are removed from the shared user's gid list only if its
8348 * not in use by other permissions of packages in the
8349 * shared user setting.
8350 */
8351 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008352 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008353 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008354 return;
8355 }
8356 // No sharedUserId
8357 if (deletedPs.sharedUser == null) {
8358 return;
8359 }
8360 SharedUserSetting sus = deletedPs.sharedUser;
8361 // Update permissions
8362 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8363 boolean used = false;
8364 if (!sus.grantedPermissions.contains (eachPerm)) {
8365 continue;
8366 }
8367 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008368 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008369 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008370 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008371 used = true;
8372 break;
8373 }
8374 }
8375 if (!used) {
8376 // can safely delete this permission from list
8377 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008378 }
8379 }
8380 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008381 int newGids[] = globalGids;
8382 for (String eachPerm : sus.grantedPermissions) {
8383 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008384 if (bp != null) {
8385 newGids = appendInts(newGids, bp.gids);
8386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008387 }
8388 sus.gids = newGids;
8389 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008391 private int removePackageLP(String name) {
8392 PackageSetting p = mPackages.get(name);
8393 if (p != null) {
8394 mPackages.remove(name);
8395 if (p.sharedUser != null) {
8396 p.sharedUser.packages.remove(p);
8397 if (p.sharedUser.packages.size() == 0) {
8398 mSharedUsers.remove(p.sharedUser.name);
8399 removeUserIdLP(p.sharedUser.userId);
8400 return p.sharedUser.userId;
8401 }
8402 } else {
8403 removeUserIdLP(p.userId);
8404 return p.userId;
8405 }
8406 }
8407 return -1;
8408 }
8409
8410 private boolean addUserIdLP(int uid, Object obj, Object name) {
8411 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8412 return false;
8413 }
8414
8415 if (uid >= FIRST_APPLICATION_UID) {
8416 int N = mUserIds.size();
8417 final int index = uid - FIRST_APPLICATION_UID;
8418 while (index >= N) {
8419 mUserIds.add(null);
8420 N++;
8421 }
8422 if (mUserIds.get(index) != null) {
8423 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008424 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008425 + " name=" + name);
8426 return false;
8427 }
8428 mUserIds.set(index, obj);
8429 } else {
8430 if (mOtherUserIds.get(uid) != null) {
8431 reportSettingsProblem(Log.ERROR,
8432 "Adding duplicate shared id: " + uid
8433 + " name=" + name);
8434 return false;
8435 }
8436 mOtherUserIds.put(uid, obj);
8437 }
8438 return true;
8439 }
8440
8441 public Object getUserIdLP(int uid) {
8442 if (uid >= FIRST_APPLICATION_UID) {
8443 int N = mUserIds.size();
8444 final int index = uid - FIRST_APPLICATION_UID;
8445 return index < N ? mUserIds.get(index) : null;
8446 } else {
8447 return mOtherUserIds.get(uid);
8448 }
8449 }
8450
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008451 private Set<String> findPackagesWithFlag(int flag) {
8452 Set<String> ret = new HashSet<String>();
8453 for (PackageSetting ps : mPackages.values()) {
8454 // Has to match atleast all the flag bits set on flag
8455 if ((ps.pkgFlags & flag) == flag) {
8456 ret.add(ps.name);
8457 }
8458 }
8459 return ret;
8460 }
8461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008462 private void removeUserIdLP(int uid) {
8463 if (uid >= FIRST_APPLICATION_UID) {
8464 int N = mUserIds.size();
8465 final int index = uid - FIRST_APPLICATION_UID;
8466 if (index < N) mUserIds.set(index, null);
8467 } else {
8468 mOtherUserIds.remove(uid);
8469 }
8470 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008472 void writeLP() {
8473 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8474
8475 // Keep the old settings around until we know the new ones have
8476 // been successfully written.
8477 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008478 // Presence of backup settings file indicates that we failed
8479 // to persist settings earlier. So preserve the older
8480 // backup for future reference since the current settings
8481 // might have been corrupted.
8482 if (!mBackupSettingsFilename.exists()) {
8483 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008484 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008485 return;
8486 }
8487 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008488 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008489 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008490 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008491 }
8492
8493 mPastSignatures.clear();
8494
8495 try {
8496 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8497
8498 //XmlSerializer serializer = XmlUtils.serializerInstance();
8499 XmlSerializer serializer = new FastXmlSerializer();
8500 serializer.setOutput(str, "utf-8");
8501 serializer.startDocument(null, true);
8502 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8503
8504 serializer.startTag(null, "packages");
8505
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008506 serializer.startTag(null, "last-platform-version");
8507 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8508 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8509 serializer.endTag(null, "last-platform-version");
8510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008511 serializer.startTag(null, "permission-trees");
8512 for (BasePermission bp : mPermissionTrees.values()) {
8513 writePermission(serializer, bp);
8514 }
8515 serializer.endTag(null, "permission-trees");
8516
8517 serializer.startTag(null, "permissions");
8518 for (BasePermission bp : mPermissions.values()) {
8519 writePermission(serializer, bp);
8520 }
8521 serializer.endTag(null, "permissions");
8522
8523 for (PackageSetting pkg : mPackages.values()) {
8524 writePackage(serializer, pkg);
8525 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008527 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8528 writeDisabledSysPackage(serializer, pkg);
8529 }
8530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008531 serializer.startTag(null, "preferred-activities");
8532 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8533 serializer.startTag(null, "item");
8534 pa.writeToXml(serializer);
8535 serializer.endTag(null, "item");
8536 }
8537 serializer.endTag(null, "preferred-activities");
8538
8539 for (SharedUserSetting usr : mSharedUsers.values()) {
8540 serializer.startTag(null, "shared-user");
8541 serializer.attribute(null, "name", usr.name);
8542 serializer.attribute(null, "userId",
8543 Integer.toString(usr.userId));
8544 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8545 serializer.startTag(null, "perms");
8546 for (String name : usr.grantedPermissions) {
8547 serializer.startTag(null, "item");
8548 serializer.attribute(null, "name", name);
8549 serializer.endTag(null, "item");
8550 }
8551 serializer.endTag(null, "perms");
8552 serializer.endTag(null, "shared-user");
8553 }
8554
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008555 if (mPackagesToBeCleaned.size() > 0) {
8556 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8557 serializer.startTag(null, "cleaning-package");
8558 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8559 serializer.endTag(null, "cleaning-package");
8560 }
8561 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008562
8563 if (mRenamedPackages.size() > 0) {
8564 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8565 serializer.startTag(null, "renamed-package");
8566 serializer.attribute(null, "new", e.getKey());
8567 serializer.attribute(null, "old", e.getValue());
8568 serializer.endTag(null, "renamed-package");
8569 }
8570 }
8571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008572 serializer.endTag(null, "packages");
8573
8574 serializer.endDocument();
8575
8576 str.flush();
8577 str.close();
8578
8579 // New settings successfully written, old ones are no longer
8580 // needed.
8581 mBackupSettingsFilename.delete();
8582 FileUtils.setPermissions(mSettingsFilename.toString(),
8583 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8584 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8585 |FileUtils.S_IROTH,
8586 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008587
8588 // Write package list file now, use a JournaledFile.
8589 //
8590 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8591 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8592
8593 str = new FileOutputStream(journal.chooseForWrite());
8594 try {
8595 StringBuilder sb = new StringBuilder();
8596 for (PackageSetting pkg : mPackages.values()) {
8597 ApplicationInfo ai = pkg.pkg.applicationInfo;
8598 String dataPath = ai.dataDir;
8599 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8600
8601 // Avoid any application that has a space in its path
8602 // or that is handled by the system.
8603 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8604 continue;
8605
8606 // we store on each line the following information for now:
8607 //
8608 // pkgName - package name
8609 // userId - application-specific user id
8610 // debugFlag - 0 or 1 if the package is debuggable.
8611 // dataPath - path to package's data path
8612 //
8613 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8614 //
8615 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8616 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8617 // system/core/run-as/run-as.c
8618 //
8619 sb.setLength(0);
8620 sb.append(ai.packageName);
8621 sb.append(" ");
8622 sb.append((int)ai.uid);
8623 sb.append(isDebug ? " 1 " : " 0 ");
8624 sb.append(dataPath);
8625 sb.append("\n");
8626 str.write(sb.toString().getBytes());
8627 }
8628 str.flush();
8629 str.close();
8630 journal.commit();
8631 }
8632 catch (Exception e) {
8633 journal.rollback();
8634 }
8635
8636 FileUtils.setPermissions(mPackageListFilename.toString(),
8637 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8638 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8639 |FileUtils.S_IROTH,
8640 -1, -1);
8641
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008642 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008643
8644 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008645 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 -08008646 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008647 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 -08008648 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008649 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008650 if (mSettingsFilename.exists()) {
8651 if (!mSettingsFilename.delete()) {
8652 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8653 }
8654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008655 //Debug.stopMethodTracing();
8656 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008657
8658 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008659 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008660 serializer.startTag(null, "updated-package");
8661 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008662 if (pkg.realName != null) {
8663 serializer.attribute(null, "realName", pkg.realName);
8664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008665 serializer.attribute(null, "codePath", pkg.codePathString);
8666 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008667 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008668 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8669 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8670 }
8671 if (pkg.sharedUser == null) {
8672 serializer.attribute(null, "userId",
8673 Integer.toString(pkg.userId));
8674 } else {
8675 serializer.attribute(null, "sharedUserId",
8676 Integer.toString(pkg.userId));
8677 }
8678 serializer.startTag(null, "perms");
8679 if (pkg.sharedUser == null) {
8680 // If this is a shared user, the permissions will
8681 // be written there. We still need to write an
8682 // empty permissions list so permissionsFixed will
8683 // be set.
8684 for (final String name : pkg.grantedPermissions) {
8685 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008686 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008687 // We only need to write signature or system permissions but this wont
8688 // match the semantics of grantedPermissions. So write all permissions.
8689 serializer.startTag(null, "item");
8690 serializer.attribute(null, "name", name);
8691 serializer.endTag(null, "item");
8692 }
8693 }
8694 }
8695 serializer.endTag(null, "perms");
8696 serializer.endTag(null, "updated-package");
8697 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008698
8699 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008700 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008701 serializer.startTag(null, "package");
8702 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008703 if (pkg.realName != null) {
8704 serializer.attribute(null, "realName", pkg.realName);
8705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008706 serializer.attribute(null, "codePath", pkg.codePathString);
8707 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8708 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8709 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008710 serializer.attribute(null, "flags",
8711 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008712 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008713 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008714 if (pkg.sharedUser == null) {
8715 serializer.attribute(null, "userId",
8716 Integer.toString(pkg.userId));
8717 } else {
8718 serializer.attribute(null, "sharedUserId",
8719 Integer.toString(pkg.userId));
8720 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008721 if (pkg.uidError) {
8722 serializer.attribute(null, "uidError", "true");
8723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008724 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8725 serializer.attribute(null, "enabled",
8726 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8727 ? "true" : "false");
8728 }
8729 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8730 serializer.attribute(null, "installStatus", "false");
8731 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008732 if (pkg.installerPackageName != null) {
8733 serializer.attribute(null, "installer", pkg.installerPackageName);
8734 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008735 if (pkg.obbPathString != null) {
8736 serializer.attribute(null, "obbPath", pkg.obbPathString);
8737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008738 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8739 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8740 serializer.startTag(null, "perms");
8741 if (pkg.sharedUser == null) {
8742 // If this is a shared user, the permissions will
8743 // be written there. We still need to write an
8744 // empty permissions list so permissionsFixed will
8745 // be set.
8746 for (final String name : pkg.grantedPermissions) {
8747 serializer.startTag(null, "item");
8748 serializer.attribute(null, "name", name);
8749 serializer.endTag(null, "item");
8750 }
8751 }
8752 serializer.endTag(null, "perms");
8753 }
8754 if (pkg.disabledComponents.size() > 0) {
8755 serializer.startTag(null, "disabled-components");
8756 for (final String name : pkg.disabledComponents) {
8757 serializer.startTag(null, "item");
8758 serializer.attribute(null, "name", name);
8759 serializer.endTag(null, "item");
8760 }
8761 serializer.endTag(null, "disabled-components");
8762 }
8763 if (pkg.enabledComponents.size() > 0) {
8764 serializer.startTag(null, "enabled-components");
8765 for (final String name : pkg.enabledComponents) {
8766 serializer.startTag(null, "item");
8767 serializer.attribute(null, "name", name);
8768 serializer.endTag(null, "item");
8769 }
8770 serializer.endTag(null, "enabled-components");
8771 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008773 serializer.endTag(null, "package");
8774 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008776 void writePermission(XmlSerializer serializer, BasePermission bp)
8777 throws XmlPullParserException, java.io.IOException {
8778 if (bp.type != BasePermission.TYPE_BUILTIN
8779 && bp.sourcePackage != null) {
8780 serializer.startTag(null, "item");
8781 serializer.attribute(null, "name", bp.name);
8782 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008783 if (bp.protectionLevel !=
8784 PermissionInfo.PROTECTION_NORMAL) {
8785 serializer.attribute(null, "protection",
8786 Integer.toString(bp.protectionLevel));
8787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008788 if (DEBUG_SETTINGS) Log.v(TAG,
8789 "Writing perm: name=" + bp.name + " type=" + bp.type);
8790 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8791 PermissionInfo pi = bp.perm != null ? bp.perm.info
8792 : bp.pendingInfo;
8793 if (pi != null) {
8794 serializer.attribute(null, "type", "dynamic");
8795 if (pi.icon != 0) {
8796 serializer.attribute(null, "icon",
8797 Integer.toString(pi.icon));
8798 }
8799 if (pi.nonLocalizedLabel != null) {
8800 serializer.attribute(null, "label",
8801 pi.nonLocalizedLabel.toString());
8802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008803 }
8804 }
8805 serializer.endTag(null, "item");
8806 }
8807 }
8808
8809 String getReadMessagesLP() {
8810 return mReadMessages.toString();
8811 }
8812
Oscar Montemayora8529f62009-11-18 10:14:20 -08008813 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008814 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8815 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008816 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008817 while(its.hasNext()) {
8818 String key = its.next();
8819 PackageSetting ps = mPackages.get(key);
8820 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008821 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008822 }
8823 }
8824 return ret;
8825 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008827 boolean readLP() {
8828 FileInputStream str = null;
8829 if (mBackupSettingsFilename.exists()) {
8830 try {
8831 str = new FileInputStream(mBackupSettingsFilename);
8832 mReadMessages.append("Reading from backup settings file\n");
8833 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008834 if (mSettingsFilename.exists()) {
8835 // If both the backup and settings file exist, we
8836 // ignore the settings since it might have been
8837 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008838 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008839 mSettingsFilename.delete();
8840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008841 } catch (java.io.IOException e) {
8842 // We'll try for the normal settings file.
8843 }
8844 }
8845
8846 mPastSignatures.clear();
8847
8848 try {
8849 if (str == null) {
8850 if (!mSettingsFilename.exists()) {
8851 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008852 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008853 return false;
8854 }
8855 str = new FileInputStream(mSettingsFilename);
8856 }
8857 XmlPullParser parser = Xml.newPullParser();
8858 parser.setInput(str, null);
8859
8860 int type;
8861 while ((type=parser.next()) != XmlPullParser.START_TAG
8862 && type != XmlPullParser.END_DOCUMENT) {
8863 ;
8864 }
8865
8866 if (type != XmlPullParser.START_TAG) {
8867 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008868 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008869 return false;
8870 }
8871
8872 int outerDepth = parser.getDepth();
8873 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8874 && (type != XmlPullParser.END_TAG
8875 || parser.getDepth() > outerDepth)) {
8876 if (type == XmlPullParser.END_TAG
8877 || type == XmlPullParser.TEXT) {
8878 continue;
8879 }
8880
8881 String tagName = parser.getName();
8882 if (tagName.equals("package")) {
8883 readPackageLP(parser);
8884 } else if (tagName.equals("permissions")) {
8885 readPermissionsLP(mPermissions, parser);
8886 } else if (tagName.equals("permission-trees")) {
8887 readPermissionsLP(mPermissionTrees, parser);
8888 } else if (tagName.equals("shared-user")) {
8889 readSharedUserLP(parser);
8890 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008891 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008892 } else if (tagName.equals("preferred-activities")) {
8893 readPreferredActivitiesLP(parser);
8894 } else if(tagName.equals("updated-package")) {
8895 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008896 } else if (tagName.equals("cleaning-package")) {
8897 String name = parser.getAttributeValue(null, "name");
8898 if (name != null) {
8899 mPackagesToBeCleaned.add(name);
8900 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008901 } else if (tagName.equals("renamed-package")) {
8902 String nname = parser.getAttributeValue(null, "new");
8903 String oname = parser.getAttributeValue(null, "old");
8904 if (nname != null && oname != null) {
8905 mRenamedPackages.put(nname, oname);
8906 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008907 } else if (tagName.equals("last-platform-version")) {
8908 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8909 try {
8910 String internal = parser.getAttributeValue(null, "internal");
8911 if (internal != null) {
8912 mInternalSdkPlatform = Integer.parseInt(internal);
8913 }
8914 String external = parser.getAttributeValue(null, "external");
8915 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008916 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008917 }
8918 } catch (NumberFormatException e) {
8919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008920 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008921 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008922 + parser.getName());
8923 XmlUtils.skipCurrentTag(parser);
8924 }
8925 }
8926
8927 str.close();
8928
8929 } catch(XmlPullParserException e) {
8930 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008931 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008932
8933 } catch(java.io.IOException e) {
8934 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008935 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008936
8937 }
8938
8939 int N = mPendingPackages.size();
8940 for (int i=0; i<N; i++) {
8941 final PendingPackage pp = mPendingPackages.get(i);
8942 Object idObj = getUserIdLP(pp.sharedId);
8943 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008944 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008945 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008946 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008947 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008948 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008949 + pp.name);
8950 continue;
8951 }
8952 p.copyFrom(pp);
8953 } else if (idObj != null) {
8954 String msg = "Bad package setting: package " + pp.name
8955 + " has shared uid " + pp.sharedId
8956 + " that is not a shared uid\n";
8957 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008958 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008959 } else {
8960 String msg = "Bad package setting: package " + pp.name
8961 + " has shared uid " + pp.sharedId
8962 + " that is not defined\n";
8963 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008964 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008965 }
8966 }
8967 mPendingPackages.clear();
8968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008969 mReadMessages.append("Read completed successfully: "
8970 + mPackages.size() + " packages, "
8971 + mSharedUsers.size() + " shared uids\n");
8972
8973 return true;
8974 }
8975
8976 private int readInt(XmlPullParser parser, String ns, String name,
8977 int defValue) {
8978 String v = parser.getAttributeValue(ns, name);
8979 try {
8980 if (v == null) {
8981 return defValue;
8982 }
8983 return Integer.parseInt(v);
8984 } catch (NumberFormatException e) {
8985 reportSettingsProblem(Log.WARN,
8986 "Error in package manager settings: attribute " +
8987 name + " has bad integer value " + v + " at "
8988 + parser.getPositionDescription());
8989 }
8990 return defValue;
8991 }
8992
8993 private void readPermissionsLP(HashMap<String, BasePermission> out,
8994 XmlPullParser parser)
8995 throws IOException, XmlPullParserException {
8996 int outerDepth = parser.getDepth();
8997 int type;
8998 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8999 && (type != XmlPullParser.END_TAG
9000 || parser.getDepth() > outerDepth)) {
9001 if (type == XmlPullParser.END_TAG
9002 || type == XmlPullParser.TEXT) {
9003 continue;
9004 }
9005
9006 String tagName = parser.getName();
9007 if (tagName.equals("item")) {
9008 String name = parser.getAttributeValue(null, "name");
9009 String sourcePackage = parser.getAttributeValue(null, "package");
9010 String ptype = parser.getAttributeValue(null, "type");
9011 if (name != null && sourcePackage != null) {
9012 boolean dynamic = "dynamic".equals(ptype);
9013 BasePermission bp = new BasePermission(name, sourcePackage,
9014 dynamic
9015 ? BasePermission.TYPE_DYNAMIC
9016 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009017 bp.protectionLevel = readInt(parser, null, "protection",
9018 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009019 if (dynamic) {
9020 PermissionInfo pi = new PermissionInfo();
9021 pi.packageName = sourcePackage.intern();
9022 pi.name = name.intern();
9023 pi.icon = readInt(parser, null, "icon", 0);
9024 pi.nonLocalizedLabel = parser.getAttributeValue(
9025 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009026 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009027 bp.pendingInfo = pi;
9028 }
9029 out.put(bp.name, bp);
9030 } else {
9031 reportSettingsProblem(Log.WARN,
9032 "Error in package manager settings: permissions has"
9033 + " no name at " + parser.getPositionDescription());
9034 }
9035 } else {
9036 reportSettingsProblem(Log.WARN,
9037 "Unknown element reading permissions: "
9038 + parser.getName() + " at "
9039 + parser.getPositionDescription());
9040 }
9041 XmlUtils.skipCurrentTag(parser);
9042 }
9043 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009045 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009046 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009047 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009048 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009049 String codePathStr = parser.getAttributeValue(null, "codePath");
9050 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009051 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009052 resourcePathStr = codePathStr;
9053 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009054 String version = parser.getAttributeValue(null, "version");
9055 int versionCode = 0;
9056 if (version != null) {
9057 try {
9058 versionCode = Integer.parseInt(version);
9059 } catch (NumberFormatException e) {
9060 }
9061 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009063 int pkgFlags = 0;
9064 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009065 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009066 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009067 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009068 String timeStampStr = parser.getAttributeValue(null, "ts");
9069 if (timeStampStr != null) {
9070 try {
9071 long timeStamp = Long.parseLong(timeStampStr);
9072 ps.setTimeStamp(timeStamp, timeStampStr);
9073 } catch (NumberFormatException e) {
9074 }
9075 }
9076 String idStr = parser.getAttributeValue(null, "userId");
9077 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
9078 if(ps.userId <= 0) {
9079 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9080 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
9081 }
9082 int outerDepth = parser.getDepth();
9083 int type;
9084 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9085 && (type != XmlPullParser.END_TAG
9086 || parser.getDepth() > outerDepth)) {
9087 if (type == XmlPullParser.END_TAG
9088 || type == XmlPullParser.TEXT) {
9089 continue;
9090 }
9091
9092 String tagName = parser.getName();
9093 if (tagName.equals("perms")) {
9094 readGrantedPermissionsLP(parser,
9095 ps.grantedPermissions);
9096 } else {
9097 reportSettingsProblem(Log.WARN,
9098 "Unknown element under <updated-package>: "
9099 + parser.getName());
9100 XmlUtils.skipCurrentTag(parser);
9101 }
9102 }
9103 mDisabledSysPackages.put(name, ps);
9104 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009106 private void readPackageLP(XmlPullParser parser)
9107 throws XmlPullParserException, IOException {
9108 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009109 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009110 String idStr = null;
9111 String sharedIdStr = null;
9112 String codePathStr = null;
9113 String resourcePathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07009114 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009115 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009116 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009117 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009118 int pkgFlags = 0;
9119 String timeStampStr;
9120 long timeStamp = 0;
9121 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009122 String version = null;
9123 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009124 try {
9125 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009126 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009127 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009128 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009129 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9130 codePathStr = parser.getAttributeValue(null, "codePath");
9131 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root93565c4b2010-06-18 15:46:06 -07009132 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009133 version = parser.getAttributeValue(null, "version");
9134 if (version != null) {
9135 try {
9136 versionCode = Integer.parseInt(version);
9137 } catch (NumberFormatException e) {
9138 }
9139 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009140 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009141
9142 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009143 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009144 try {
9145 pkgFlags = Integer.parseInt(systemStr);
9146 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009147 }
9148 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009149 // For backward compatibility
9150 systemStr = parser.getAttributeValue(null, "system");
9151 if (systemStr != null) {
9152 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9153 } else {
9154 // Old settings that don't specify system... just treat
9155 // them as system, good enough.
9156 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9157 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009158 }
9159 timeStampStr = parser.getAttributeValue(null, "ts");
9160 if (timeStampStr != null) {
9161 try {
9162 timeStamp = Long.parseLong(timeStampStr);
9163 } catch (NumberFormatException e) {
9164 }
9165 }
9166 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9167 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9168 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9169 if (resourcePathStr == null) {
9170 resourcePathStr = codePathStr;
9171 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009172 if (realName != null) {
9173 realName = realName.intern();
9174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009175 if (name == null) {
9176 reportSettingsProblem(Log.WARN,
9177 "Error in package manager settings: <package> has no name at "
9178 + parser.getPositionDescription());
9179 } else if (codePathStr == null) {
9180 reportSettingsProblem(Log.WARN,
9181 "Error in package manager settings: <package> has no codePath at "
9182 + parser.getPositionDescription());
9183 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009184 packageSetting = addPackageLP(name.intern(), realName,
9185 new File(codePathStr), new File(resourcePathStr),
9186 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009187 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9188 + ": userId=" + userId + " pkg=" + packageSetting);
9189 if (packageSetting == null) {
9190 reportSettingsProblem(Log.ERROR,
9191 "Failure adding uid " + userId
9192 + " while parsing settings at "
9193 + parser.getPositionDescription());
9194 } else {
9195 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9196 }
9197 } else if (sharedIdStr != null) {
9198 userId = sharedIdStr != null
9199 ? Integer.parseInt(sharedIdStr) : 0;
9200 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009201 packageSetting = new PendingPackage(name.intern(), realName,
9202 new File(codePathStr), new File(resourcePathStr),
9203 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009204 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9205 mPendingPackages.add((PendingPackage) packageSetting);
9206 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9207 + ": sharedUserId=" + userId + " pkg="
9208 + packageSetting);
9209 } else {
9210 reportSettingsProblem(Log.WARN,
9211 "Error in package manager settings: package "
9212 + name + " has bad sharedId " + sharedIdStr
9213 + " at " + parser.getPositionDescription());
9214 }
9215 } else {
9216 reportSettingsProblem(Log.WARN,
9217 "Error in package manager settings: package "
9218 + name + " has bad userId " + idStr + " at "
9219 + parser.getPositionDescription());
9220 }
9221 } catch (NumberFormatException e) {
9222 reportSettingsProblem(Log.WARN,
9223 "Error in package manager settings: package "
9224 + name + " has bad userId " + idStr + " at "
9225 + parser.getPositionDescription());
9226 }
9227 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009228 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009229 packageSetting.installerPackageName = installerPackageName;
Kenny Root93565c4b2010-06-18 15:46:06 -07009230 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009231 final String enabledStr = parser.getAttributeValue(null, "enabled");
9232 if (enabledStr != null) {
9233 if (enabledStr.equalsIgnoreCase("true")) {
9234 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9235 } else if (enabledStr.equalsIgnoreCase("false")) {
9236 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9237 } else if (enabledStr.equalsIgnoreCase("default")) {
9238 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9239 } else {
9240 reportSettingsProblem(Log.WARN,
9241 "Error in package manager settings: package "
9242 + name + " has bad enabled value: " + idStr
9243 + " at " + parser.getPositionDescription());
9244 }
9245 } else {
9246 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9247 }
9248 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9249 if (installStatusStr != null) {
9250 if (installStatusStr.equalsIgnoreCase("false")) {
9251 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9252 } else {
9253 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9254 }
9255 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009257 int outerDepth = parser.getDepth();
9258 int type;
9259 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9260 && (type != XmlPullParser.END_TAG
9261 || parser.getDepth() > outerDepth)) {
9262 if (type == XmlPullParser.END_TAG
9263 || type == XmlPullParser.TEXT) {
9264 continue;
9265 }
9266
9267 String tagName = parser.getName();
9268 if (tagName.equals("disabled-components")) {
9269 readDisabledComponentsLP(packageSetting, parser);
9270 } else if (tagName.equals("enabled-components")) {
9271 readEnabledComponentsLP(packageSetting, parser);
9272 } else if (tagName.equals("sigs")) {
9273 packageSetting.signatures.readXml(parser, mPastSignatures);
9274 } else if (tagName.equals("perms")) {
9275 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009276 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009277 packageSetting.permissionsFixed = true;
9278 } else {
9279 reportSettingsProblem(Log.WARN,
9280 "Unknown element under <package>: "
9281 + parser.getName());
9282 XmlUtils.skipCurrentTag(parser);
9283 }
9284 }
9285 } else {
9286 XmlUtils.skipCurrentTag(parser);
9287 }
9288 }
9289
9290 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9291 XmlPullParser parser)
9292 throws IOException, XmlPullParserException {
9293 int outerDepth = parser.getDepth();
9294 int type;
9295 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9296 && (type != XmlPullParser.END_TAG
9297 || parser.getDepth() > outerDepth)) {
9298 if (type == XmlPullParser.END_TAG
9299 || type == XmlPullParser.TEXT) {
9300 continue;
9301 }
9302
9303 String tagName = parser.getName();
9304 if (tagName.equals("item")) {
9305 String name = parser.getAttributeValue(null, "name");
9306 if (name != null) {
9307 packageSetting.disabledComponents.add(name.intern());
9308 } else {
9309 reportSettingsProblem(Log.WARN,
9310 "Error in package manager settings: <disabled-components> has"
9311 + " no name at " + parser.getPositionDescription());
9312 }
9313 } else {
9314 reportSettingsProblem(Log.WARN,
9315 "Unknown element under <disabled-components>: "
9316 + parser.getName());
9317 }
9318 XmlUtils.skipCurrentTag(parser);
9319 }
9320 }
9321
9322 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9323 XmlPullParser parser)
9324 throws IOException, XmlPullParserException {
9325 int outerDepth = parser.getDepth();
9326 int type;
9327 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9328 && (type != XmlPullParser.END_TAG
9329 || parser.getDepth() > outerDepth)) {
9330 if (type == XmlPullParser.END_TAG
9331 || type == XmlPullParser.TEXT) {
9332 continue;
9333 }
9334
9335 String tagName = parser.getName();
9336 if (tagName.equals("item")) {
9337 String name = parser.getAttributeValue(null, "name");
9338 if (name != null) {
9339 packageSetting.enabledComponents.add(name.intern());
9340 } else {
9341 reportSettingsProblem(Log.WARN,
9342 "Error in package manager settings: <enabled-components> has"
9343 + " no name at " + parser.getPositionDescription());
9344 }
9345 } else {
9346 reportSettingsProblem(Log.WARN,
9347 "Unknown element under <enabled-components>: "
9348 + parser.getName());
9349 }
9350 XmlUtils.skipCurrentTag(parser);
9351 }
9352 }
9353
9354 private void readSharedUserLP(XmlPullParser parser)
9355 throws XmlPullParserException, IOException {
9356 String name = null;
9357 String idStr = null;
9358 int pkgFlags = 0;
9359 SharedUserSetting su = null;
9360 try {
9361 name = parser.getAttributeValue(null, "name");
9362 idStr = parser.getAttributeValue(null, "userId");
9363 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9364 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9365 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9366 }
9367 if (name == null) {
9368 reportSettingsProblem(Log.WARN,
9369 "Error in package manager settings: <shared-user> has no name at "
9370 + parser.getPositionDescription());
9371 } else if (userId == 0) {
9372 reportSettingsProblem(Log.WARN,
9373 "Error in package manager settings: shared-user "
9374 + name + " has bad userId " + idStr + " at "
9375 + parser.getPositionDescription());
9376 } else {
9377 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9378 reportSettingsProblem(Log.ERROR,
9379 "Occurred while parsing settings at "
9380 + parser.getPositionDescription());
9381 }
9382 }
9383 } catch (NumberFormatException e) {
9384 reportSettingsProblem(Log.WARN,
9385 "Error in package manager settings: package "
9386 + name + " has bad userId " + idStr + " at "
9387 + parser.getPositionDescription());
9388 };
9389
9390 if (su != null) {
9391 int outerDepth = parser.getDepth();
9392 int type;
9393 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9394 && (type != XmlPullParser.END_TAG
9395 || parser.getDepth() > outerDepth)) {
9396 if (type == XmlPullParser.END_TAG
9397 || type == XmlPullParser.TEXT) {
9398 continue;
9399 }
9400
9401 String tagName = parser.getName();
9402 if (tagName.equals("sigs")) {
9403 su.signatures.readXml(parser, mPastSignatures);
9404 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009405 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009406 } else {
9407 reportSettingsProblem(Log.WARN,
9408 "Unknown element under <shared-user>: "
9409 + parser.getName());
9410 XmlUtils.skipCurrentTag(parser);
9411 }
9412 }
9413
9414 } else {
9415 XmlUtils.skipCurrentTag(parser);
9416 }
9417 }
9418
9419 private void readGrantedPermissionsLP(XmlPullParser parser,
9420 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9421 int outerDepth = parser.getDepth();
9422 int type;
9423 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9424 && (type != XmlPullParser.END_TAG
9425 || parser.getDepth() > outerDepth)) {
9426 if (type == XmlPullParser.END_TAG
9427 || type == XmlPullParser.TEXT) {
9428 continue;
9429 }
9430
9431 String tagName = parser.getName();
9432 if (tagName.equals("item")) {
9433 String name = parser.getAttributeValue(null, "name");
9434 if (name != null) {
9435 outPerms.add(name.intern());
9436 } else {
9437 reportSettingsProblem(Log.WARN,
9438 "Error in package manager settings: <perms> has"
9439 + " no name at " + parser.getPositionDescription());
9440 }
9441 } else {
9442 reportSettingsProblem(Log.WARN,
9443 "Unknown element under <perms>: "
9444 + parser.getName());
9445 }
9446 XmlUtils.skipCurrentTag(parser);
9447 }
9448 }
9449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009450 private void readPreferredActivitiesLP(XmlPullParser parser)
9451 throws XmlPullParserException, IOException {
9452 int outerDepth = parser.getDepth();
9453 int type;
9454 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9455 && (type != XmlPullParser.END_TAG
9456 || parser.getDepth() > outerDepth)) {
9457 if (type == XmlPullParser.END_TAG
9458 || type == XmlPullParser.TEXT) {
9459 continue;
9460 }
9461
9462 String tagName = parser.getName();
9463 if (tagName.equals("item")) {
9464 PreferredActivity pa = new PreferredActivity(parser);
9465 if (pa.mParseError == null) {
9466 mPreferredActivities.addFilter(pa);
9467 } else {
9468 reportSettingsProblem(Log.WARN,
9469 "Error in package manager settings: <preferred-activity> "
9470 + pa.mParseError + " at "
9471 + parser.getPositionDescription());
9472 }
9473 } else {
9474 reportSettingsProblem(Log.WARN,
9475 "Unknown element under <preferred-activities>: "
9476 + parser.getName());
9477 XmlUtils.skipCurrentTag(parser);
9478 }
9479 }
9480 }
9481
9482 // Returns -1 if we could not find an available UserId to assign
9483 private int newUserIdLP(Object obj) {
9484 // Let's be stupidly inefficient for now...
9485 final int N = mUserIds.size();
9486 for (int i=0; i<N; i++) {
9487 if (mUserIds.get(i) == null) {
9488 mUserIds.set(i, obj);
9489 return FIRST_APPLICATION_UID + i;
9490 }
9491 }
9492
9493 // None left?
9494 if (N >= MAX_APPLICATION_UIDS) {
9495 return -1;
9496 }
9497
9498 mUserIds.add(obj);
9499 return FIRST_APPLICATION_UID + N;
9500 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009502 public PackageSetting getDisabledSystemPkg(String name) {
9503 synchronized(mPackages) {
9504 PackageSetting ps = mDisabledSysPackages.get(name);
9505 return ps;
9506 }
9507 }
9508
9509 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009510 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9511 return true;
9512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009513 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9514 if (Config.LOGV) {
9515 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9516 + " componentName = " + componentInfo.name);
9517 Log.v(TAG, "enabledComponents: "
9518 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9519 Log.v(TAG, "disabledComponents: "
9520 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9521 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009522 if (packageSettings == null) {
9523 if (false) {
9524 Log.w(TAG, "WAITING FOR DEBUGGER");
9525 Debug.waitForDebugger();
9526 Log.i(TAG, "We will crash!");
9527 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009528 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009529 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009530 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9531 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9532 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9533 return false;
9534 }
9535 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9536 return true;
9537 }
9538 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9539 return false;
9540 }
9541 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009542 }
9543 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009544
9545 // ------- apps on sdcard specific code -------
9546 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009547 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009548 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009549 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009550 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009551
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009552 private String getEncryptKey() {
9553 try {
9554 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9555 if (sdEncKey == null) {
9556 sdEncKey = SystemKeyStore.getInstance().
9557 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9558 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009559 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009560 return null;
9561 }
9562 }
9563 return sdEncKey;
9564 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009565 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009566 return null;
9567 }
9568 }
9569
Kenny Rootc78a8072010-07-27 15:18:38 -07009570 /* package */ static String getTempContainerId() {
9571 int tmpIdx = 1;
9572 String list[] = PackageHelper.getSecureContainerList();
9573 if (list != null) {
9574 for (final String name : list) {
9575 // Ignore null and non-temporary container entries
9576 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9577 continue;
9578 }
9579
9580 String subStr = name.substring(mTempContainerPrefix.length());
9581 try {
9582 int cid = Integer.parseInt(subStr);
9583 if (cid >= tmpIdx) {
9584 tmpIdx = cid + 1;
9585 }
9586 } catch (NumberFormatException e) {
9587 }
9588 }
9589 }
9590 return mTempContainerPrefix + tmpIdx;
9591 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009592
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009593 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009594 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009595 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009596 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9597 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9598 throw new SecurityException("Media status can only be updated by the system");
9599 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009600 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009601 Log.i(TAG, "Updating external media status from " +
9602 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9603 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009604 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9605 mediaStatus+", mMediaMounted=" + mMediaMounted);
9606 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009607 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9608 reportStatus ? 1 : 0, -1);
9609 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009610 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009611 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009612 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009613 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009614 // Queue up an async operation since the package installation may take a little while.
9615 mHandler.post(new Runnable() {
9616 public void run() {
9617 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009618 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009619 }
9620 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009621 }
9622
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009623 /*
9624 * Collect information of applications on external media, map them
9625 * against existing containers and update information based on current
9626 * mount status. Please note that we always have to report status
9627 * if reportStatus has been set to true especially when unloading packages.
9628 */
9629 private void updateExternalMediaStatusInner(boolean mediaStatus,
9630 boolean reportStatus) {
9631 // Collection of uids
9632 int uidArr[] = null;
9633 // Collection of stale containers
9634 HashSet<String> removeCids = new HashSet<String>();
9635 // Collection of packages on external media with valid containers.
9636 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9637 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009638 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009639 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009640 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009641 } else {
9642 // Process list of secure containers and categorize them
9643 // as active or stale based on their package internal state.
9644 int uidList[] = new int[list.length];
9645 int num = 0;
9646 synchronized (mPackages) {
9647 for (String cid : list) {
9648 SdInstallArgs args = new SdInstallArgs(cid);
9649 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009650 String pkgName = args.getPackageName();
9651 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009652 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9653 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009654 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009655 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009656 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9657 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009658 // The package status is changed only if the code path
9659 // matches between settings and the container id.
9660 if (ps != null && ps.codePathString != null &&
9661 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009662 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9663 " corresponds to pkg : " + pkgName +
9664 " at code path: " + ps.codePathString);
9665 // We do have a valid package installed on sdcard
9666 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009667 int uid = ps.userId;
9668 if (uid != -1) {
9669 uidList[num++] = uid;
9670 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009671 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009672 // Stale container on sdcard. Just delete
9673 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9674 removeCids.add(cid);
9675 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009676 }
9677 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009678
9679 if (num > 0) {
9680 // Sort uid list
9681 Arrays.sort(uidList, 0, num);
9682 // Throw away duplicates
9683 uidArr = new int[num];
9684 uidArr[0] = uidList[0];
9685 int di = 0;
9686 for (int i = 1; i < num; i++) {
9687 if (uidList[i-1] != uidList[i]) {
9688 uidArr[di++] = uidList[i];
9689 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009690 }
9691 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009692 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009693 // Process packages with valid entries.
9694 if (mediaStatus) {
9695 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009696 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009697 startCleaningPackages();
9698 } else {
9699 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009700 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009701 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009702 }
9703
9704 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009705 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009706 int size = pkgList.size();
9707 if (size > 0) {
9708 // Send broadcasts here
9709 Bundle extras = new Bundle();
9710 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9711 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009712 if (uidArr != null) {
9713 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9714 }
9715 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9716 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009717 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009718 }
9719 }
9720
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009721 /*
9722 * Look at potentially valid container ids from processCids
9723 * If package information doesn't match the one on record
9724 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009725 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009726 */
9727 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009728 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009729 ArrayList<String> pkgList = new ArrayList<String>();
9730 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009731 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009732 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009733 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009734 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9735 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009736 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009737 try {
9738 // Make sure there are no container errors first.
9739 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9740 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009741 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009742 " when installing from sdcard");
9743 continue;
9744 }
9745 // Check code path here.
9746 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009747 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009748 " does not match one in settings " + codePath);
9749 continue;
9750 }
9751 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009752 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009753 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009754 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009755 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9756 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009757 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009758 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009759 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009760 retCode = PackageManager.INSTALL_SUCCEEDED;
9761 pkgList.add(pkg.packageName);
9762 // Post process args
9763 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9764 }
9765 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009766 Slog.i(TAG, "Failed to install pkg from " +
9767 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009768 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009769 }
9770
9771 } finally {
9772 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9773 // Don't destroy container here. Wait till gc clears things up.
9774 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009775 }
9776 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009777 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009778 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009779 // If the platform SDK has changed since the last time we booted,
9780 // we need to re-grant app permission to catch any new ones that
9781 // appear. This is really a hack, and means that apps can in some
9782 // cases get permissions that the user didn't initially explicitly
9783 // allow... it would be nice to have some better way to handle
9784 // this situation.
9785 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9786 != mSdkVersion;
9787 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9788 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9789 + "; regranting permissions for external storage");
9790 mSettings.mExternalSdkPlatform = mSdkVersion;
9791
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009792 // Make sure group IDs have been assigned, and any permission
9793 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009794 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009795 // Persist settings
9796 mSettings.writeLP();
9797 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009798 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009799 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009800 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009801 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009802 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009803 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009804 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009805 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009806 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009807 if (removeCids != null) {
9808 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009809 if (cid.startsWith(mTempContainerPrefix)) {
9810 Log.i(TAG, "Destroying stale temporary container " + cid);
9811 PackageHelper.destroySdDir(cid);
9812 } else {
9813 Log.w(TAG, "Container " + cid + " is stale");
9814 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009815 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009816 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009817 }
9818
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009819 /*
9820 * Utility method to unload a list of specified containers
9821 */
9822 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9823 // Just unmount all valid containers.
9824 for (SdInstallArgs arg : cidArgs) {
9825 synchronized (mInstallLock) {
9826 arg.doPostDeleteLI(false);
9827 }
9828 }
9829 }
9830
9831 /*
9832 * Unload packages mounted on external media. This involves deleting
9833 * package data from internal structures, sending broadcasts about
9834 * diabled packages, gc'ing to free up references, unmounting all
9835 * secure containers corresponding to packages on external media, and
9836 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9837 * Please note that we always have to post this message if status has
9838 * been requested no matter what.
9839 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009840 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009841 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009842 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009843 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009844 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009845 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009846 for (SdInstallArgs args : keys) {
9847 String cid = args.cid;
9848 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009849 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009850 // Delete package internally
9851 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9852 synchronized (mInstallLock) {
9853 boolean res = deletePackageLI(pkgName, false,
9854 PackageManager.DONT_DELETE_DATA, outInfo);
9855 if (res) {
9856 pkgList.add(pkgName);
9857 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009858 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009859 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009860 }
9861 }
9862 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009863 // We have to absolutely send UPDATED_MEDIA_STATUS only
9864 // after confirming that all the receivers processed the ordered
9865 // broadcast when packages get disabled, force a gc to clean things up.
9866 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009867 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009868 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9869 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9870 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009871 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9872 reportStatus ? 1 : 0, 1, keys);
9873 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009874 }
9875 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009876 } else {
9877 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9878 reportStatus ? 1 : 0, -1, keys);
9879 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009880 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009881 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009882
9883 public void movePackage(final String packageName,
9884 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009885 mContext.enforceCallingOrSelfPermission(
9886 android.Manifest.permission.MOVE_PACKAGE, null);
9887 int returnCode = PackageManager.MOVE_SUCCEEDED;
9888 int currFlags = 0;
9889 int newFlags = 0;
9890 synchronized (mPackages) {
9891 PackageParser.Package pkg = mPackages.get(packageName);
9892 if (pkg == null) {
9893 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009894 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009895 // Disable moving fwd locked apps and system packages
9896 if (pkg.applicationInfo != null &&
9897 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9898 Slog.w(TAG, "Cannot move system application");
9899 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9900 } else if (pkg.applicationInfo != null &&
9901 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9902 Slog.w(TAG, "Cannot move forward locked app.");
9903 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009904 } else if (pkg.mOperationPending) {
9905 Slog.w(TAG, "Attempt to move package which has pending operations");
9906 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009907 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009908 // Find install location first
9909 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9910 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9911 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009912 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009913 } else {
9914 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9915 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9916 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
9917 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9918 if (newFlags == currFlags) {
9919 Slog.w(TAG, "No move required. Trying to move to same location");
9920 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9921 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009922 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009923 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9924 pkg.mOperationPending = true;
9925 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009926 }
9927 }
9928 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07009929 processPendingMove(new MoveParams(null, observer, 0, packageName), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009930 } else {
9931 Message msg = mHandler.obtainMessage(INIT_COPY);
9932 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9933 pkg.applicationInfo.publicSourceDir);
9934 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9935 packageName);
9936 msg.obj = mp;
9937 mHandler.sendMessage(msg);
9938 }
9939 }
9940 }
9941
9942 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9943 // Queue up an async operation since the package deletion may take a little while.
9944 mHandler.post(new Runnable() {
9945 public void run() {
9946 mHandler.removeCallbacks(this);
9947 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009948 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9949 int uidArr[] = null;
9950 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009951 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009952 PackageParser.Package pkg = mPackages.get(mp.packageName);
9953 if (pkg == null ) {
9954 Slog.w(TAG, " Package " + mp.packageName +
9955 " doesn't exist. Aborting move");
9956 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9957 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9958 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9959 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9960 " Aborting move and returning error");
9961 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9962 } else {
9963 uidArr = new int[] { pkg.applicationInfo.uid };
9964 pkgList = new ArrayList<String>();
9965 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009966 }
9967 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009968 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9969 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009970 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009971 // Update package code and resource paths
9972 synchronized (mInstallLock) {
9973 synchronized (mPackages) {
9974 PackageParser.Package pkg = mPackages.get(mp.packageName);
9975 // Recheck for package again.
9976 if (pkg == null ) {
9977 Slog.w(TAG, " Package " + mp.packageName +
9978 " doesn't exist. Aborting move");
9979 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9980 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9981 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9982 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9983 " Aborting move and returning error");
9984 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9985 } else {
9986 String oldCodePath = pkg.mPath;
9987 String newCodePath = mp.targetArgs.getCodePath();
9988 String newResPath = mp.targetArgs.getResourcePath();
9989 pkg.mPath = newCodePath;
9990 // Move dex files around
9991 if (moveDexFilesLI(pkg)
9992 != PackageManager.INSTALL_SUCCEEDED) {
9993 // Moving of dex files failed. Set
9994 // error code and abort move.
9995 pkg.mPath = pkg.mScanPath;
9996 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9997 } else {
9998 pkg.mScanPath = newCodePath;
9999 pkg.applicationInfo.sourceDir = newCodePath;
10000 pkg.applicationInfo.publicSourceDir = newResPath;
10001 PackageSetting ps = (PackageSetting) pkg.mExtras;
10002 ps.codePath = new File(pkg.applicationInfo.sourceDir);
10003 ps.codePathString = ps.codePath.getPath();
10004 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
10005 ps.resourcePathString = ps.resourcePath.getPath();
10006 // Set the application info flag correctly.
10007 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
10008 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10009 } else {
10010 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10011 }
10012 ps.setFlags(pkg.applicationInfo.flags);
10013 mAppDirs.remove(oldCodePath);
10014 mAppDirs.put(newCodePath, pkg);
10015 // Persist settings
10016 mSettings.writeLP();
10017 }
10018 }
10019 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010020 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -070010021 // Send resources available broadcast
10022 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010023 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010024 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010025 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010026 // Clean up failed installation
10027 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010028 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010029 }
10030 } else {
10031 // Force a gc to clear things up.
10032 Runtime.getRuntime().gc();
10033 // Delete older code
10034 synchronized (mInstallLock) {
10035 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010036 }
10037 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010038
10039 // Allow more operations on this file if we didn't fail because
10040 // an operation was already pending for this package.
10041 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
10042 synchronized (mPackages) {
10043 PackageParser.Package pkg = mPackages.get(mp.packageName);
10044 if (pkg != null) {
10045 pkg.mOperationPending = false;
10046 }
10047 }
10048 }
10049
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010050 IPackageMoveObserver observer = mp.observer;
10051 if (observer != null) {
10052 try {
10053 observer.packageMoved(mp.packageName, returnCode);
10054 } catch (RemoteException e) {
10055 Log.i(TAG, "Observer no longer exists.");
10056 }
10057 }
10058 }
10059 });
10060 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070010061
10062 public boolean setInstallLocation(int loc) {
10063 mContext.enforceCallingOrSelfPermission(
10064 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
10065 if (getInstallLocation() == loc) {
10066 return true;
10067 }
10068 if (loc == PackageHelper.APP_INSTALL_AUTO ||
10069 loc == PackageHelper.APP_INSTALL_INTERNAL ||
10070 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
10071 android.provider.Settings.System.putInt(mContext.getContentResolver(),
10072 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
10073 return true;
10074 }
10075 return false;
10076 }
10077
10078 public int getInstallLocation() {
10079 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
10080 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
10081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010082}